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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
mozilla-mobile/firefox-ios | Client/Frontend/Intro/OnboardingCardViewModel.swift | 2 | 2535 | // This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/
import Foundation
protocol OnboardingCardProtocol {
var cardType: IntroViewModel.InformationCards { get set }
var infoModel: OnboardingModelProtocol { get }
var shouldShowDescriptionBold: Bool { get }
func sendCardViewTelemetry()
func sendTelemetryButton(isPrimaryAction: Bool)
}
struct OnboardingCardViewModel: OnboardingCardProtocol {
var cardType: IntroViewModel.InformationCards
var infoModel: OnboardingModelProtocol
var shouldShowDescriptionBold: Bool
init(cardType: IntroViewModel.InformationCards,
infoModel: OnboardingModelProtocol,
isv106Version: Bool) {
self.cardType = cardType
self.infoModel = infoModel
self.shouldShowDescriptionBold = cardType == .welcome && !isv106Version
}
func sendCardViewTelemetry() {
let extra = [TelemetryWrapper.EventExtraKey.cardType.rawValue: cardType.telemetryValue]
let eventObject: TelemetryWrapper.EventObject = cardType.isOnboardingScreen ?
. onboardingCardView : .upgradeOnboardingCardView
TelemetryWrapper.recordEvent(category: .action,
method: .view,
object: eventObject,
value: nil,
extras: extra)
}
func sendTelemetryButton(isPrimaryAction: Bool) {
let eventObject: TelemetryWrapper.EventObject
let extra = [TelemetryWrapper.EventExtraKey.cardType.rawValue: cardType.telemetryValue]
switch (isPrimaryAction, cardType.isOnboardingScreen) {
case (true, true):
eventObject = TelemetryWrapper.EventObject.onboardingPrimaryButton
case (false, true):
eventObject = TelemetryWrapper.EventObject.onboardingSecondaryButton
case (true, false):
eventObject = TelemetryWrapper.EventObject.upgradeOnboardingPrimaryButton
case (false, false):
eventObject = TelemetryWrapper.EventObject.upgradeOnboardingSecondaryButton
}
TelemetryWrapper.recordEvent(category: .action,
method: .tap,
object: eventObject,
value: nil,
extras: extra)
}
}
| mpl-2.0 | ef2f14716be5abce627463f962d17ba8 | 39.238095 | 95 | 0.642604 | 5.547046 | false | false | false | false |
1271284056/JDPhotoBrowser | JDPhotoBrowser/Classes/JDPhotoBrowserAnimator.swift | 1 | 6971 | //
// JDPhotoBrowserAnimator
// Created by 张江东 on 2017/4/12.
// Copyright © 2017年 58kuaipai. All rights reserved.
import UIKit
class JDPhotoBrowserAnimator: NSObject {
var imageRect = CGRect(x: 0 , y:0, width: kJDScreenWidth , height: kJDScreenHeight )
var isPresented : Bool = false
var sourceImageView: UIImageView? // 来源view
var endImageView: UIImageView? // 消失时候view
var currentPage: Int = 0
var preSnapView : UIView?
var isAniDone : Bool = false
var superVc: JDPhotoBrowser?
//加载进度提示框
private lazy var progressView : UIActivityIndicatorView = {
let loadVi = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.whiteLarge)
loadVi.startAnimating()
return loadVi
}()
var isImageDone: Bool?{
didSet{
if isImageDone == true && self.isAniDone == true{
progressView.removeFromSuperview()
self.preSnapView?.removeFromSuperview()
}else{
if self.isAniDone == true {
progressView.center = CGPoint(x: imageRect.size.width/2, y: imageRect.size.height/2)
self.preSnapView?.addSubview(progressView)
// print("加载中")
}
}
}
}
}
extension JDPhotoBrowserAnimator : UIViewControllerTransitioningDelegate{
// isPresented 调用的动画
func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
isPresented = true
return self
}
//消失时候调用的动画
func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
isPresented = false
return self
}
}
extension JDPhotoBrowserAnimator : UIViewControllerAnimatedTransitioning{
//动画时间
func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
return 0.3
}
//动画方式
func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
isPresented ? animationForPresentedView(transitionContext) : animationForDismissView(transitionContext)
}
//弹出动画
func animationForPresentedView(_ transitionContext: UIViewControllerContextTransitioning){
//取出下一个 view 浏览器
let presentedView = transitionContext.view(forKey: UITransitionContextViewKey.to)!
transitionContext.containerView.addSubview(presentedView)
if sourceImageView == nil {
transitionContext.completeTransition(true)
return
}
let imgView = UIImageView()
imgView.image = sourceImageView?.image
let window = UIApplication.shared.keyWindow
imgView.frame = (sourceImageView?.convert((sourceImageView?.bounds)!, to: window))!
self.getImageSize()
let imgSize = imgView.image?.size
let imgW = imgSize?.width
let imgH = imgSize?.height
imgView.JDwidth = (sourceImageView?.JDwidth)!
imgView.JDheight = (sourceImageView?.JDwidth)!/imgW! * imgH!
let snapView = imgView.snapshotView(afterScreenUpdates: true)
//截图
snapView?.frame = imgView.frame
transitionContext.containerView.addSubview(snapView!)
presentedView.alpha = 0.0
transitionContext.containerView.backgroundColor = UIColor.black
let tap = UITapGestureRecognizer(target: self, action: #selector(snapViewTap(recognizer:)))
tap.numberOfTouchesRequired = 1
tap.numberOfTapsRequired = 1
snapView?.addGestureRecognizer(tap)
self.preSnapView = snapView
self.isAniDone = false
UIView.animate(withDuration:0.3 , animations: {
snapView?.frame = self.imageRect
}, completion: { (_) in
self.isAniDone = true
let presentedVc = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.to) as! JDPhotoBrowser
let indexPath = IndexPath(item: self.currentPage, section: 0)
guard presentedVc.collectionView1.cellForItem(at: indexPath) != nil else { return }
let cell = presentedVc.collectionView1.cellForItem(at: indexPath) as! JDPhotoBrowserCell
self.isImageDone = cell.isImageDone
presentedView.alpha = 1.0
transitionContext.containerView.backgroundColor = UIColor.clear
transitionContext.completeTransition(true)
})
}
//单击
@objc private func snapViewTap(recognizer: UITapGestureRecognizer){
self.superVc?.dismiss(animated: true, completion: nil)
}
//大图尺寸
func getImageSize(){
let imageSize = sourceImageView?.image?.size
let imageW = imageSize?.width
let imageH = imageSize?.height
let actualImageW = kJDScreenWidth
let actualImageH = actualImageW/imageW! * imageH!
imageRect = CGRect(x: 0, y: (kJDScreenHeight - actualImageH)/2, width: actualImageW, height: actualImageH)
}
//消失动画
func animationForDismissView(_ transitionContext: UIViewControllerContextTransitioning){
//上一级view
let dismissView = transitionContext.view(forKey: UITransitionContextViewKey.from)!
let dismissVc = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.from) as! JDPhotoBrowser
let indexPath = IndexPath(item: currentPage, section: 0)
if dismissVc.collectionView1.cellForItem(at: indexPath) == nil {
//currentPage快速滑动一直不变 最后销毁了
transitionContext.completeTransition(true)
return
}
let cell = dismissVc.collectionView1.cellForItem(at: indexPath) as! JDPhotoBrowserCell
let snapView = cell.backImg.snapshotView(afterScreenUpdates: true)
snapView?.frame = imageRect
transitionContext.containerView.addSubview(snapView!)
dismissView.removeFromSuperview()
UIView.animate(withDuration: 0.3, animations: {
if self.endImageView == nil{
snapView?.frame = self.imageRect
}else{
snapView?.frame = self.convertRect(for: self.endImageView!)
}
}, completion: { (_) in
snapView?.removeFromSuperview()
transitionContext.completeTransition(true)
})
}
fileprivate func convertRect(for view: UIView) -> CGRect! {
let rootView = UIApplication.shared.keyWindow?.rootViewController?.view
let rect = view.superview?.convert(view.frame, to: rootView)
return rect!
}
}
| mit | 5f1ec69be18df7da7d95d365fb56eaa1 | 37.235955 | 170 | 0.655451 | 5.393027 | false | false | false | false |
wordpress-mobile/WordPress-iOS | WordPress/Classes/ViewRelated/Pages/PageListViewController.swift | 1 | 47217 | import Foundation
import CocoaLumberjack
import WordPressShared
import WordPressFlux
import UIKit
class PageListViewController: AbstractPostListViewController, UIViewControllerRestoration {
private struct Constant {
struct Size {
static let pageSectionHeaderHeight = CGFloat(40.0)
static let pageCellEstimatedRowHeight = CGFloat(44.0)
static let pageCellWithTagEstimatedRowHeight = CGFloat(60.0)
static let pageListTableViewCellLeading = CGFloat(16.0)
}
struct Identifiers {
static let pagesViewControllerRestorationKey = "PagesViewControllerRestorationKey"
static let pageCellIdentifier = "PageCellIdentifier"
static let pageCellNibName = "PageListTableViewCell"
static let restorePageCellIdentifier = "RestorePageCellIdentifier"
static let restorePageCellNibName = "RestorePageTableViewCell"
static let currentPageListStatusFilterKey = "CurrentPageListStatusFilterKey"
}
struct Events {
static let source = "page_list"
static let pagePostType = "page"
}
}
fileprivate lazy var sectionFooterSeparatorView: UIView = {
let footer = UIView()
footer.backgroundColor = .neutral(.shade10)
return footer
}()
private lazy var _tableViewHandler: PageListTableViewHandler = {
let tableViewHandler = PageListTableViewHandler(tableView: self.tableView, blog: self.blog)
tableViewHandler.cacheRowHeights = false
tableViewHandler.delegate = self
tableViewHandler.listensForContentChanges = false
tableViewHandler.updateRowAnimation = .none
return tableViewHandler
}()
override var tableViewHandler: WPTableViewHandler {
get {
return _tableViewHandler
} set {
super.tableViewHandler = newValue
}
}
lazy var homepageSettingsService = {
return HomepageSettingsService(blog: blog, context: blog.managedObjectContext ?? ContextManager.shared.mainContext)
}()
private lazy var createButtonCoordinator: CreateButtonCoordinator = {
let action = PageAction(handler: { [weak self] in
self?.createPost()
}, source: Constant.Events.source)
return CreateButtonCoordinator(self, actions: [action], source: Constant.Events.source)
}()
// MARK: - GUI
@IBOutlet weak var filterTabBarTopConstraint: NSLayoutConstraint!
@IBOutlet weak var filterTabBariOS10TopConstraint: NSLayoutConstraint!
@IBOutlet weak var filterTabBarBottomConstraint: NSLayoutConstraint!
@IBOutlet weak var tableViewTopConstraint: NSLayoutConstraint!
// MARK: - Convenience constructors
@objc class func controllerWithBlog(_ blog: Blog) -> PageListViewController {
let storyBoard = UIStoryboard(name: "Pages", bundle: Bundle.main)
let controller = storyBoard.instantiateViewController(withIdentifier: "PageListViewController") as! PageListViewController
controller.blog = blog
controller.restorationClass = self
if QuickStartTourGuide.shared.isCurrentElement(.pages) {
controller.filterSettings.setFilterWithPostStatus(BasePost.Status.publish)
}
return controller
}
static func showForBlog(_ blog: Blog, from sourceController: UIViewController) {
let controller = PageListViewController.controllerWithBlog(blog)
controller.navigationItem.largeTitleDisplayMode = .never
sourceController.navigationController?.pushViewController(controller, animated: true)
QuickStartTourGuide.shared.visited(.pages)
}
// MARK: - UIViewControllerRestoration
class func viewController(withRestorationIdentifierPath identifierComponents: [String],
coder: NSCoder) -> UIViewController? {
let context = ContextManager.sharedInstance().mainContext
guard let blogID = coder.decodeObject(forKey: Constant.Identifiers.pagesViewControllerRestorationKey) as? String,
let objectURL = URL(string: blogID),
let objectID = context.persistentStoreCoordinator?.managedObjectID(forURIRepresentation: objectURL),
let restoredBlog = try? context.existingObject(with: objectID) as? Blog else {
return nil
}
return controllerWithBlog(restoredBlog)
}
// MARK: - UIStateRestoring
override func encodeRestorableState(with coder: NSCoder) {
let objectString = blog?.objectID.uriRepresentation().absoluteString
coder.encode(objectString, forKey: Constant.Identifiers.pagesViewControllerRestorationKey)
super.encodeRestorableState(with: coder)
}
// MARK: - UIViewController
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
super.refreshNoResultsViewController = { [weak self] noResultsViewController in
self?.handleRefreshNoResultsViewController(noResultsViewController)
}
super.tableViewController = (segue.destination as! UITableViewController)
}
override func viewDidLoad() {
super.viewDidLoad()
if QuickStartTourGuide.shared.isCurrentElement(.newPage) {
updateFilterWithPostStatus(.publish)
}
super.updateAndPerformFetchRequest()
title = NSLocalizedString("Pages", comment: "Title of the screen showing the list of pages for a blog.")
configureFilterBarTopConstraint()
createButtonCoordinator.add(to: view, trailingAnchor: view.safeAreaLayoutGuide.trailingAnchor, bottomAnchor: view.safeAreaLayoutGuide.bottomAnchor)
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
_tableViewHandler.status = filterSettings.currentPostListFilter().filterType
_tableViewHandler.refreshTableView()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
if traitCollection.horizontalSizeClass == .compact {
createButtonCoordinator.showCreateButton(for: blog)
}
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
QuickStartTourGuide.shared.endCurrentTour()
}
override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
super.traitCollectionDidChange(previousTraitCollection)
if traitCollection.horizontalSizeClass == .compact {
createButtonCoordinator.showCreateButton(for: blog)
} else {
createButtonCoordinator.hideCreateButton()
}
}
// MARK: - Configuration
private func configureFilterBarTopConstraint() {
filterTabBariOS10TopConstraint.isActive = false
}
override func configureTableView() {
tableView.accessibilityIdentifier = "PagesTable"
tableView.estimatedRowHeight = Constant.Size.pageCellEstimatedRowHeight
tableView.rowHeight = UITableView.automaticDimension
let bundle = Bundle.main
// Register the cells
let pageCellNib = UINib(nibName: Constant.Identifiers.pageCellNibName, bundle: bundle)
tableView.register(pageCellNib, forCellReuseIdentifier: Constant.Identifiers.pageCellIdentifier)
let restorePageCellNib = UINib(nibName: Constant.Identifiers.restorePageCellNibName, bundle: bundle)
tableView.register(restorePageCellNib, forCellReuseIdentifier: Constant.Identifiers.restorePageCellIdentifier)
WPStyleGuide.configureColors(view: view, tableView: tableView)
}
override func configureSearchController() {
super.configureSearchController()
tableView.tableHeaderView = searchController.searchBar
tableView.verticalScrollIndicatorInsets.top = searchController.searchBar.bounds.height
}
override func configureAuthorFilter() {
// Noop
}
override func configureFooterView() {
super.configureFooterView()
tableView.tableFooterView = UIView(frame: .zero)
}
fileprivate func beginRefreshingManually() {
guard let refreshControl = refreshControl else {
return
}
refreshControl.beginRefreshing()
tableView.setContentOffset(CGPoint(x: 0, y: tableView.contentOffset.y - refreshControl.frame.size.height), animated: true)
}
// MARK: - Sync Methods
override internal func postTypeToSync() -> PostServiceType {
return .page
}
override internal func lastSyncDate() -> Date? {
return blog?.lastPagesSync
}
override func selectedFilterDidChange(_ filterBar: FilterTabBar) {
filterSettings.setCurrentFilterIndex(filterBar.selectedIndex)
_tableViewHandler.status = filterSettings.currentPostListFilter().filterType
_tableViewHandler.refreshTableView()
super.selectedFilterDidChange(filterBar)
}
override func updateFilterWithPostStatus(_ status: BasePost.Status) {
filterSettings.setFilterWithPostStatus(status)
_tableViewHandler.status = filterSettings.currentPostListFilter().filterType
_tableViewHandler.refreshTableView()
super.updateFilterWithPostStatus(status)
}
override func updateAndPerformFetchRequest() {
super.updateAndPerformFetchRequest()
_tableViewHandler.refreshTableView()
}
override func syncPostsMatchingSearchText() {
guard let searchText = searchController.searchBar.text, !searchText.isEmpty() else {
return
}
postsSyncWithSearchDidBegin()
let author = filterSettings.shouldShowOnlyMyPosts() ? blogUserID() : nil
let postService = PostService(managedObjectContext: managedObjectContext())
let options = PostServiceSyncOptions()
options.statuses = filterSettings.availablePostListFilters().flatMap { $0.statuses.strings }
options.authorID = author
options.number = 20
options.purgesLocalSync = false
options.search = searchText
postService.syncPosts(
ofType: postTypeToSync(),
with: options,
for: blog,
success: { [weak self] posts in
self?.postsSyncWithSearchEnded()
}, failure: { [weak self] (error) in
self?.postsSyncWithSearchEnded()
}
)
}
override func sortDescriptorsForFetchRequest() -> [NSSortDescriptor] {
if !searchController.isActive {
return super.sortDescriptorsForFetchRequest()
}
let descriptor = NSSortDescriptor(key: BasePost.statusKeyPath, ascending: true)
return [descriptor]
}
override func updateForLocalPostsMatchingSearchText() {
guard searchController.isActive else {
hideNoResultsView()
return
}
_tableViewHandler.isSearching = true
updateAndPerformFetchRequest()
tableView.reloadData()
hideNoResultsView()
if let text = searchController.searchBar.text,
text.isEmpty ||
tableViewHandler.resultsController.fetchedObjects?.count == 0 {
showNoResultsView()
}
}
override func showNoResultsView() {
super.showNoResultsView()
if searchController.isActive {
noResultsViewController.view.frame = CGRect(x: 0.0,
y: searchController.searchBar.bounds.height,
width: tableView.frame.width,
height: max(tableView.frame.height, tableView.contentSize.height))
tableView.bringSubviewToFront(noResultsViewController.view)
}
}
override func syncContentEnded(_ syncHelper: WPContentSyncHelper) {
guard syncHelper.hasMoreContent else {
super.syncContentEnded(syncHelper)
return
}
}
// MARK: - Model Interaction
/// Retrieves the page object at the specified index path.
///
/// - Parameter indexPath: the index path of the page object to retrieve.
///
/// - Returns: the requested page.
///
fileprivate func pageAtIndexPath(_ indexPath: IndexPath) -> Page {
return _tableViewHandler.page(at: indexPath)
}
// MARK: - TableView Handler Delegate Methods
override func entityName() -> String {
return String(describing: Page.self)
}
override func predicateForFetchRequest() -> NSPredicate {
var predicates = [NSPredicate]()
if let blog = blog {
let basePredicate = NSPredicate(format: "blog = %@ && revision = nil", blog)
predicates.append(basePredicate)
}
let searchText = currentSearchTerm() ?? ""
let filterPredicate = searchController.isActive ? NSPredicate(format: "postTitle CONTAINS[cd] %@", searchText) : filterSettings.currentPostListFilter().predicateForFetchRequest
// If we have recently trashed posts, create an OR predicate to find posts matching the filter,
// or posts that were recently deleted.
if searchText.count == 0 && recentlyTrashedPostObjectIDs.count > 0 {
let trashedPredicate = NSPredicate(format: "SELF IN %@", recentlyTrashedPostObjectIDs)
predicates.append(NSCompoundPredicate(orPredicateWithSubpredicates: [filterPredicate, trashedPredicate]))
} else {
predicates.append(filterPredicate)
}
if searchText.count > 0 {
let searchPredicate = NSPredicate(format: "postTitle CONTAINS[cd] %@", searchText)
predicates.append(searchPredicate)
}
let predicate = NSCompoundPredicate(andPredicateWithSubpredicates: predicates)
return predicate
}
// MARK: - Table View Handling
func sectionNameKeyPath() -> String {
let sortField = filterSettings.currentPostListFilter().sortField
return Page.sectionIdentifier(dateKeyPath: sortField.keyPath)
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
guard _tableViewHandler.groupResults else {
return 0.0
}
return Constant.Size.pageSectionHeaderHeight
}
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
guard _tableViewHandler.groupResults else {
return UIView(frame: .zero)
}
let sectionInfo = _tableViewHandler.resultsController.sections?[section]
let nibName = String(describing: PageListSectionHeaderView.self)
let headerView = Bundle.main.loadNibNamed(nibName, owner: nil, options: nil)?.first as? PageListSectionHeaderView
if let sectionInfo = sectionInfo, let headerView = headerView {
headerView.setTitle(PostSearchHeader.title(forStatus: sectionInfo.name))
}
return headerView
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
let page = pageAtIndexPath(indexPath)
if page.isSiteHomepage {
tableView.reloadRows(at: [indexPath], with: .automatic)
} else if page.isSitePostsPage {
showSitePostPageUneditableNotice()
return
} else {
QuickStartTourGuide.shared.endCurrentTour()
tableView.reloadData()
}
guard page.status != .trash else {
return
}
editPage(page)
}
private func showSitePostPageUneditableNotice() {
let sitePostPageUneditableNotice = NSLocalizedString("The content of your latest posts page is automatically generated and cannot be edited.", comment: "Message informing the user that posts page cannot be edited")
let notice = Notice(title: sitePostPageUneditableNotice, feedbackType: .warning)
ActionDispatcher.global.dispatch(NoticeAction.post(notice))
}
@objc func tableView(_ tableView: UITableView, cellForRowAtIndexPath indexPath: IndexPath) -> UITableViewCell {
if let windowlessCell = dequeCellForWindowlessLoadingIfNeeded(tableView) {
return windowlessCell
}
let page = pageAtIndexPath(indexPath)
let identifier = cellIdentifierForPage(page)
let cell = tableView.dequeueReusableCell(withIdentifier: identifier, for: indexPath)
configureCell(cell, at: indexPath)
return cell
}
override func configureCell(_ cell: UITableViewCell, at indexPath: IndexPath) {
guard let cell = cell as? BasePageListCell else {
preconditionFailure("The cell should be of class \(String(describing: BasePageListCell.self))")
}
cell.accessoryType = .none
let page = pageAtIndexPath(indexPath)
let filterType = filterSettings.currentPostListFilter().filterType
if cell.reuseIdentifier == Constant.Identifiers.pageCellIdentifier {
cell.indentationWidth = _tableViewHandler.isSearching ? 0.0 : Constant.Size.pageListTableViewCellLeading
cell.indentationLevel = filterType != .published ? 0 : page.hierarchyIndex
cell.onAction = { [weak self] cell, button, page in
self?.handleMenuAction(fromCell: cell, fromButton: button, forPage: page)
}
} else if cell.reuseIdentifier == Constant.Identifiers.restorePageCellIdentifier {
cell.selectionStyle = .none
cell.onAction = { [weak self] cell, _, page in
self?.handleRestoreAction(fromCell: cell, forPage: page)
}
}
cell.contentView.backgroundColor = UIColor.listForeground
cell.configureCell(page)
}
fileprivate func cellIdentifierForPage(_ page: Page) -> String {
var identifier: String
if recentlyTrashedPostObjectIDs.contains(page.objectID) == true && filterSettings.currentPostListFilter().filterType != .trashed {
identifier = Constant.Identifiers.restorePageCellIdentifier
} else {
identifier = Constant.Identifiers.pageCellIdentifier
}
return identifier
}
// MARK: - Post Actions
override func createPost() {
WPAppAnalytics.track(.editorCreatedPost, withProperties: [WPAppAnalyticsKeyTapSource: Constant.Events.source, WPAppAnalyticsKeyPostType: Constant.Events.pagePostType], with: blog)
PageCoordinator.showLayoutPickerIfNeeded(from: self, forBlog: blog) { [weak self] (selectedLayout) in
self?.createPage(selectedLayout)
}
}
private func createPage(_ starterLayout: PageTemplateLayout?) {
let editorViewController = EditPageViewController(blog: blog, postTitle: starterLayout?.title, content: starterLayout?.content, appliedTemplate: starterLayout?.slug)
present(editorViewController, animated: false)
QuickStartTourGuide.shared.visited(.newPage)
}
fileprivate func editPage(_ page: Page) {
guard !PostCoordinator.shared.isUploading(post: page) else {
presentAlertForPageBeingUploaded()
return
}
WPAppAnalytics.track(.postListEditAction, withProperties: propertiesForAnalytics(), with: page)
let editorViewController = EditPageViewController(page: page)
present(editorViewController, animated: false)
}
fileprivate func copyPage(_ page: Page) {
// Analytics
WPAnalytics.track(.postListDuplicateAction, withProperties: propertiesForAnalytics())
// Copy Page
let newPage = page.blog.createDraftPage()
newPage.postTitle = page.postTitle
newPage.content = page.content
// Open Editor
let editorViewController = EditPageViewController(page: newPage)
present(editorViewController, animated: false)
}
fileprivate func copyLink(_ page: Page) {
let pasteboard = UIPasteboard.general
guard let link = page.permaLink else { return }
pasteboard.string = link as String
let noticeTitle = NSLocalizedString("Link Copied to Clipboard", comment: "Link copied to clipboard notice title")
let notice = Notice(title: noticeTitle, feedbackType: .success)
ActionDispatcher.dispatch(NoticeAction.dismiss) // Dismiss any old notices
ActionDispatcher.dispatch(NoticeAction.post(notice))
}
fileprivate func retryPage(_ apost: AbstractPost) {
PostCoordinator.shared.save(apost)
}
// MARK: - Alert
func presentAlertForPageBeingUploaded() {
let message = NSLocalizedString("This page is currently uploading. It won't take long – try again soon and you'll be able to edit it.", comment: "Prompts the user that the page is being uploaded and cannot be edited while that process is ongoing.")
let alertCancel = NSLocalizedString("OK", comment: "Title of an OK button. Pressing the button acknowledges and dismisses a prompt.")
let alertController = UIAlertController(title: nil, message: message, preferredStyle: .alert)
alertController.addCancelActionWithTitle(alertCancel, handler: nil)
alertController.presentFromRootViewController()
}
fileprivate func draftPage(_ apost: AbstractPost, at indexPath: IndexPath?) {
WPAnalytics.track(.postListDraftAction, withProperties: propertiesForAnalytics())
let previousStatus = apost.status
apost.status = .draft
let contextManager = ContextManager.sharedInstance()
let postService = PostService(managedObjectContext: contextManager.mainContext)
postService.uploadPost(apost, success: { [weak self] _ in
DispatchQueue.main.async {
self?._tableViewHandler.refreshTableView(at: indexPath)
}
}) { [weak self] (error) in
apost.status = previousStatus
if let strongSelf = self {
contextManager.save(strongSelf.managedObjectContext())
}
WPError.showXMLRPCErrorAlert(error)
}
}
override func promptThatPostRestoredToFilter(_ filter: PostListFilter) {
var message = NSLocalizedString("Page Restored to Drafts", comment: "Prompts the user that a restored page was moved to the drafts list.")
switch filter.filterType {
case .published:
message = NSLocalizedString("Page Restored to Published", comment: "Prompts the user that a restored page was moved to the published list.")
break
case .scheduled:
message = NSLocalizedString("Page Restored to Scheduled", comment: "Prompts the user that a restored page was moved to the scheduled list.")
break
default:
break
}
let alertCancel = NSLocalizedString("OK", comment: "Title of an OK button. Pressing the button acknowledges and dismisses a prompt.")
let alertController = UIAlertController(title: nil, message: message, preferredStyle: .alert)
alertController.addCancelActionWithTitle(alertCancel, handler: nil)
alertController.presentFromRootViewController()
}
// MARK: - Cell Action Handling
fileprivate func handleMenuAction(fromCell cell: UITableViewCell, fromButton button: UIButton, forPage page: AbstractPost) {
let objectID = page.objectID
let retryButtonTitle = NSLocalizedString("Retry", comment: "Label for a button that attempts to re-upload a page that previously failed to upload.")
let viewButtonTitle = NSLocalizedString("View", comment: "Label for a button that opens the page when tapped.")
let draftButtonTitle = NSLocalizedString("Move to Draft", comment: "Label for a button that moves a page to the draft folder")
let publishButtonTitle = NSLocalizedString("Publish Immediately", comment: "Label for a button that moves a page to the published folder, publishing with the current date/time.")
let trashButtonTitle = NSLocalizedString("Move to Trash", comment: "Label for a button that moves a page to the trash folder")
let cancelButtonTitle = NSLocalizedString("Cancel", comment: "Label for a cancel button")
let deleteButtonTitle = NSLocalizedString("Delete Permanently", comment: "Label for a button permanently deletes a page.")
let alertController = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
alertController.addCancelActionWithTitle(cancelButtonTitle, handler: nil)
let indexPath = tableView.indexPath(for: cell)
let filter = filterSettings.currentPostListFilter().filterType
let isHomepage = ((page as? Page)?.isSiteHomepage ?? false)
if filter == .trashed {
alertController.addActionWithTitle(draftButtonTitle, style: .default, handler: { [weak self] (action) in
guard let strongSelf = self,
let page = strongSelf.pageForObjectID(objectID) else {
return
}
strongSelf.draftPage(page, at: indexPath)
})
alertController.addActionWithTitle(deleteButtonTitle, style: .destructive, handler: { [weak self] (action) in
guard let strongSelf = self,
let page = strongSelf.pageForObjectID(objectID) else {
return
}
strongSelf.handleTrashPage(page)
})
} else if filter == .published {
if page.isFailed {
alertController.addActionWithTitle(retryButtonTitle, style: .default, handler: { [weak self] (action) in
guard let strongSelf = self,
let page = strongSelf.pageForObjectID(objectID) else {
return
}
strongSelf.retryPage(page)
})
} else {
addEditAction(to: alertController, for: page)
alertController.addActionWithTitle(viewButtonTitle, style: .default, handler: { [weak self] (action) in
guard let strongSelf = self,
let page = strongSelf.pageForObjectID(objectID) else {
return
}
strongSelf.viewPost(page)
})
addSetParentAction(to: alertController, for: page, at: indexPath)
addSetHomepageAction(to: alertController, for: page, at: indexPath)
addSetPostsPageAction(to: alertController, for: page, at: indexPath)
addDuplicateAction(to: alertController, for: page)
if !isHomepage {
alertController.addActionWithTitle(draftButtonTitle, style: .default, handler: { [weak self] (action) in
guard let strongSelf = self,
let page = strongSelf.pageForObjectID(objectID) else {
return
}
strongSelf.draftPage(page, at: indexPath)
})
}
}
addCopyLinkAction(to: alertController, for: page)
if !isHomepage {
alertController.addActionWithTitle(trashButtonTitle, style: .destructive, handler: { [weak self] (action) in
guard let strongSelf = self,
let page = strongSelf.pageForObjectID(objectID) else {
return
}
strongSelf.handleTrashPage(page)
})
}
} else {
if page.isFailed {
alertController.addActionWithTitle(retryButtonTitle, style: .default, handler: { [weak self] (action) in
guard let strongSelf = self,
let page = strongSelf.pageForObjectID(objectID) else {
return
}
strongSelf.retryPage(page)
})
} else {
addEditAction(to: alertController, for: page)
alertController.addActionWithTitle(viewButtonTitle, style: .default, handler: { [weak self] (action) in
guard let strongSelf = self,
let page = strongSelf.pageForObjectID(objectID) else {
return
}
strongSelf.viewPost(page)
})
addSetParentAction(to: alertController, for: page, at: indexPath)
addDuplicateAction(to: alertController, for: page)
alertController.addActionWithTitle(publishButtonTitle, style: .default, handler: { [weak self] (action) in
guard let strongSelf = self,
let page = strongSelf.pageForObjectID(objectID) else {
return
}
strongSelf.publishPost(page)
})
}
addCopyLinkAction(to: alertController, for: page)
alertController.addActionWithTitle(trashButtonTitle, style: .destructive, handler: { [weak self] (action) in
guard let strongSelf = self,
let page = strongSelf.pageForObjectID(objectID) else {
return
}
strongSelf.handleTrashPage(page)
})
}
WPAnalytics.track(.postListOpenedCellMenu, withProperties: propertiesForAnalytics())
alertController.modalPresentationStyle = .popover
present(alertController, animated: true)
if let presentationController = alertController.popoverPresentationController {
presentationController.permittedArrowDirections = .any
presentationController.sourceView = button
presentationController.sourceRect = button.bounds
}
}
override func deletePost(_ apost: AbstractPost) {
super.deletePost(apost)
}
private func addEditAction(to controller: UIAlertController, for page: AbstractPost) {
guard let page = page as? Page else { return }
if page.status == .trash || page.isSitePostsPage {
return
}
let buttonTitle = NSLocalizedString("Edit", comment: "Label for a button that opens the Edit Page view controller")
controller.addActionWithTitle(buttonTitle, style: .default, handler: { [weak self] _ in
if let page = self?.pageForObjectID(page.objectID) {
self?.editPage(page)
}
})
}
private func addDuplicateAction(to controller: UIAlertController, for page: AbstractPost) {
if page.status != .publish && page.status != .draft {
return
}
let buttonTitle = NSLocalizedString("Duplicate", comment: "Label for page duplicate option. Tapping creates a copy of the page.")
controller.addActionWithTitle(buttonTitle, style: .default, handler: { [weak self] _ in
if let page = self?.pageForObjectID(page.objectID) {
self?.copyPage(page)
}
})
}
private func addCopyLinkAction(to controller: UIAlertController, for page: AbstractPost) {
let buttonTitle = NSLocalizedString("Copy Link", comment: "Label for page copy link. Tapping copy the url of page")
controller.addActionWithTitle(buttonTitle, style: .default) { [weak self] _ in
if let page = self?.pageForObjectID(page.objectID) {
self?.copyLink(page)
}
}
}
private func addSetParentAction(to controller: UIAlertController, for page: AbstractPost, at index: IndexPath?) {
/// This button is disabled for trashed pages
//
if page.status == .trash {
return
}
let objectID = page.objectID
let setParentButtonTitle = NSLocalizedString("Set Parent", comment: "Label for a button that opens the Set Parent options view controller")
controller.addActionWithTitle(setParentButtonTitle, style: .default, handler: { [weak self] _ in
if let page = self?.pageForObjectID(objectID) {
self?.setParent(for: page, at: index)
}
})
}
private func setParent(for page: Page, at index: IndexPath?) {
guard let index = index else {
return
}
let selectedPage = pageAtIndexPath(index)
let newIndex = _tableViewHandler.index(for: selectedPage)
let pages = _tableViewHandler.removePage(from: newIndex)
let parentPageNavigationController = ParentPageSettingsViewController.navigationController(with: pages, selectedPage: selectedPage, onClose: { [weak self] in
self?._tableViewHandler.isSearching = false
self?._tableViewHandler.refreshTableView(at: index)
}, onSuccess: { [weak self] in
self?.handleSetParentSuccess()
} )
present(parentPageNavigationController, animated: true)
}
private func handleSetParentSuccess() {
let setParentSuccefullyNotice = NSLocalizedString("Parent page successfully updated.", comment: "Message informing the user that their pages parent has been set successfully")
let notice = Notice(title: setParentSuccefullyNotice, feedbackType: .success)
ActionDispatcher.global.dispatch(NoticeAction.post(notice))
}
fileprivate func pageForObjectID(_ objectID: NSManagedObjectID) -> Page? {
var pageManagedOjbect: NSManagedObject
do {
pageManagedOjbect = try managedObjectContext().existingObject(with: objectID)
} catch let error as NSError {
DDLogError("\(NSStringFromClass(type(of: self))), \(#function), \(error)")
return nil
} catch _ {
DDLogError("\(NSStringFromClass(type(of: self))), \(#function), Could not find Page with ID \(objectID)")
return nil
}
let page = pageManagedOjbect as? Page
return page
}
fileprivate func handleRestoreAction(fromCell cell: UITableViewCell, forPage page: AbstractPost) {
restorePost(page) { [weak self] in
self?._tableViewHandler.refreshTableView(at: self?.tableView.indexPath(for: cell))
}
}
private func addSetHomepageAction(to controller: UIAlertController, for page: AbstractPost, at index: IndexPath?) {
let objectID = page.objectID
/// This button is enabled if
/// - Page is not trashed
/// - The site's homepage type is .page
/// - The page isn't currently the homepage
//
guard page.status != .trash,
let homepageType = blog.homepageType,
homepageType == .page,
let page = pageForObjectID(objectID),
page.isSiteHomepage == false else {
return
}
let setHomepageButtonTitle = NSLocalizedString("Set as Homepage", comment: "Label for a button that sets the selected page as the site's Homepage")
controller.addActionWithTitle(setHomepageButtonTitle, style: .default, handler: { [weak self] _ in
if let pageID = page.postID?.intValue {
self?.beginRefreshingManually()
WPAnalytics.track(.postListSetHomePageAction)
self?.homepageSettingsService?.setHomepageType(.page,
homePageID: pageID, success: {
self?.refreshAndReload()
self?.handleHomepageSettingsSuccess()
}, failure: { error in
self?.refreshControl?.endRefreshing()
self?.handleHomepageSettingsFailure()
})
}
})
}
private func addSetPostsPageAction(to controller: UIAlertController, for page: AbstractPost, at index: IndexPath?) {
let objectID = page.objectID
/// This button is enabled if
/// - Page is not trashed
/// - The site's homepage type is .page
/// - The page isn't currently the posts page
//
guard page.status != .trash,
let homepageType = blog.homepageType,
homepageType == .page,
let page = pageForObjectID(objectID),
page.isSitePostsPage == false else {
return
}
let setPostsPageButtonTitle = NSLocalizedString("Set as Posts Page", comment: "Label for a button that sets the selected page as the site's Posts page")
controller.addActionWithTitle(setPostsPageButtonTitle, style: .default, handler: { [weak self] _ in
if let pageID = page.postID?.intValue {
self?.beginRefreshingManually()
WPAnalytics.track(.postListSetAsPostsPageAction)
self?.homepageSettingsService?.setHomepageType(.page,
withPostsPageID: pageID, success: {
self?.refreshAndReload()
self?.handleHomepagePostsPageSettingsSuccess()
}, failure: { error in
self?.refreshControl?.endRefreshing()
self?.handleHomepageSettingsFailure()
})
}
})
}
private func handleHomepageSettingsSuccess() {
let notice = Notice(title: HomepageSettingsText.updateHomepageSuccessTitle, feedbackType: .success)
ActionDispatcher.global.dispatch(NoticeAction.post(notice))
}
private func handleHomepagePostsPageSettingsSuccess() {
let notice = Notice(title: HomepageSettingsText.updatePostsPageSuccessTitle, feedbackType: .success)
ActionDispatcher.global.dispatch(NoticeAction.post(notice))
}
private func handleHomepageSettingsFailure() {
let notice = Notice(title: HomepageSettingsText.updateErrorTitle, message: HomepageSettingsText.updateErrorMessage, feedbackType: .error)
ActionDispatcher.global.dispatch(NoticeAction.post(notice))
}
private func handleTrashPage(_ post: AbstractPost) {
guard ReachabilityUtils.isInternetReachable() else {
let offlineMessage = NSLocalizedString("Unable to trash pages while offline. Please try again later.", comment: "Message that appears when a user tries to trash a page while their device is offline.")
ReachabilityUtils.showNoInternetConnectionNotice(message: offlineMessage)
return
}
let cancelText = NSLocalizedString("Cancel", comment: "Cancels an Action")
let deleteText: String
let messageText: String
let titleText: String
if post.status == .trash {
deleteText = NSLocalizedString("Delete Permanently", comment: "Delete option in the confirmation alert when deleting a page from the trash.")
titleText = NSLocalizedString("Delete Permanently?", comment: "Title of the confirmation alert when deleting a page from the trash.")
messageText = NSLocalizedString("Are you sure you want to permanently delete this page?", comment: "Message of the confirmation alert when deleting a page from the trash.")
} else {
deleteText = NSLocalizedString("Move to Trash", comment: "Trash option in the trash page confirmation alert.")
titleText = NSLocalizedString("Trash this page?", comment: "Title of the trash page confirmation alert.")
messageText = NSLocalizedString("Are you sure you want to trash this page?", comment: "Message of the trash page confirmation alert.")
}
let alertController = UIAlertController(title: titleText, message: messageText, preferredStyle: .alert)
alertController.addCancelActionWithTitle(cancelText)
alertController.addDestructiveActionWithTitle(deleteText) { [weak self] action in
self?.deletePost(post)
}
alertController.presentFromRootViewController()
}
// MARK: - UISearchControllerDelegate
override func willPresentSearchController(_ searchController: UISearchController) {
super.willPresentSearchController(searchController)
filterTabBar.alpha = WPAlphaZero
tableView.contentInset.top = -searchController.searchBar.bounds.height
}
override func updateSearchResults(for searchController: UISearchController) {
super.updateSearchResults(for: searchController)
}
override func willDismissSearchController(_ searchController: UISearchController) {
_tableViewHandler.isSearching = false
_tableViewHandler.refreshTableView()
super.willDismissSearchController(searchController)
}
func didPresentSearchController(_ searchController: UISearchController) {
tableView.verticalScrollIndicatorInsets.top = searchController.searchBar.bounds.height + searchController.searchBar.frame.origin.y - view.safeAreaInsets.top
}
func didDismissSearchController(_ searchController: UISearchController) {
UIView.animate(withDuration: Animations.searchDismissDuration, delay: 0, options: .curveLinear, animations: {
self.filterTabBar.alpha = WPAlphaFull
}) { _ in
self.hideNoResultsView()
}
}
enum Animations {
static let searchDismissDuration: TimeInterval = 0.3
}
// MARK: - NetworkAwareUI
override func noConnectionMessage() -> String {
return NSLocalizedString("No internet connection. Some pages may be unavailable while offline.",
comment: "Error message shown when the user is browsing Site Pages without an internet connection.")
}
struct HomepageSettingsText {
static let updateErrorTitle = NSLocalizedString("Unable to update homepage settings", comment: "Error informing the user that their homepage settings could not be updated")
static let updateErrorMessage = NSLocalizedString("Please try again later.", comment: "Prompt for the user to retry a failed action again later")
static let updateHomepageSuccessTitle = NSLocalizedString("Homepage successfully updated", comment: "Message informing the user that their static homepage page was set successfully")
static let updatePostsPageSuccessTitle = NSLocalizedString("Posts page successfully updated", comment: "Message informing the user that their static homepage for posts was set successfully")
}
}
// MARK: - No Results Handling
private extension PageListViewController {
func handleRefreshNoResultsViewController(_ noResultsViewController: NoResultsViewController) {
guard connectionAvailable() else {
noResultsViewController.configure(title: "", noConnectionTitle: NoResultsText.noConnectionTitle, buttonTitle: NoResultsText.buttonTitle, subtitle: nil, noConnectionSubtitle: NoResultsText.noConnectionSubtitle, attributedSubtitle: nil, attributedSubtitleConfiguration: nil, image: nil, subtitleImage: nil, accessoryView: nil)
return
}
if searchController.isActive {
if currentSearchTerm()?.count == 0 {
noResultsViewController.configureForNoSearchResults(title: NoResultsText.searchPages)
} else {
noResultsViewController.configureForNoSearchResults(title: noResultsTitle())
}
} else {
let accessoryView = syncHelper.isSyncing ? NoResultsViewController.loadingAccessoryView() : nil
noResultsViewController.configure(title: noResultsTitle(),
buttonTitle: noResultsButtonTitle(),
image: noResultsImageName,
accessoryView: accessoryView)
}
}
var noResultsImageName: String {
return "pages-no-results"
}
func noResultsButtonTitle() -> String? {
if syncHelper.isSyncing == true || isSearching() {
return nil
}
let filterType = filterSettings.currentPostListFilter().filterType
return filterType == .trashed ? nil : NoResultsText.buttonTitle
}
func noResultsTitle() -> String {
if syncHelper.isSyncing == true {
return NoResultsText.fetchingTitle
}
if isSearching() {
return NoResultsText.noMatchesTitle
}
return noResultsFilteredTitle()
}
func noResultsFilteredTitle() -> String {
let filterType = filterSettings.currentPostListFilter().filterType
switch filterType {
case .draft:
return NoResultsText.noDraftsTitle
case .scheduled:
return NoResultsText.noScheduledTitle
case .trashed:
return NoResultsText.noTrashedTitle
case .published:
return NoResultsText.noPublishedTitle
}
}
struct NoResultsText {
static let buttonTitle = NSLocalizedString("Create Page", comment: "Button title, encourages users to create their first page on their blog.")
static let fetchingTitle = NSLocalizedString("Fetching pages...", comment: "A brief prompt shown when the reader is empty, letting the user know the app is currently fetching new pages.")
static let noMatchesTitle = NSLocalizedString("No pages matching your search", comment: "Displayed when the user is searching the pages list and there are no matching pages")
static let noDraftsTitle = NSLocalizedString("You don't have any draft pages", comment: "Displayed when the user views drafts in the pages list and there are no pages")
static let noScheduledTitle = NSLocalizedString("You don't have any scheduled pages", comment: "Displayed when the user views scheduled pages in the pages list and there are no pages")
static let noTrashedTitle = NSLocalizedString("You don't have any trashed pages", comment: "Displayed when the user views trashed in the pages list and there are no pages")
static let noPublishedTitle = NSLocalizedString("You haven't published any pages yet", comment: "Displayed when the user views published pages in the pages list and there are no pages")
static let searchPages = NSLocalizedString("Search pages", comment: "Text displayed when the search controller will be presented")
static let noConnectionTitle: String = NSLocalizedString("Unable to load pages right now.", comment: "Title for No results full page screen displayedfrom pages list when there is no connection")
static let noConnectionSubtitle: String = NSLocalizedString("Check your network connection and try again. Or draft a page.", comment: "Subtitle for No results full page screen displayed from pages list when there is no connection")
}
}
| gpl-2.0 | b124a1de84b0fb388795d918e4bdd590 | 41.689873 | 338 | 0.657461 | 5.557975 | false | false | false | false |
KevinCoble/AIToolbox | AIToolbox/DeepChannel.swift | 1 | 11733 | //
// DeepChannel.swift
// AIToolbox
//
// Created by Kevin Coble on 6/25/16.
// Copyright © 2016 Kevin Coble. All rights reserved.
//
import Foundation
public struct DeepChannelSize {
public let numDimensions : Int
public var dimensions : [Int]
public init(dimensionCount: Int, dimensionValues: [Int]) {
numDimensions = dimensionCount
dimensions = dimensionValues
}
public var totalSize: Int {
get {
var result = 1
for i in 0..<numDimensions {
result *= dimensions[i]
}
return result
}
}
public func asString() ->String
{
var result = "\(numDimensions)D - ["
if (numDimensions > 0) { result += "\(dimensions[0])" }
if (numDimensions > 1) {
for i in 1..<numDimensions {
result += ", \(dimensions[i])"
}
}
result += "]"
return result
}
/// Function to determine if another input of a specified size can be added to an input of this size
public func canAddInput(ofSize: DeepChannelSize) -> Bool
{
// All but the last dimension must match
if (abs(numDimensions - ofSize.numDimensions) > 1) { return false }
var numMatchingDimensions = numDimensions
if (numDimensions < ofSize.numDimensions) { numMatchingDimensions = ofSize.numDimensions }
if (numDimensions != ofSize.numDimensions) { numMatchingDimensions -= 1 }
let ourDimensionsExtended = dimensions + [1, 1, 1]
let theirDimensionsExtended = ofSize.dimensions + [1, 1, 1]
for index in 0..<numMatchingDimensions {
if ourDimensionsExtended[index] != theirDimensionsExtended[index] { return false }
}
return true
}
}
/// Class for a single channel of a deep layer
/// A deep channel manages a network topology for a single data-stream within a deep layer
/// It contains an ordered array of 'network operators' that manipulate the channel data (convolutions, poolings, feedforward nets, etc.)
final public class DeepChannel : MLPersistence
{
public let idString : String // The string ID for the channel. i.e. "red component"
public private(set) var sourceChannelIDs : [String] // ID's of the channels that are the source for this channel from the previous layer
public private(set) var resultSize : DeepChannelSize // Size of the result of this channel
var networkOperators : [DeepNetworkOperator] = []
fileprivate var inputErrorGradient : [Float] = []
public init(identifier: String, sourceChannels: [String]) {
idString = identifier
sourceChannelIDs = sourceChannels
resultSize = DeepChannelSize(dimensionCount: 1, dimensionValues: [0])
}
public init?(fromDictionary: [String: AnyObject])
{
// Init for nil return (hopefully Swift 3 removes this need)
resultSize = DeepChannelSize(dimensionCount: 1, dimensionValues: [0])
// Get the id string type
let id = fromDictionary["idString"] as? NSString
if id == nil { return nil }
idString = id! as String
// Get the array of source IDs
sourceChannelIDs = []
let sourceIDArray = fromDictionary["sourceChannelIDs"] as? NSArray
if (sourceIDArray == nil) { return nil }
for item in sourceIDArray! {
let source = item as? NSString
if source == nil { return nil }
sourceChannelIDs.append(source! as String)
}
// Get the array of network operators
let networkOpArray = fromDictionary["networkOperators"] as? NSArray
if (networkOpArray == nil) { return nil }
for item in networkOpArray! {
let element = item as? [String: AnyObject]
if (element == nil) { return nil }
let netOperator = DeepNetworkOperatorType.getDeepNetworkOperatorFromDict(element!)
if (netOperator == nil) { return nil }
networkOperators.append(netOperator!)
}
}
/// Function that indicates if a given input ID is used by this channel
public func usesInputID(_ id : String) -> Bool {
for usedID in sourceChannelIDs {
if usedID == id { return true }
}
return false
}
/// Function to add a network operator to the channel
public func addNetworkOperator(_ newOperator: DeepNetworkOperator)
{
networkOperators.append(newOperator)
}
/// Function to get the number of defined operators
public var numOperators: Int {
get { return networkOperators.count }
}
/// Function to get a network operator at the specified index
public func getNetworkOperator(_ operatorIndex: Int) ->DeepNetworkOperator?
{
if (operatorIndex >= 0 && operatorIndex < networkOperators.count) {
return networkOperators[operatorIndex]
}
return nil
}
/// Function to replace a network operator at the specified index
public func replaceNetworkOperator(_ operatorIndex: Int, newOperator: DeepNetworkOperator)
{
if (operatorIndex >= 0 && operatorIndex < networkOperators.count) {
networkOperators[operatorIndex] = newOperator
}
}
/// Functions to remove a network operator from the channel
public func removeNetworkOperator(_ operatorIndex: Int)
{
if (operatorIndex >= 0 && operatorIndex < networkOperators.count) {
networkOperators.remove(at: operatorIndex)
}
}
// Method to validate inputs exist and match requirements
func validateAgainstPreviousLayer(_ prevLayer: DeepNetworkInputSource, layerIndex: Int) ->[String]
{
var errors : [String] = []
var firstInputSize : DeepChannelSize?
// Check each source ID to see if it exists and matches
for sourceID in sourceChannelIDs {
// Get the input sizing from the previous layer that has our source
if let inputSize = prevLayer.getInputDataSize([sourceID]) {
// It exists, see if it matches any previous size
if let firstSize = firstInputSize {
if (!firstSize.canAddInput(ofSize: inputSize)) {
errors.append("Layer \(layerIndex), channel \(idString) uses input \(sourceID), which does not match size of other inputs")
}
}
else {
// First input
firstInputSize = inputSize
}
}
else {
// Source channel not found
errors.append("Layer \(layerIndex), channel \(idString) uses input \(sourceID), which does not exist")
}
}
// If all the sources exist and are of appropriate size, update the output sizes
if let inputSize = prevLayer.getInputDataSize(sourceChannelIDs) {
// We have the input, update the output size of the channel
updateOutputSize(inputSize)
}
else {
// Source channel not found
errors.append("Combining sources of for Layer \(layerIndex), channel \(idString) fails")
}
return errors
}
// Method to determine the output size based on the input size and the operation layers
func updateOutputSize(_ inputSize : DeepChannelSize)
{
// Iterate through each operator, adjusting the size
var currentSize = inputSize
for networkOperator in networkOperators {
currentSize = networkOperator.getResultingSize(currentSize)
}
resultSize = currentSize
}
func getResultRange() ->(minimum: Float, maximum: Float)
{
if let lastOperator = networkOperators.last {
return lastOperator.getResultRange()
}
return (minimum: 0.0, maximum: 1.0)
}
public func initializeParameters()
{
for networkOperator in networkOperators {
networkOperator.initializeParameters()
}
}
// Method to feed values forward through the channel
func feedForward(_ inputSource: DeepNetworkInputSource)
{
// Get the inputs from the previous layer
var inputs = inputSource.getValuesForIDs(sourceChannelIDs)
var inputSize = inputSource.getInputDataSize(sourceChannelIDs)
if (inputSize == nil) { return }
// Process each operator
for networkOperator in networkOperators {
inputs = networkOperator.feedForward(inputs, inputSize: inputSize!)
inputSize = networkOperator.getResultSize()
}
}
// Function to clear weight-change accumulations for the start of a batch
public func startBatch()
{
for networkOperator in networkOperators {
networkOperator.startBatch()
}
}
func backPropagate(_ gradientSource: DeepNetworkOutputDestination)
{
// Get the gradients from the previous layer
inputErrorGradient = gradientSource.getGradientForSource(idString)
// Process the gradient backwards through all the operators
for operatorIndex in stride(from: (networkOperators.count - 1), through: 0, by: -1) {
inputErrorGradient = networkOperators[operatorIndex].backPropogateGradient(inputErrorGradient)
}
}
public func updateWeights(_ trainingRate : Float, weightDecay: Float)
{
for networkOperator in networkOperators {
networkOperator.updateWeights(trainingRate, weightDecay: weightDecay)
}
}
public func gradientCheck(ε: Float, Δ: Float, network: DeepNetwork) -> Bool
{
// Have each operator check
var result = true
for operatorIndex in 0..<networkOperators.count {
if (!networkOperators[operatorIndex].gradientCheck(ε: ε, Δ: Δ, network: network)) { result = false }
}
return result
}
func getGradient() -> [Float]
{
return inputErrorGradient
}
/// Function to get the result of the last operation
public func getFinalResult() -> [Float]
{
if let lastOperator = networkOperators.last {
return lastOperator.getResults()
}
return []
}
public func getResultOfItem(_ operatorIndex: Int) ->(values : [Float], size: DeepChannelSize)?
{
if (operatorIndex >= 0 && operatorIndex < networkOperators.count) {
let values = networkOperators[operatorIndex].getResults()
let size = networkOperators[operatorIndex].getResultSize()
return (values : values, size: size)
}
return nil
}
public func getPersistenceDictionary() -> [String: AnyObject]
{
var resultDictionary : [String: AnyObject] = [:]
// Set the id string type
resultDictionary["idString"] = idString as AnyObject?
// Set the array of source IDs
resultDictionary["sourceChannelIDs"] = sourceChannelIDs as AnyObject?
// Set the array of network operators
var operationsArray : [[String: AnyObject]] = []
for networkOperator in networkOperators {
operationsArray.append(networkOperator.getOperationPersistenceDictionary())
}
resultDictionary["networkOperators"] = operationsArray as AnyObject?
return resultDictionary
}
}
| apache-2.0 | 2922553e3f2fa2a9dc78bee83a4f7e64 | 35.191358 | 147 | 0.614361 | 4.956044 | false | false | false | false |
xingerdayu/dayu | dayu/User.swift | 1 | 1902 | //
// User.swift
// Community
//
// Created by Xinger on 15/3/16.
// Copyright (c) 2015年 Xinger. All rights reserved.
//
import UIKit
class User: NSObject {
var id = 1;
var tel:String?;
var regTime:Int64 = 0;
var havePhoto = 0
var intro:String?;
var maxLost:Float?;
var profit:Float?;
var transNum:Int?;
var username:String?;
var winRate:Float?;
var score:Float?;
var fans:Int?;
var copyNum = 0
var pwd = ""
var token = ""
var authority = 0;
// func parse(dict:NSDictionary) {
// id = dict["id"] as Int
// tel = dict["tel"] as String
// regTime = (dict["register_time"] as NSString).longLongValue
//
// score = dict["avgScore"] as? Float
// fans = dict["fansCount"] as? Int
// havePhoto = dict["havePhoto"] as Int
//
// //Get maybe null value field
// intro = dict["intro"] as? String
// maxLost = dict["max_lost"] as? Float
// profit = dict["profit"] as? Float
// winRate = dict["win_rate"] as? Float
// transNum = dict["trans_num"] as? Int
// username = dict["username"] as? String
// copyNum = dict["copy_num"] as Int
// }
func parse(dict:NSDictionary) {
id = dict["id"] as! Int
tel = dict["tel"] as? String
username = dict["username"] as? String
intro = dict["intro"] as? String
}
func getUsername() -> String {
let name = username == nil ? "\(id)" : username
return name!
}
func getUserIntro() -> String {
let tIntro = intro == nil ? "无" : intro!
return tIntro
}
func getShowUsername() -> String {
let name = username == nil ? "新用户" : username
return name!
}
func getLocalImageName() -> String {
return "U\(id).jpg"
}
}
| bsd-3-clause | ae2013905c20e470989fee3fd5ecbeb3 | 23.571429 | 69 | 0.526427 | 3.673786 | false | false | false | false |
PiXeL16/BudgetShare | BudgetShare/Entities/Budget.swift | 1 | 4114 | //
// Created by Chris Jimenez on 3/2/17.
// Copyright (c) 2017 Chris Jimenez. All rights reserved.
//
import Foundation
import SwiftyJSON
import Firebase
internal struct Budget: FirebaseModeled {
var id: String
var amount: Double
var moneyLeft: Double
var name: String
var type: BudgetType
//TODO: Figure out how to handle multiple currencies
var currency: String
var startDay: StartDay
var transactions: [Transaction]
var users: [User]
var createdAtTimeStamp: Double
var updatedAtTimeStamp: Double
// Firebase reference and key
var firebaseRef: DatabaseReference?
init(id: String, amount: Double, moneyLeft: Double, name: String, type: BudgetType, currency: String,
startDay: StartDay, transactions: [Transaction], users: [User], createdAtTimeStamp: Double, updatedAtTimeStamp: Double) {
self.id = id
self.amount = amount
self.moneyLeft = moneyLeft
self.name = name
self.type = type
self.currency = currency
self.startDay = startDay
self.transactions = transactions
self.users = users
self.createdAtTimeStamp = createdAtTimeStamp
self.updatedAtTimeStamp = updatedAtTimeStamp
}
}
extension Budget {
init(firebaseSnapshot: DataSnapshot) {
/// Initialize firebase data
self.id = firebaseSnapshot.key
self.firebaseRef = firebaseSnapshot.ref
self.amount = firebaseSnapshot.json["amount"].doubleValue
self.moneyLeft = firebaseSnapshot.json["moneyLeft"].doubleValue
self.name = firebaseSnapshot.json["name"].stringValue
self.currency = firebaseSnapshot.json["currency"].stringValue
/// Default to Unknown if not a valid type
if let budgetType = BudgetType(rawValue: firebaseSnapshot.json["type"].stringValue) {
self.type = budgetType
} else {
self.type = .Unknown
}
/// Default to Unknown if not a valid type
if let startDay = StartDay(rawValue: firebaseSnapshot.json["startDay"].intValue) {
self.startDay = startDay
} else {
self.startDay = .Unknown
}
// Gets the createdAt from the JSON string and if not default to now
if let createdAt = firebaseSnapshot.json["createdAt"].double {
self.createdAtTimeStamp = createdAt
} else {
self.createdAtTimeStamp = Date().timeIntervalSinceNow
}
// Gets the createdAt from the JSON string and if not default to now
if let updatedAt = firebaseSnapshot.json["updatedAt"].double {
self.updatedAtTimeStamp = updatedAt
} else {
self.updatedAtTimeStamp = Date().timeIntervalSinceNow
}
// TODO: This should be paginated.
self.transactions = [Transaction]()
if let transactions = firebaseSnapshot.json[FirebaseConstants.TRANSACTIONS_KEY].array {
self.transactions = transactions.map({
Transaction(json: $0)
})
}
self.users = [User]()
}
}
internal enum BudgetType: String, CustomStringConvertible {
case Monthly = "monthly"
case Weekly = "weekly"
case Unknown = "unknown"
var description: String {
switch self {
case .Monthly: return "Monthly".localized
case .Weekly: return "Weekly".localized
case .Unknown: return "Unknown".localized
}
}
}
internal enum StartDay: Int, CustomStringConvertible {
case FirstDayOfMonth = 1
case LastDayOfMonth = 30
case SecondDayOfMonth = 2
case FifteenDayOfMonth = 15
case Unknown = 0
var description: String {
switch self {
case .FirstDayOfMonth: return "FirstDayOfTheMonth".localized
case .LastDayOfMonth: return "LastDayOfTheMonth".localized
case .FifteenDayOfMonth: return "FifteenOfTheMonth".localized
case .SecondDayOfMonth: return "SecondDayOfMonth".localized
case .Unknown: return "Unknown".localized
}
}
}
| mit | 1412293d2bab652cbea36f2dc6008e4a | 30.166667 | 130 | 0.642684 | 4.874408 | false | false | false | false |
cuappdev/podcast-ios | old/Podcast/SearchHeaderView.swift | 1 | 4329 | //
// SearchHeaderView.swift
// Podcast
//
// Created by Mindy Lou on 11/1/17.
// Copyright © 2017 Cornell App Development. All rights reserved.
//
import UIKit
protocol SearchHeaderDelegate: class {
func searchHeaderDidPress(searchHeader: SearchHeaderView)
func searchHeaderDidPressDismiss(searchHeader: SearchHeaderView)
}
enum searchHeaderViewType {
case itunes
case facebook
case facebookRelogin // when a user is a facebook user but doesn't have auth token from facebook
var title: NSMutableAttributedString {
switch self {
case .itunes:
let attributedString = NSMutableAttributedString(string: "Can’t find a series you’re looking for? Search the web to add more series to our collection.")
attributedString.addAttribute(.foregroundColor, value: UIColor.sea, range: NSRange(location: 40, length: 15))
return attributedString
case .facebook:
let attributedString = NSMutableAttributedString(string: "You haven't connected to Facebook yet. Connect to Facebook to find friends to follow")
attributedString.addAttribute(.foregroundColor, value: UIColor.sea, range: NSRange(location: 39, length: 20))
return attributedString
case .facebookRelogin:
let attributedString = NSMutableAttributedString(string: "Login with Facebook to find friends to follow")
attributedString.addAttribute(.foregroundColor, value: UIColor.sea, range: NSRange(location: 0, length: 19))
return attributedString
}
}
}
class SearchHeaderView: UIView {
let headerHeight: CGFloat = 79.5
let topPadding: CGFloat = 12.5
let bottomPadding: CGFloat = 25
let leftPadding: CGFloat = 17.5
let rightPadding: CGFloat = 36.5
let dividerHeight: CGFloat = 16
let buttonWidthHeight: CGFloat = 15
let buttonTopRightOffset: CGFloat = 18
var descriptionLabel: UILabel!
var dismissBannerButton: UIButton!
var dividerLabel: UILabel!
weak var delegate: SearchHeaderDelegate?
init(frame: CGRect, type: searchHeaderViewType) {
super.init(frame: frame)
backgroundColor = .offWhite
isUserInteractionEnabled = true
descriptionLabel = UILabel(frame: .zero)
descriptionLabel.font = ._14RegularFont()
descriptionLabel.textAlignment = .left
descriptionLabel.numberOfLines = 2
descriptionLabel.textColor = .slateGrey
descriptionLabel.attributedText = type.title
descriptionLabel.isUserInteractionEnabled = true
addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(didTapSearch)))
addSubview(descriptionLabel!)
descriptionLabel?.snp.makeConstraints { make in
make.leading.equalToSuperview().offset(leftPadding)
make.trailing.equalToSuperview().inset(rightPadding)
make.top.equalToSuperview().offset(topPadding)
make.bottom.equalToSuperview().inset(bottomPadding)
}
dismissBannerButton = UIButton(frame: .zero)
dismissBannerButton.setImage(#imageLiteral(resourceName: "dismiss_banner"), for: .normal)
dismissBannerButton.addTarget(self, action: #selector(dismissHeader), for: .touchUpInside)
addSubview(dismissBannerButton!)
dismissBannerButton.snp.makeConstraints { make in
make.width.height.equalTo(buttonWidthHeight)
make.top.equalToSuperview().offset(buttonTopRightOffset)
make.trailing.equalToSuperview().inset(buttonTopRightOffset)
}
dividerLabel = UILabel(frame: .zero)
dividerLabel.backgroundColor = .paleGrey
addSubview(dividerLabel!)
dividerLabel.snp.makeConstraints { make in
make.width.equalToSuperview()
make.height.equalTo(dividerHeight)
make.bottom.equalToSuperview()
}
}
@objc func didTapSearch() {
delegate?.searchHeaderDidPress(searchHeader: self)
}
@objc func dismissHeader() {
delegate?.searchHeaderDidPressDismiss(searchHeader: self)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| mit | 8828083f7d15f5eb5ce14a4c32d62dc3 | 37.265487 | 164 | 0.681776 | 5.190876 | false | false | false | false |
STLabs/STState | Sources/State/Storable.swift | 2 | 5185 | //
// State: Storable.swift
// Copyright © 2016 SIMPLETOUCH LLC. All rights reserved.
//
import Foundation
#if os(iOS)
import UIKit
#endif
/*===----------------------------------------------------------------------===//
* TODO: implement customDebugStringConvertible, Mirror?
* TODO: add overloads with throws, for required props
* TODO: add overloads with default values to Store
//===----------------------------------------------------------------------===*/
/// A type that can read and write it's properties to a Store.
public protocol Storable {
/// Stores the receiver to the given store.
func store(to: inout Store)
/// Restores a Storable from the given store.
static func restore(from: Store) -> Self?
}
public extension Storable {
var properties : PropertyList {
var s = Store()
self.store(to: &s)
return s.properties
}
init?(properties: PropertyList) {
let s = Store(properties: properties)
if let instance = Self.restore(from: s) {
self = instance
}
else {
return nil
}
}
/// Create an instance from a plist file.
init?(plistFile file: URL) {
guard let p = Format.plist.read(file) as? PropertyList else { return nil }
self.init(properties: p)
}
/// Create an instance from a json file.
init?(jsonFile file: URL) {
guard let p = Format.json.read(file) as? PropertyList else { return nil }
self.init(properties: p)
}
/// Create an instance from a binary file.
init?(binaryFile file: URL) {
guard let p = Format.binary.read(file) as? PropertyList else { return nil }
self.init(properties: p)
}
/// Create an instance from binary data.
init?(data: Data) {
guard let p = Format.binary.read(data) as? PropertyList else { return nil }
self.init(properties: p)
}
/// Write the receiver to a file in the specified format.
///
/// - Returns: `true` if succeeded otherwise `false`
func write(to location: URL, format: Format = .plist) -> Bool {
return format.write(properties, to: location)
}
/// Return the receiver formatted to a json string.
func makeJson() -> String? {
return Format.json.makeString(from: properties)
}
/// Return the receiver formatted to binary data.
func makeData() -> Data? {
return Format.binary.makeData(from: properties, prettyPrint: true)
}
}
/*===----------------------------------------------------------------------===//
* MARK: - ARRAY SUPPORT
*
* TODO: Can this be on collection or sequence instead?
*===----------------------------------------------------------------------===*/
public extension Array where Element: Storable {
/// Create an array of elements from a property list.
init?(properties: [PropertyList]) {
guard let instance = sequence(properties.map { Element(properties:$0) })
else { return nil }
self = instance
}
/// Create an array of elements from a file in the specified format.
private init?(file: URL, format: Format = Format.plist) {
guard let d = format.read(file) as? [[String: AnyObject]]
else { return nil }
guard let instance = sequence(d.map { Element(properties: $0) })
else { return nil }
self = instance
}
/// Create an array of elements from a json file.
init?(jsonFile file: URL) {
self.init(file: file, format: .json)
}
/// Create an array of elements from a plist file.
init?(plistFile file: URL) {
self.init(file: file, format: .plist)
}
/// Create an array of elements from a binary file.
init?(binaryFile file: URL) {
self.init(file: file, format: .binary)
}
/// Create an array if elements from binary data.
init?(data: Data) {
guard let d = Format.binary.read(data) as? [[String: AnyObject]]
else { return nil }
guard let instance = sequence(d.map { Element(properties: $0) })
else { return nil }
self = instance
}
/// Writes the receiver to a file in the specified format.
///
/// - Returns: `true` if succeeded otherwise `false`
func write(to location: URL, format: Format = Format.plist) -> Bool {
return format.write(makePropertyList() as AnyObject, to: location)
}
/// Returns the array of elements formatted to a json string.
func makeJson() -> String? {
return Format.json.makeString(from: makePropertyList())
}
/// Returns the array of elements formatted to binary data.
func makeData() -> Data? {
return Format.binary.makeData(from: makePropertyList() as AnyObject, prettyPrint: true)
}
/// Returns the array elements formatted to a property list.
func makePropertyList() -> [PropertyList] {
return self.reduce([PropertyList]()) { (accum, elem) -> [PropertyList] in
var vaccum = accum
vaccum.append(elem.properties)
return vaccum
}
}
}
| mit | eeb2adef74d1e0444e078da92087c38d | 31.603774 | 95 | 0.571952 | 4.461274 | false | false | false | false |
aloco/Argonaut | Argonaut/JSONMapping.swift | 1 | 1841 | //
// JSONMapping.swift
// Example
//
// Created by Alexander Schuch on 03/04/15.
// Copyright (c) 2015 Alexander Schuch. All rights reserved.
//
import Foundation
import Argo
// MARK: Direct object conversion
/// Creates an object from the given encoded JSON object
///
/// - parameter JSON: data
/// - returns: The decoded object
public func decodeData<T: Argo.Decodable>(_ data: Data?) -> T? where T == T.DecodedType {
if let json = JSONWithData(data) {
return decode(json)
}
return .none
}
/// Creates an array of objects from the given encoded JSON array
///
/// - parameter JSON: data
/// - returns: An array containing the decoded objects
public func decodeData<T: Argo.Decodable>(_ data: Data?) -> [T]? where T == T.DecodedType {
if let json = JSONWithData(data) {
return decode(json)
}
return .none
}
// MARK: Decoded type conversion
/// Creates an object from the given encoded JSON object
///
/// - parameter JSON: data
/// - returns: An instance of the `Decoded` type
public func decodeData<T: Argo.Decodable>(_ data: Data?) -> Decoded<T>? where T == T.DecodedType {
if let json = JSONWithData(data) {
return decode(json)
}
return .none
}
/// Creates an array of objects from the given encoded JSON array
///
/// - parameter JSON: data
/// - returns: An instance of the `Decoded` type
public func decodeData<T: Argo.Decodable>(_ data: Data?) -> Decoded<[T]>? where T == T.DecodedType {
if let json = JSONWithData(data) {
return decode(json)
}
return .none
}
// MARK: Private: JSON Serialization Helper
private func JSONWithData(_ data: Data?) -> Any? {
if let data = data {
return try? JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions())
}
return .none
}
| mit | 2d3cd97a4c0881fe790f03a45d61d8d2 | 23.878378 | 105 | 0.652363 | 3.933761 | false | false | false | false |
spf2/FirebaseAdapter | FirebaseAdapterExample/FirebaseAdapterExample/Message.swift | 1 | 609 | //
// Message.swift
// FirebaseAdapterExample
//
// Created by Steve Farrell on 9/14/15.
// Copyright (c) 2015 Movem3nt. All rights reserved.
//
import Foundation
import FirebaseAdapter
class Message : BaseItem {
var text: String?
var username: String?
override func update(dict: [String : AnyObject]?) {
super.update(dict)
text = dict?["text"] as? String
username = dict?["username"] as? String
}
override var dict: [String: AnyObject] {
var d = super.dict
d["text"] = text
d["username"] = username
return d
}
}
| mit | db631b011d8d17d13cde48fb1cf4619d | 20.75 | 55 | 0.597701 | 3.85443 | false | false | false | false |
huangboju/Moots | Examples/Lumia/Lumia/Component/CustomPaging/PagingView.swift | 1 | 4403 | //
// PagingView.swift
// CustomPaging
//
// Created by Ilya Lobanov on 26/08/2018.
// Copyright © 2018 Ilya Lobanov. All rights reserved.
//
import UIKit
import pop
final class PagingView: UIView {
let contentView: UIScrollView
var anchors: [CGPoint] = []
var decelerationRate: CGFloat = UIScrollView.DecelerationRate.fast.rawValue
/**
@abstract The effective bounciness.
@discussion Use in conjunction with 'springSpeed' to change animation effect. Values are converted into corresponding dynamics constants. Higher values increase spring movement range resulting in more oscillations and springiness. Defined as a value in the range [0, 20]. Defaults to 4.
*/
var springBounciness: CGFloat = 4
/**
@abstract The effective speed.
@discussion Use in conjunction with 'springBounciness' to change animation effect. Values are converted into corresponding dynamics constants. Higher values increase the dampening power of the spring resulting in a faster initial velocity and more rapid bounce slowdown. Defined as a value in the range [0, 20]. Defaults to 12.
*/
var springSpeed: CGFloat = 12
init(contentView: UIScrollView) {
self.contentView = contentView
super.init(frame: .zero)
setupViews()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func contentViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint,
targetContentOffset: UnsafeMutablePointer<CGPoint>)
{
// Stop system animation
targetContentOffset.pointee = scrollView.contentOffset
let offsetProjection = scrollView.contentOffset.project(initialVelocity: velocity,
decelerationRate: decelerationRate)
if let target = nearestAnchor(forContentOffset: offsetProjection) {
snapAnimated(toContentOffset: target, velocity: velocity)
}
}
func contentViewWillBeginDragging(_ scrollView: UIScrollView) {
stopSnappingAnimation()
}
// MARK: - Private
private var minAnchor: CGPoint {
let x = -contentView.adjustedContentInset.left
let y = -contentView.adjustedContentInset.top
return CGPoint(x: x, y: y)
}
private var maxAnchor: CGPoint {
let x = contentView.contentSize.width - bounds.width + contentView.adjustedContentInset.right
let y = contentView.contentSize.height - bounds.height + contentView.adjustedContentInset.bottom
return CGPoint(x: x, y: y)
}
private func setupViews() {
addSubview(contentView)
setupLayout()
}
private func setupLayout() {
contentView.translatesAutoresizingMaskIntoConstraints = false
contentView.topAnchor.constraint(equalTo: topAnchor).isActive = true
contentView.leftAnchor.constraint(equalTo: leftAnchor).isActive = true
contentView.bottomAnchor.constraint(equalTo: bottomAnchor).isActive = true
contentView.rightAnchor.constraint(equalTo: rightAnchor).isActive = true
}
private func nearestAnchor(forContentOffset offset: CGPoint) -> CGPoint? {
guard let candidate = anchors.min(by: { offset.distance(to: $0) < offset.distance(to: $1) }) else {
return nil
}
let x = candidate.x.clamped(to: minAnchor.x...maxAnchor.x)
let y = candidate.y.clamped(to: minAnchor.y...maxAnchor.y)
return CGPoint(x: x, y: y)
}
// MARK: - Private: Animation
private static let snappingAnimationKey = "CustomPaging.PagingView.scrollView.snappingAnimation"
private func snapAnimated(toContentOffset newOffset: CGPoint, velocity: CGPoint) {
let animation: POPSpringAnimation = POPSpringAnimation(propertyNamed: kPOPScrollViewContentOffset)
animation.velocity = velocity
animation.toValue = newOffset
animation.fromValue = contentView.contentOffset
animation.springBounciness = springBounciness
animation.springSpeed = springSpeed
contentView.pop_add(animation, forKey: PagingView.snappingAnimationKey)
}
private func stopSnappingAnimation() {
contentView.pop_removeAnimation(forKey: PagingView.snappingAnimationKey)
}
}
| mit | 8a383ebbb5b82eacb6590b1d118dfe89 | 35.991597 | 332 | 0.68696 | 5.172738 | false | false | false | false |
coolsamson7/inject | InjectTests/SampleTest.swift | 1 | 9818 | //
// BeanFactoryTests.swift
// Inject
//
// Created by Andreas Ernst on 18.07.16.
// Copyright © 2016 Andreas Ernst. All rights reserved.
//
import XCTest
import Foundation
@testable import Inject
// test classes
class SamplePostProcessor : NSObject, BeanPostProcessor {
// implement BeanPostProcessor
func process(_ bean : AnyObject) throws -> AnyObject {
print("post process \(bean)...")
return bean
}
}
class Foo : NSObject, Bean, BeanDescriptorInitializer {
// instance data
var id : String = ""
var number : Int = 0
var bar : Bar?
// init
override init() {
super.init()
}
// implement Bean
func postConstruct() throws -> Void {
// funny code here
}
// implement BeanDescriptorInitializer
func initializeBeanDescriptor(_ beanDescriptor : BeanDescriptor) {
beanDescriptor["bar"].inject(InjectBean())
}
// CustomStringConvertible
override internal var description: String {
return "foo[id: \(id), number: \(number), bar: \(String(describing: bar))]"
}
}
class Bar : NSObject, EnvironmentAware {
// instance data
var id : String = ""
var magic = 0
// init
override init() {
super.init()
}
// implement EnvironmentAware
var _environment : Environment?
var environment: Environment? {
get {
return _environment
}
set {
_environment = newValue
}
}
}
class BazFactory : NSObject, FactoryBean {
// instance data
var name : String = ""
var id : String = ""
// init
override init() {
super.init()
}
// implement FactoryBean
func create() throws -> AnyObject {
let result = Baz()
result.factory = name
result.id = id
return result
}
}
class Baz : NSObject {
// instance data
var factory : String = ""
var id : String = ""
// init
override init() {
super.init()
}
}
class Bazong : NSObject {
// instance data
var id : String = ""
var foo : Foo? = nil
// init
override init() {
super.init()
}
}
protocol SwiftProtocol {
}
class SampleScope : AbstractBeanScope {
override init() {
super.init(name: "sample")
}
override func prepare(_ bean : Environment.BeanDeclaration, factory : BeanFactory) throws {
if !bean.lazy {
try get(bean, factory: factory)
}
}
override func get(_ bean : Environment.BeanDeclaration, factory : BeanFactory) throws -> AnyObject {
if bean.singleton == nil {
bean.singleton = try factory.create(bean)
}
return bean.singleton!
}
}
class SampleTest: XCTestCase {
override class func setUp() {
Classes.setDefaultBundle(SampleTest.self)
Tracer.setTraceLevel("inject", level: .full)
Tracer.setTraceLevel("configuration", level: .full)
// register the namespace handler.
ConfigurationNamespaceHandler(namespace: "configuration")
// logger
LogManager()
.registerLogger("", level : .all, logs: [ConsoleLog(name: "console", synchronize: true)])
}
// MARK: internal funcs
func getResource(_ name : String, suffix : String = "xml") -> Foundation.Data {
return (try! Foundation.Data(contentsOf: Bundle(for: type(of: self)).url(forResource: name, withExtension: suffix)!))
}
// tests
/*func testXML() {
let environment = try! Environment(name: "environment")
try! environment
.loadXML(getResource("sample"))
.startup()
print(environment.report())
let baz = try! environment.getBean(Baz.self)
XCTAssert(baz.id == "id")
}*/
func testFluent() {
let environment = try! Environment(name: "fluent environment", traceOrigin: true)
try! environment.addConfigurationSource(ProcessInfoConfigurationSource())
try! environment
.define(environment.bean(Foo.self, id: "foo-by-factory", factory: {return Foo()}))
.define(environment.bean(SamplePostProcessor.self))
.define(environment.bean(Foo.self, id: "foo-1")
.property("id", value: "foo-1")
.property("number", resolve: "${dunno=1}"))
.define(environment.bean(Foo.self, id: "foo-prototype")
.scope("prototype")
.property("id", value: "foo-prototype")
.property("number", resolve: "${com.foo:bar=1}"))
.define(environment.bean(Bar.self, id: "bar-parent")
.abstract()
.property("magic", value: 4711))
.define(environment.bean(Bar.self, id: "bar")
.parent("bar-parent")
.property("id", value: "bar"))
.define(environment.bean(BazFactory.self, id: "baz")
.target(Baz.self)
.property("name", value: "factory")
.property("id", value: "baz"))
.define(environment.bean(Bazong.self, id: "bazong-1")
.property("id", value: "id")
.property("foo", ref: "foo-1"))
.define(environment.bean(Bazong.self, id: "bazong-2")
.property("id", value: "id")
.property("foo", bean: environment.bean(Foo.self)
.property("id", value: "foo-3")
.property("number", value: 1)))
.startup()
print(environment.report())
let foos = try! environment.getBeansByType(Foo.self)
XCTAssert(foos.count == 4)
let baz = try! environment.getBean(Baz.self)
XCTAssert(baz.id == "baz")
}
class Swift : SwiftProtocol, Initializable, BeanDescriptorInitializer {
var name : String?
var number : Int = 0
var other : AnotherSwift?
// MARK: init
required init() {
}
// MARK: implement BeanDescriptorInitializer
func initializeBeanDescriptor(_ beanDescriptor : BeanDescriptor) {
try! beanDescriptor.implements(SwiftProtocol.self, Initializable.self, BeanDescriptorInitializer.self)
}
}
class AnotherSwift : NSObject, BeanDescriptorInitializer {
var name : String?
var number : Int = 0
// MARK: init
override init() {
super.init()
}
// MARK: implement BeanDescriptorInitializer
func initializeBeanDescriptor(_ beanDescriptor : BeanDescriptor) {
beanDescriptor["number"].inject(InjectConfigurationValue(key: "key", defaultValue: -1))
try! beanDescriptor.implements(BeanDescriptorInitializer.self, Initializable.self)
}
}
func testNoReflection() {
let environment = try! Environment(name: "no reflection environment")
try! environment.addConfigurationSource(ProcessInfoConfigurationSource())
try! environment
.define(environment.bean(SampleScope.self, factory: SampleScope.init))
.define(environment.bean(Swift.self, factory: {
let swift = Swift()
swift.name = try environment.getConfigurationValue(String.self, key: "dunno", defaultValue: "default")
swift.other = try environment.getBean(AnotherSwift.self)
return swift
})
.requires(class: AnotherSwift.self)
.scope("sample")
.implements(SwiftProtocol.self))
.define(environment.bean(AnotherSwift.self, factory: AnotherSwift.init))
// fetch
let swiftProtocol = try! environment.getBean(SwiftProtocol.self)
let other = try! environment.getBean(AnotherSwift.self)
XCTAssert(swiftProtocol is Swift)
XCTAssert(other.number == -1)
let swiftProtocols = try! environment.getBeansByType(SwiftProtocol.self)
XCTAssert(swiftProtocols.count == 1)
let initializables = try! environment.getBeansByType(Initializable.self)
XCTAssert(initializables.count == 2)
let descriptoInitializers = try! environment.getBeansByType(BeanDescriptorInitializer.self)
XCTAssert(descriptoInitializers.count == 2)
}
// FOO
// TEST
// test classes
class B {
init() {
print("B");
}
}
class A {
init() {
print("A");
}
}
class TestModuleA : EnvironmentBuilder.Module {
// init
required init() {
super.init(name: "module A")
}
// implement Module
override func configure(_ environment : Environment) throws -> Void {
// require...
// own dependencies
try environment.define(bean(A.self, factory: A.init))
}
}
class TestModuleB : EnvironmentBuilder.Module {
// init
required init() {
super.init(name: "module B")
}
// implement Module
override func configure(_ environment : Environment) throws -> Void {
// require...
try require(TestModuleA.self);
//finish();
// own dependencies
try environment.define(bean(B.self, factory: B.init))
}
}
func testEnvironment() throws {
let builder = EnvironmentBuilder(name: "environment");
// register a couple of environments
try builder.register(module: TestModuleA());
//try builder.register(module: TestModuleB.self);
// go
let environment = try builder.build(module: TestModuleB());//.self);
print(environment.report());
}
}
| mit | 3ae572e6561f7de38b6394ccc7505dbc | 23.061275 | 125 | 0.575736 | 4.521879 | false | false | false | false |
mightydeveloper/swift | test/decl/func/arg_rename.swift | 10 | 1732 | // RUN: %target-parse-verify-swift
// Renaming of arguments.
func foo(a x: Int, b y: Int) { }
foo(a: 5, b: 7)
func bar<T>(a x: T, b y: T) { }
bar(a: 5, b: 7)
// Renaming of arguments in initializers.
struct S {
init(a x: Int, b y: Int) { }
}
S(a: 5, b: 7) // expected-warning{{unused}}
struct GS {
init<T>(a x: T, b y: T) { }
}
GS(a: 5, b: 7) // expected-warning{{unused}}
// Using the hash to make a name API.
func f1(a a: Int, b: Int) { }
f1(a: 1, b: 2)
func f2(`class` cls: Int) { }
f2(`class`: 5)
// # diagnostics.
func g1(#a x: Int, #b y: Int) { }
// expected-warning@-1{{extraneous '#' in parameter}}{{9-10=}}
// expected-warning@-2{{extraneous '#' in parameter}}{{20-21=}}
func g2(a a: Int) { }
func g3(#:Int) { }
// expected-error@-1{{expected parameter name after '#'}}
func g4(#_:Int) { }
// expected-error@-1{{expected non-empty parameter name after '#'}}{{9-10=}}
func g5(_ a: Int) { }
// expected-warning@-1{{extraneous '_' in parameter: 'a' has no keyword argument name}}{{9-11=}}
class X {
init(a a: Int) { } // expected-warning{{extraneous duplicate parameter name; 'a' already has an argument label}}{{8-10=}}
func f1(a a: Int, b: Int) { }
func f2(a: Int, b b: Int) { } // expected-warning{{extraneous duplicate parameter name; 'b' already has an argument label}}{{19-21=}}
func f3(_ a: Int, b: Int) { }
// expected-warning@-1{{extraneous '_' in parameter: 'a' has no keyword argument name}}{{11-13=}}
}
// Operators never have keyword arguments.
infix operator +++ { }
func +++(#lhs: Int, // expected-error{{operator cannot have keyword arguments}}{{10-11=}}
rhs x: Int) -> Int { // expected-error{{operator cannot have keyword arguments}}{{10-14=}}
return lhs + x
}
| apache-2.0 | f8caebcc23f87fca6836a2d331e58f04 | 26.935484 | 135 | 0.604503 | 2.86755 | false | false | false | false |
TouchInstinct/LeadKit | TIFoundationUtils/AsyncOperation/Sources/AsyncOperation+Observe.swift | 1 | 2624 | //
// Copyright (c) 2022 Touch Instinct
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the Software), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED AS IS, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
private final class ClosureObserverOperation<Output, Failure: Error>: DependendAsyncOperation<Output, Failure> {
public typealias OnResultClosure = (Result<Output, Failure>) -> Void
public init(dependency: AsyncOperation<Output, Failure>,
onResult: OnResultClosure? = nil,
callbackQueue: DispatchQueue = .main) {
super.init(dependency: dependency) { result in
callbackQueue.async {
onResult?(result)
}
return result
}
}
}
public extension AsyncOperation {
func observe(onResult: ((Result<Output, Failure>) -> Void)? = nil,
callbackQueue: DispatchQueue = .main) -> AsyncOperation<Output, Failure> {
ClosureObserverOperation(dependency: self,
onResult: onResult,
callbackQueue: callbackQueue)
}
func observe(onSuccess: ((Output) -> Void)? = nil,
onFailure: ((Failure) -> Void)? = nil,
callbackQueue: DispatchQueue = .main) -> AsyncOperation<Output, Failure> {
let onResult: ClosureObserverOperation<Output, Failure>.OnResultClosure = {
switch $0 {
case let .success(output):
onSuccess?(output)
case let .failure(error):
onFailure?(error)
}
}
return observe(onResult: onResult, callbackQueue: callbackQueue)
}
}
| apache-2.0 | 6965a4559dbbb9419d88926c884b1500 | 38.757576 | 112 | 0.654726 | 4.913858 | false | false | false | false |
tompiking/shop_ke | shop_ke/ActivityShop.swift | 1 | 1968 | //
// ActivityShop.swift
// shop_ke
//
// Created by mac on 16/3/18.
// Copyright © 2016年 peraytech. All rights reserved.
//
import Foundation
//MARK:活动商店数据
class ActivityShop {
var discount = 0.0
var name = ""
var image_url = ""
var activities:[Activity] = [] //获取到的定时跳转的图片数据形成一个数组
static func getActivityShop(data:AnyObject?) ->[ActivityShop]{
var shops = [ActivityShop]()
if let arr = data!["hot_brands" ] as? [[String: AnyObject]] {
for index in 0..<arr.count {
let arr_data = arr[index]
let shop = ActivityShop()
shop.discount = arr_data["discount"] as! Double
shop.name = arr_data["name"] as! String
shop.image_url = arr_data["img_url"] as! String
shops.append(shop)
}
// for (_,brand) in arr.enumerate() {
// let shop = ActivityShop()
// shop.discount = brand["discount"] as? Int
// shop.name = brand["name"] as! String
// shop.image_url = brand["img_url"] as! String
// shops.append(shop)
// }
}
return shops
}
// //加载数据
// func loadData() {
// var params = [String : AnyObject]()
// params["client_type"] = "iphone"
// params["num"] = "4"
// params["pa"] = "pa"
// HttpManager.httpGetRequest(.GET, api_url: API_URL+"/brand_theme_index", params: params, onSuccess: { (successData) -> Void in
// self.activities = Activity.saveDataToModel(successData["activities"])
// self.loadBanner()
//
// self.shops = ActivityShop.getActivityShop(successData) //存商品数据
// self.activityTableView.reloadData() //渲染表格
// }) { (failData) -> Void in
// print(failData)
// }
// }
} | apache-2.0 | 825e2924a8cdd070021462ffbbc31d84 | 31.586207 | 135 | 0.520911 | 3.740594 | false | false | false | false |
PrinceChen/DouYu | DouYu/DouYu/Classes/Home/ViewModel/RecommendViewModel.swift | 1 | 3765 | //
// RecommendViewModel.swift
// DouYu
//
// Created by prince.chen on 2017/3/2.
// Copyright © 2017年 prince.chen. All rights reserved.
//
import UIKit
class RecommendViewModel: BaseViewModel {
// lazy var anchorGroups: [AnchorGroup] = [AnchorGroup]()
lazy var cycleModels: [CycleModel] = [CycleModel]()
fileprivate lazy var bigDataGroup: AnchorGroup = AnchorGroup()
fileprivate lazy var prettyGroup: AnchorGroup = AnchorGroup()
}
extension RecommendViewModel {
func requestData(_ finishiedCallback: @escaping () -> ()) {
let parameters = ["limit" : "4", "offset": "0", "time": NSDate.getCurrentTime() as NSString]
let disGroup = DispatchGroup.init()
disGroup.enter()
// 1. 请求推荐数据
NetworkTools.requestData(type: .get, URLString: "http://capi.douyucdn.cn/api/v1/getbigDataRoom", parameters: ["time": NSDate.getCurrentTime() as NSString]) { (result) in
guard let resultDict = result as? [String: NSObject] else {
return
}
guard let dataArray = resultDict["data"] as? [[String: NSObject]] else { return }
self.bigDataGroup.tag_name = "最热"
self.bigDataGroup.icon_name = "home_header_hot"
for dict in dataArray {
let anchor = AnchorModel(dict: dict)
self.bigDataGroup.anchors.append(anchor)
}
disGroup.leave()
// print("1的数据都请求到")
}
// 2.请求颜值数据
disGroup.enter()
NetworkTools.requestData(type: .get, URLString: "http://capi.douyucdn.cn/api/v1/getVerticalRoom", parameters: parameters) { (result) in
guard let resultDict = result as? [String: NSObject] else {
return
}
guard let dataArray = resultDict["data"] as? [[String: NSObject]] else { return }
self.prettyGroup.tag_name = "颜值"
self.prettyGroup.icon_name = "home_header_phone"
for dict in dataArray {
let anchor = AnchorModel(dict: dict)
self.prettyGroup.anchors.append(anchor)
}
disGroup.leave()
// print("2的数据都请求到")
}
// 3.请求后面部分游戏数据
//"http://capi.douyucdn.cn/api/v1/getHotCate?limit=4&offset=0&time"
// print(NSDate.getCurrentTime())
disGroup.enter()
loadAnchorData(isGroupData: true, URLString: "http://capi.douyucdn.cn/api/v1/getHotCate") {
disGroup.leave()
}
// 排序数据
disGroup.notify(queue: DispatchQueue.main) {
// print("所有的数据都请求到")
self.anchorGroups.insert(self.prettyGroup, at: 0)
self.anchorGroups.insert(self.bigDataGroup, at: 0)
finishiedCallback()
}
}
func requestCycleData(_ finishiedCallback: @escaping () -> ()) {
NetworkTools.requestData(type: .get, URLString: "http://capi.douyucdn.cn/api/v1/slide/6", parameters: ["version":"2.300"]) { (result) in
guard let resultDict = result as? [String : NSObject] else {
return
}
guard let dataArray = resultDict["data"] as? [[String : NSObject]] else { return }
for dict in dataArray {
self.cycleModels.append(CycleModel(dict: dict))
}
finishiedCallback()
}
}
}
| mit | 5c0021f3040ec1a1035b0e36ddcc90ef | 31.936937 | 177 | 0.536652 | 4.663265 | false | false | false | false |
sjtu-meow/iOS | Meow/AnswerSummary.swift | 1 | 1228 | //
// Answer.swift
// Meow
//
// Created by 林树子 on 2017/6/30.
// Copyright © 2017年 喵喵喵的伙伴. All rights reserved.
//
import SwiftyJSON
struct AnswerSummary: ItemProtocol {
var id: Int!
var type: ItemType!
var profile: Profile!
var createTime: Date!
var questionId: Int!
var questionTitle: String?
var content: String!
var likeCount: Int!
var commentCount: Int!
}
extension AnswerSummary: JSONConvertible {
static func fromJSON(_ json: JSON) -> AnswerSummary? {
var answerJson = json["answer"]
let item = Item.fromJSON(answerJson)!
var answerSummary = self.init()
answerSummary.id = item.id
answerSummary.type = item.type
answerSummary.profile = item.profile
answerSummary.createTime = item.createTime
answerSummary.questionId <- json["questionId"]
answerSummary.questionTitle <- json["questionTitle"]
answerSummary.content <- answerJson["content"]
answerSummary.likeCount <- answerJson["likeCount"]
answerSummary.commentCount <- answerJson["commentCount"]
return answerSummary
}
}
| apache-2.0 | 2a0d0a726a5f822730279d2849913d7d | 23.632653 | 64 | 0.624689 | 4.453875 | false | false | false | false |
m0rb1u5/Accediendo-a-la-nube-con-iOS_Semanas-1-2-3-y-5_Petici-n-al-servidor-openlibrary.org | Accediendo-a-la-nube-con-iOS_Semana-1_Petici-n-al-servidor-openlibrary.org/ViewController.swift | 1 | 13191 | //
// ViewController.swift
// Accediendo-a-la-nube-con-iOS_Semana-1_Petici-n-al-servidor-openlibrary.org
//
// Created by Juan Carlos Carbajal Ipenza on 5/10/16.
// Copyright © 2016 Juan Carlos Carbajal Ipenza. All rights reserved.
//
import UIKit
import CoreData
protocol MyDelegado {
func agregarLibro(libro: Libro)
}
class ViewController: UIViewController, UISearchBarDelegate {
@IBOutlet weak var searchBar: UISearchBar!
@IBOutlet weak var textView: UITextView!
var pending: UIAlertController!
var indicator: UIActivityIndicatorView!
var libro: Libro = Libro()
var delegado: MyDelegado?
var contexto: NSManagedObjectContext? = nil
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.contexto = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
searchBar.showsCancelButton = true
let cancelButton = searchBar.value(forKey: "cancelButton") as! UIButton
cancelButton.setTitle("Limpiar", for: .normal)
self.pending = UIAlertController(title: "Cargando", message: nil, preferredStyle: .alert)
self.indicator = UIActivityIndicatorView(frame: pending.view.bounds)
self.indicator.activityIndicatorViewStyle = .gray
self.indicator.color = UIColor(red: 80/255, green: 165/255, blue: 247/255, alpha: 1.0)
self.indicator.isUserInteractionEnabled = false
self.indicator.hidesWhenStopped = true
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
let urls = "https://openlibrary.org/api/books?jscmd=data&format=json&bibkeys=ISBN:"+searchBar.text!
let url: NSURL? = NSURL(string: urls)
let sesion: URLSession = URLSession.shared
let bloque = { (datos: Data?, resp: URLResponse?, error: Error?) -> Void in
DispatchQueue.main.async {
searchBar.resignFirstResponder()
}
if (error == nil) {
do {
let json = try JSONSerialization.jsonObject(with: datos! as Data, options: JSONSerialization.ReadingOptions.mutableLeaves)
let dico1 = json as! NSDictionary
if (dico1["ISBN:"+searchBar.text!] != nil) {
self.libro = Libro()
self.libro.isbn = searchBar.text!
DispatchQueue.main.async {
let bodyFontDescriptor = UIFontDescriptor.preferredFontDescriptor(withTextStyle: UIFontTextStyle.body)
let bodyFont = UIFont(descriptor: bodyFontDescriptor, size: 0)
self.textView.font = bodyFont
self.textView.textColor = UIColor.black
self.textView.backgroundColor = UIColor.white
self.textView.isScrollEnabled = true
self.textView.text = ""
self.indicator.autoresizingMask = [.flexibleRightMargin, .flexibleHeight]
self.pending.view.addSubview(self.indicator)
self.indicator.startAnimating()
self.present(self.pending, animated: true, completion: nil)
}
let dico2 = dico1["ISBN:"+searchBar.text!] as! NSDictionary
if (dico2["title"] != nil) {
let titulo = dico2["title"] as! NSString as String
self.libro.titulo = titulo
}
if (dico2["authors"] != nil) {
let autores = dico2["authors"] as! NSArray as Array
let autor0 = autores[0] as! NSDictionary
if (autor0["name"] != nil) {
let textAutor0 = autor0["name"] as! NSString as String
self.libro.autores.append(textAutor0)
for index in 1..<autores.count {
let autor = autores[index] as! NSDictionary
if (autor["name"] != nil) {
let textAutor = autor["name"] as! NSString as String
self.libro.autores.append(textAutor)
}
}
}
}
if (dico2["cover"] != nil) {
let portada = dico2["cover"] as! NSDictionary
if (portada["medium"] != nil) {
let medium = portada["medium"] as! NSString as String
if let checkedUrl = URL(string: medium) {
let data = try? Data(contentsOf: checkedUrl)
let image = UIImage(data: data!)
self.libro.cover = image
}
}
else if (portada["small"] != nil) {
let small = portada["small"] as! NSString as String
if let checkedUrl = URL(string: small) {
let data = try? Data(contentsOf: checkedUrl)
let image = UIImage(data: data!)
self.libro.cover = image
}
}
else if (portada["large"] != nil) {
let large = portada["large"] as! NSString as String
if let checkedUrl = URL(string: large) {
let data = try? Data(contentsOf: checkedUrl)
let image = UIImage(data: data!)
self.libro.cover = image
}
}
}
DispatchQueue.main.async {
self.indicator.stopAnimating()
self.dismiss(animated: true, completion: nil)
self.textView.attributedText = self.libro.getAttributedText()
}
}
else {
DispatchQueue.main.async {
let title = NSLocalizedString("Advertencia", comment: "")
let message = NSLocalizedString("EL ISBN no existe, intente con otro.", comment: "")
let cancelButtonTitle = NSLocalizedString("OK", comment: "")
let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert)
let cancelAction = UIAlertAction(title: cancelButtonTitle, style: .cancel) { action in
NSLog("La alerta acaba de ocurrir.")
}
alertController.addAction(cancelAction)
self.present(alertController, animated: true, completion: nil)
}
}
}
catch let error as NSError {
DispatchQueue.main.async {
let title = NSLocalizedString("Error \(error.code)", comment: "")
let message = NSLocalizedString(error.localizedDescription, comment: "")
let cancelButtonTitle = NSLocalizedString("OK", comment: "")
let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert)
let cancelAction = UIAlertAction(title: cancelButtonTitle, style: .cancel) { action in
NSLog("La alerta acaba de ocurrir.")
}
alertController.addAction(cancelAction)
self.present(alertController, animated: true, completion: nil)
}
}
}
else {
let e = error! as NSError
print(e)
DispatchQueue.main.async {
let title = NSLocalizedString("Error \(e.code)", comment: "")
let message = NSLocalizedString(e.localizedDescription, comment: "")
let cancelButtonTitle = NSLocalizedString("OK", comment: "")
let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert)
let cancelAction = UIAlertAction(title: cancelButtonTitle, style: .cancel) { action in
NSLog("La alerta acaba de ocurrir.")
}
alertController.addAction(cancelAction)
self.present(alertController, animated: true, completion: nil)
}
}
}
let dt: URLSessionDataTask = sesion.dataTask(with: url! as URL, completionHandler: bloque)
dt.resume()
}
func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
self.libro = Libro()
textView.text = ""
searchBar.text = nil
searchBar.resignFirstResponder()
}
@IBAction func cancelar(_ sender: AnyObject) {
self.dismiss(animated: true, completion: nil)
}
@IBAction func agregar(_ sender: UIBarButtonItem) {
if let delegado = self.delegado {
if !self.libro.isEmpty() {
self.libro.isbn = self.libro.isbn?.replacingOccurrences(of: "-", with: "")
let libroEntidad = NSEntityDescription.entity(forEntityName: "LibroEntidad", in: self.contexto!)
let peticion = libroEntidad?.managedObjectModel.fetchRequestFromTemplate(withName: "peticionLibro", substitutionVariables: ["isbn": self.libro.isbn!])
do {
let libroEntidad2: [Any]? = try self.contexto?.fetch(peticion!)
if ((libroEntidad2?.count)! > 0) {
let title = NSLocalizedString("Advertencia", comment: "")
let message = NSLocalizedString("Este libro ya se encuentra en la lista.", comment: "")
let cancelButtonTitle = NSLocalizedString("OK", comment: "")
let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert)
let cancelAction = UIAlertAction(title: cancelButtonTitle, style: .cancel) { action in
NSLog("La alerta acaba de ocurrir.")
}
alertController.addAction(cancelAction)
self.present(alertController, animated: true, completion: nil)
}
else {
delegado.agregarLibro(libro: self.libro)
self.dismiss(animated: true, completion: nil)
}
}
catch let error as NSError {
let title = NSLocalizedString("Error \(error.code)", comment: "")
let message = NSLocalizedString(error.localizedDescription, comment: "")
let cancelButtonTitle = NSLocalizedString("OK", comment: "")
let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert)
let cancelAction = UIAlertAction(title: cancelButtonTitle, style: .cancel) { action in
NSLog("La alerta acaba de ocurrir.")
}
alertController.addAction(cancelAction)
self.present(alertController, animated: true, completion: nil)
}
}
else {
let title = NSLocalizedString("Advertencia", comment: "")
let message = NSLocalizedString("No se buscó algún libro, por lo tanto no se pudo agregar alguno.", comment: "")
let cancelButtonTitle = NSLocalizedString("OK", comment: "")
let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert)
let cancelAction = UIAlertAction(title: cancelButtonTitle, style: .cancel) { action in
NSLog("La alerta acaba de ocurrir.")
}
alertController.addAction(cancelAction)
self.present(alertController, animated: true, completion: nil)
}
}
}
}
| gpl-3.0 | 8b58ced384d6138f1ab652c569436c22 | 54.179916 | 166 | 0.507279 | 5.694301 | false | false | false | false |
keepcalmandcodecodecode/SweetSpinners | Example/Tests/Tests.swift | 1 | 866 | // https://github.com/Quick/Quick
import Quick
import Nimble
import SweetSpinners
class SweetSpinnerSpec: QuickSpec {
override func spec() {
var viewForSpinner:UIView!
beforeEach{
viewForSpinner = UIView()
}
describe("Spinner is show and hides"){
it("view has SweetSpinner in view's hierarchy"){
let spinner = SweetSpinner.show(viewForSpinner, withType: .FadingCircle)
expect(spinner.superview == viewForSpinner)
}
it("SweetSpinner removed from view's hierarchy"){
let spinner = SweetSpinner.show(viewForSpinner, withType: .FadingCircle)
SweetSpinner.hide(viewForSpinner)
let subviews = viewForSpinner.subviews
expect(subviews).toNot(contain(spinner))
}
}
}
}
| mit | a362758510aa06e37a4438335f2bdf6c | 32.307692 | 88 | 0.602771 | 4.948571 | false | false | false | false |
songxing10000/CodeLibrary | Extensions/Swift/UIImageView+Extension.swift | 1 | 2564 | //
// UIImageView+Extension.swift
// SmallVillage
//
// Created by 李 on 16/7/27.
// Copyright © 2016年 chenglv. All rights reserved.
//
import UIKit
import SDWebImage
extension UIImageView {
/// 使用图像名称创建 UIImageView
///
/// - parameter imageName: imageName
///
/// - returns: UIImageView
convenience init(yl_imageName imageName: String) {
self.init(image: UIImage(named: imageName))
}
/// 设置图像 - 隔离框架的方法不用百分百隔离!隔离最重要,最常见的方法,其他方法如果需要更换框架,逐一即可!
///
/// - parameter urlString: urlString
/// - parameter placeholderName: placeholderName
/// - parameter size: 裁切图像的尺寸,默认 CGSizeZero,不裁切
/// - parameter isCorner: 是否圆角裁切,默认不裁切,只有在 size != CGSizeZero 有效
/// - parameter backColor: 背景颜色,默认颜色 白色,只有在 size != CGSizeZero 有效
func yl_setImageWithURL(_ urlString: String?,
placeholderName: String?,
size: CGSize = CGSize.zero,
isCorner: Bool = false,
backColor: UIColor? = UIColor.white) {
// 占位图像
var placeholderImagePhoto: UIImage?
if placeholderName != nil {
placeholderImagePhoto = UIImage(named: placeholderName!)
}
// 如果 url 为 nil
guard let urlString = urlString,
let url = URL(string: urlString) else {
// 如果 urlString 为nil,但是指定了占位图像,显示占位图像
image = placeholderImagePhoto
return
}
// 判断裁切尺寸
if size == CGSize.zero {
sd_setImage(with: url, placeholderImage: placeholderImagePhoto)
return
}
// 对图像进行裁切,提示:从网络不一定能够获取到图像
sd_setImage(with: url) { (image, _, _, _) in
// 1. 判断图像是否存在,如果没有图像直接返回
guard let image = image else {
return
}
// 2. 对图像进行裁切
image.yl_asyncDrawImage(size, isCorner: isCorner, backColor: backColor) { (image) -> () in
self.image = image
}
}
}
}
| mit | 172a71d99b23f6bea720decb3f60e41e | 28.053333 | 102 | 0.519045 | 4.28937 | false | false | false | false |
FengDeng/RXGitHub | RxGitHubAPI/RxGitHubAPI+Repository.swift | 1 | 5449 | //
// RxGitHubAPI+Repository.swift
// RxGitHub
//
// Created by 邓锋 on 16/1/26.
// Copyright © 2016年 fengdeng. All rights reserved.
//
import Foundation
import RxSwift
extension RxGitHubAPI{
/**
List your repositories
List repositories that are accessible to the authenticated user.
This includes repositories owned by the authenticated user, repositories where the authenticated user is a collaborator, and repositories that the authenticated user has access to through an organization membership.
- parameter page: page
- parameter visibility: Can be one of all, public, or private. Default: all
- parameter affiliation: Comma-separated list of values. Can include:
* owner: Repositories that are owned by the authenticated user.
* collaborator: Repositories that the user has been added to as a collaborator.
* organization_member: Repositories that the user has access to through being a member of an organization. This includes every repository on every team that the user is on.
Default: owner,collaborator,organization_member
- parameter type: Can be one of all, owner, public, private, member. Default: all
Will cause a 422 error if used in the same request as visibility or affiliation.
give it up
- parameter sort: Can be one of created, updated, pushed, full_name. Default: full_name
- parameter direction: Can be one of asc or desc. Default:desc
- returns: Observable<[YYRepository]>
*/
static func listYourRepos(page:Int = 1,visibility:YYVisibility = YYVisibility.All,affiliation:YYAffiliation = YYAffiliation.Owner_Collaborator_Organization_member,type:YYType = YYType.All,sort:YYSort = YYSort.Full_name,direction:YYDirection = YYDirection.Desc)->Observable<[YYRepository]>{
return yyRepositoryAPI.request(YYRepositoryAPI.YourRepositories(page: page, visibility: visibility, affiliation: affiliation, type: type, sort: sort, direction: direction)).mapArrayWithClass(YYRepository)
}
/**
List user repositories
List public repositories for the specified user.
- parameter owner: owner
- parameter page: page
- parameter type: Can be one of all, owner, member. Default: owner
- parameter sort: Can be one of created, updated, pushed, full_name. Default: full_name
- parameter direction: Can be one of asc or desc. Default: desc
- returns: Observable<[YYRepository]>
*/
static func listUserRepos(owner:String,page:Int = 1,type:YYType = YYType.Owner,sort:YYSort = YYSort.Full_name,direction:YYDirection = YYDirection.Desc)->Observable<[YYRepository]>{
return yyRepositoryAPI.request(YYRepositoryAPI.UserRepositories(owner: owner, page: page, type: type, sort: sort, direction: direction)).mapArrayWithClass(YYRepository)
}
/**
List organization repositories
List repositories for the specified org.
- parameter orgs: orgs
- parameter type: Can be one of all, public, private, forks, sources, member. Default: all
- parameter page: page
- returns: Observable<[YYRepository]>
*/
static func listOrgsRepos(orgs:String,type:YYType = YYType.All,page:Int = 1)->Observable<[YYRepository]>{
return yyRepositoryAPI.request(YYRepositoryAPI.OrganizationRepositories(orgs: orgs, page: page, type: type)).mapArrayWithClass(YYRepository)
}
/**
List all public repositories
This provides a dump of every public repository, in the order that they were created.
- parameter since: The integer ID of the last Repository that you've seen.
- returns: Observable<[YYRepository]>
*/
static func listPublicRepos(since:String = "")->Observable<[YYRepository]>{
return yyRepositoryAPI.request(YYRepositoryAPI.PublicRepositories(since: since)).mapArrayWithClass(YYRepository)
}
/**
List languages
List languages for the specified repository. The value on the right of a language is the number of bytes of code written in that language.
- parameter owner: owner description
- parameter repo: repo description
- returns: Dictionary<String,AnyObject>
*/
static func listLanguages(owner:String,repo:String)->Observable<Dictionary<String,AnyObject>>{
return yyRepositoryAPI.request(YYRepositoryAPI.Languages(owner: owner, repo: repo)).mapToJSON()
}
//fix me
static func listTeams(owner:String,repo:String,page:Int = 1)->Observable<[YYTeam]>{
return yyRepositoryAPI.request(YYRepositoryAPI.Teams(owner: "FengDeng", repo: "SwiftDrawBoard",page:page)).mapArrayWithClass(YYTeam)
}
/**
List Tags
- parameter owner: owner description
- parameter repo: repo description
- parameter page: page description
- returns: Observable<[YYTeam]
*/
static func listTags(owner:String,repo:String,page:Int = 1)->Observable<[YYTeam]>{
return yyRepositoryAPI.request(YYRepositoryAPI.Tags(owner: owner, repo: repo,page:page)).mapArrayWithClass(YYTeam)
}
//fix me
static func listBranches(owner:String,repo:String,page:Int = 1)->Observable<[YYTeam]>{
return yyRepositoryAPI.request(YYRepositoryAPI.Branches(owner: owner, repo: repo,page:page)).mapArrayWithClass(YYTeam)
}
} | mit | a69592ac1eae93cde1a1abb8aa3a1cca | 43.252033 | 293 | 0.701948 | 4.482702 | false | false | false | false |
mgigirey/iBeaconSwiftOSX | iBeaconSwiftOSX/ViewController.swift | 2 | 5822 | //
// ViewController.swift
// iBeaconSwiftOSX
//
// Created by Marcelo Gigirey on 11/9/14.
// Copyright (c) 2014 Marcelo Gigirey. 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 Cocoa
import Foundation
import CoreBluetooth
class ViewController: NSViewController, CBTransmitterDelegate {
// Properties
var isAdvertising: Bool?
//var isReadyForAdvertising : Bool?
var transmitter : CBBeaconTransmitter?
// Constants
let kCBUserDefaultsUDID = "kCBUserDefaultsUDID"
let kCBCUserDefaultsMajor = "kCBCUserDefaultsMajor"
let kCBCUserDefaultsMinor = "kCBCUserDefaultsMinor"
let kCBCUserDefaultsMeasuredPower = "kCBCUserDefaultsMeasuredPower"
@IBOutlet weak var uuidTextField: NSTextFieldCell!
@IBOutlet weak var majorTextField: NSTextField!
@IBOutlet weak var minorTextField: NSTextField!
@IBOutlet weak var measuredPowerTextField: NSTextField!
@IBOutlet weak var generateUUIDButton: NSButton!
@IBOutlet weak var startButton: NSButton!
override func viewDidLoad() {
super.viewDidLoad()
isAdvertising = false
//isReadyForAdvertising = false
transmitter = CBBeaconTransmitter()
transmitter?.delegate = self
// Retrieve Values from NSUserDefaults
loadUserDefaults()
}
override var representedObject: AnyObject? {
didSet {
// Update the view, if already loaded.
}
}
func loadUserDefaults() {
var udid : NSString? = NSUserDefaults.standardUserDefaults().stringForKey(kCBUserDefaultsUDID)
if udid != nil {
uuidTextField.stringValue = "\(udid!)"
}
var major : NSString? = NSUserDefaults.standardUserDefaults().stringForKey(kCBCUserDefaultsMajor)
if major != nil {
majorTextField.stringValue = "\(major!)"
}
var minor : NSString? = NSUserDefaults.standardUserDefaults().stringForKey(kCBCUserDefaultsMinor)
if minor != nil {
minorTextField.stringValue = "\(minor!)"
}
var measuredPower : NSString? = NSUserDefaults.standardUserDefaults().stringForKey(kCBCUserDefaultsMeasuredPower)
if measuredPower != nil {
measuredPowerTextField.stringValue = "\(measuredPower!)"
}
}
@IBAction func startButtonClicked(sender: AnyObject) {
// Transmit
if !isAdvertising! {
// Store Values in NSUserDefaults
NSUserDefaults.standardUserDefaults().setObject(uuidTextField.stringValue, forKey: kCBUserDefaultsUDID)
NSUserDefaults.standardUserDefaults().setObject(majorTextField.stringValue, forKey: kCBCUserDefaultsMajor)
NSUserDefaults.standardUserDefaults().setObject(minorTextField.stringValue, forKey: kCBCUserDefaultsMinor)
NSUserDefaults.standardUserDefaults().setObject(measuredPowerTextField.stringValue, forKey: kCBCUserDefaultsMeasuredPower)
transmitAsBeacon()
}
else {
stopBeacon()
}
}
@IBAction func genereateUUIDClicked(sender: AnyObject) {
uuidTextField.stringValue = "\(NSUUID().UUIDString)"
}
// Transmit as iBeacon
func transmitAsBeacon() {
transmitter?.setUpBeacon(proximityUUID: NSUUID(UUIDString: uuidTextField.stringValue)!,
major: UInt16(majorTextField.integerValue),
minor: UInt16(minorTextField.integerValue),
measuredPower: Int8(measuredPowerTextField.integerValue))
transmitter?.startTransmitting()
}
func stopBeacon() {
transmitter?.stopTransmitting()
}
func toggleControls(beaconStatus: BeaconStatus) {
switch beaconStatus
{
case .Advertising:
startButton.title = "Turn iBeacon off"
startButton.enabled = true
enableControls(false)
case .NotAdvertising:
startButton.title = "Turn iBeacon on"
startButton.enabled = true
enableControls(true)
case .ResumeAdvertise:
transmitAsBeacon()
startButton.enabled = true
enableControls(false)
case .CannotAdvertise:
startButton.enabled = false
enableControls(false)
}
}
func enableControls(enabled: Bool) {
generateUUIDButton.enabled = enabled
uuidTextField.enabled = enabled
majorTextField.enabled = enabled
minorTextField.enabled = enabled
measuredPowerTextField.enabled = enabled
}
func transmitterDidPoweredOn(isPoweredOn: Bool) {
if isPoweredOn {
toggleControls(isAdvertising! ? BeaconStatus.ResumeAdvertise : BeaconStatus.NotAdvertising)
}
else {
toggleControls(BeaconStatus.CannotAdvertise)
}
}
func transmitterDidStartAdvertising(isAdvertising: Bool) {
self.isAdvertising = isAdvertising
toggleControls(isAdvertising == true ? BeaconStatus.Advertising : BeaconStatus.NotAdvertising)
}
enum BeaconStatus {
case Advertising
case NotAdvertising
case ResumeAdvertise
case CannotAdvertise
}
} | apache-2.0 | a0b751f5d0ca4b9b8cf5a20d9471d8f8 | 34.078313 | 134 | 0.662144 | 5.240324 | false | false | false | false |
cpuu/OTT | BlueCapKit/Service Profile Definitions/GnosusProfiles.swift | 1 | 7681 | //
// GnosusProfiles.swift
// BlueCap
//
// Created by Troy Stribling on 7/25/14.
// Copyright (c) 2014 Troy Stribling. The MIT License (MIT).
//
import Foundation
import CoreBluetooth
// MARK: - Gnosus -
public struct Gnosus {
// MARK: - Hello World Service -
public struct HelloWorldService: BCServiceConfigurable {
// ServiceConfigurable
public static let UUID = "2f0a0000-69aa-f316-3e78-4194989a6c1a"
public static let name = "Hello World"
public static let tag = "gnos.us"
public struct Greeting : BCCharacteristicConfigurable {
// BLEConfigurable
public static let UUID = "2f0a0001-69aa-f316-3e78-4194989a6c1a"
public static let name = "Hello World Greeting"
public static let permissions: CBAttributePermissions = [.Readable, .Writeable]
public static let properties: CBCharacteristicProperties = [.Read, .Notify]
public static let initialValue = BCSerDe.serialize("Hello")
}
public struct UpdatePeriod: BCRawDeserializable, BCCharacteristicConfigurable, BCStringDeserializable {
public let period : UInt16
// CharacteristicConfigurable
public static let UUID = "2f0a0002-69aa-f316-3e78-4194989a6c1a"
public static let name = "Update Period"
public static let permissions: CBAttributePermissions = [.Readable, .Writeable]
public static let properties: CBCharacteristicProperties = [.Read, .Write]
public static let initialValue: NSData? = BCSerDe.serialize(UInt16(5000))
// RawDeserializable
public var rawValue: UInt16 {
return self.period
}
public init?(rawValue: UInt16) {
self.period = rawValue
}
// StringDeserializable
public static var stringValues: [String] {
return []
}
public var stringValue: [String: String] {
return [UpdatePeriod.name:"\(self.period)"]
}
public init?(stringValue: [String: String]) {
if let value = uint16ValueFromStringValue(UpdatePeriod.name, values:stringValue) {
self.period = value
} else {
return nil
}
}
}
}
// MARK: - Location Service -
public struct LocationService: BCServiceConfigurable {
// ServiceConfigurable
public static let UUID = "2f0a0001-69aa-f316-3e78-4194989a6c1a"
public static let name = "Location"
public static let tag = "gnos.us"
public struct LatitudeAndLongitude : BCRawArrayDeserializable, BCCharacteristicConfigurable, BCStringDeserializable {
private let latitudeRaw: Int16
private let longitudeRaw: Int16
public let latitude: Double
public let longitude: Double
public init?(latitude: Double, longitude: Double) {
self.latitude = latitude
self.longitude = longitude
if let rawValues = LatitudeAndLongitude.rawFromValues([latitude, longitude]) {
(self.latitudeRaw, self.longitudeRaw) = rawValues
} else {
return nil
}
}
private static func valuesFromRaw(rawValues: [Int16]) -> (Double, Double) {
return (100.0*Double(rawValues[0]), 100.0*Double(rawValues[1]))
}
private static func rawFromValues(values: [Double]) -> (Int16, Int16)? {
let latitudeRaw = Int16(doubleValue: values[0]/100.0)
let longitudeRaw = Int16(doubleValue: values[1]/100.0)
if latitudeRaw != nil && longitudeRaw != nil {
return (latitudeRaw!, longitudeRaw!)
} else {
return nil
}
}
// CharacteristicConfigurable
public static let UUID = "2f0a0017-69aa-f316-3e78-4194989a6c1a"
public static let name = "Lattitude and Longitude"
public static let permissions: CBAttributePermissions = [.Readable, .Writeable]
public static let properties: CBCharacteristicProperties = [.Read, .Write]
public static let initialValue: NSData? = BCSerDe.serialize(Gnosus.LocationService.LatitudeAndLongitude(latitude:37.752760, longitude:-122.413234)!)
// RawArrayDeserializable
public static let size = 4
public var rawValue: [Int16] {
return [self.latitudeRaw, self.longitudeRaw]
}
public init?(rawValue: [Int16]) {
if rawValue.count == 2 {
self.latitudeRaw = rawValue[0]
self.longitudeRaw = rawValue[1]
(self.latitude, self.longitude) = LatitudeAndLongitude.valuesFromRaw(rawValue)
} else {
return nil
}
}
// StringDeserializable
public static var stringValues: [String] {
return []
}
public var stringValue: [String: String] {
return ["latitudeRaw":"\(self.latitudeRaw)",
"longitudeRaw":"\(self.longitudeRaw)",
"latitude":"\(self.latitude)",
"longitude":"\(self.longitude)"]
}
public init?(stringValue: [String: String]) {
let lat = int16ValueFromStringValue("latitudeRaw", values: stringValue)
let lon = int16ValueFromStringValue("longitudeRaw", values: stringValue)
if lat != nil && lon != nil {
self.latitudeRaw = lat!
self.longitudeRaw = lon!
(self.latitude, self.longitude) = LatitudeAndLongitude.valuesFromRaw([self.latitudeRaw, self.longitudeRaw])
} else {
return nil
}
}
}
}
}
// MARK: - Profile Definition -
public struct GnosusProfiles {
public static func create() {
let profileManager = BCProfileManager.sharedInstance
// Hello World Service
let helloWorldService = BCConfiguredServiceProfile<Gnosus.HelloWorldService>()
let greetingCharacteristic = BCStringCharacteristicProfile<Gnosus.HelloWorldService.Greeting>()
let updateCharacteristic = BCRawCharacteristicProfile<Gnosus.HelloWorldService.UpdatePeriod>()
helloWorldService.addCharacteristic(greetingCharacteristic)
helloWorldService.addCharacteristic(updateCharacteristic)
profileManager.addService(helloWorldService)
// Location Service
let locationService = BCConfiguredServiceProfile<Gnosus.LocationService>()
let latlonCharacteristic = BCRawArrayCharacteristicProfile<Gnosus.LocationService.LatitudeAndLongitude>()
locationService.addCharacteristic(latlonCharacteristic)
profileManager.addService(locationService)
}
}
| mit | ac52a9279097a793afd3b80adfad6602 | 39.856383 | 180 | 0.554485 | 5.474697 | false | true | false | false |
ZeeQL/ZeeQL3 | Sources/ZeeQL/Control/QueryBuilder.swift | 1 | 3417 | //
// QueryBuilder.swift
// ZeeQL
//
// Created by Helge Hess on 06/03/17.
// Copyright © 2017-2019 ZeeZide GmbH. All rights reserved.
//
// MARK: - Fetch Specification Convenience
public extension FetchSpecification {
// MARK: - Qualifiers
func `where`(_ q: Qualifier) -> FetchSpecification {
var fs = self
fs.qualifier = q
return fs
}
func and(_ q: Qualifier?) -> FetchSpecification {
var fs = self
fs.qualifier = ZeeQL.and(fs.qualifier, q)
return fs
}
func or(_ q: Qualifier?) -> FetchSpecification {
var fs = self
fs.qualifier = ZeeQL.or(fs.qualifier, q)
return fs
}
func `where`(_ q: String, _ args: Any?...) -> FetchSpecification {
var fs = self
let parser = QualifierParser(string: q, arguments: args)
fs.qualifier = parser.parseQualifier()
return fs
}
func and(_ q: String, _ args: Any?...) -> FetchSpecification {
var fs = self
let parser = QualifierParser(string: q, arguments: args)
fs.qualifier = ZeeQL.and(fs.qualifier, parser.parseQualifier())
return fs
}
func or(_ q: String, _ args: Any?...) -> FetchSpecification {
var fs = self
let parser = QualifierParser(string: q, arguments: args)
fs.qualifier = ZeeQL.or(fs.qualifier, parser.parseQualifier())
return fs
}
// MARK: - Limits
func limit(_ value : Int) -> FetchSpecification {
var fs = self
fs.fetchLimit = value
return fs
}
func offset(_ value : Int) -> FetchSpecification {
var fs = self
fs.fetchOffset = value
return fs
}
// MARK: - Prefetches
func prefetch(_ path: String, _ more: String...) -> FetchSpecification {
var fs = self
fs.prefetchingRelationshipKeyPathes = [ path ] + more
return fs
}
// MARK: - Ordering
func order(by: SortOrdering, _ e: SortOrdering...) -> FetchSpecification {
var fs = self
if let old = fs.sortOrderings {
fs.sortOrderings = old + [ by ] + e
}
else {
fs.sortOrderings = [ by ] + e
}
return fs
}
func order(by: String, _ e: String...) -> FetchSpecification {
var fs = self
var ops = [ SortOrdering ]()
if let p = SortOrdering.parse(by) {
ops += p
}
for by in e {
if let p = SortOrdering.parse(by) {
ops += p
}
}
guard !ops.isEmpty else { return self }
if let old = fs.sortOrderings {
fs.sortOrderings = old + ops
}
else {
fs.sortOrderings = ops
}
return fs
}
}
public extension FetchSpecification { // Qualifier Convenience Methods
mutating func conjoin(qualifier: Qualifier) {
if let q = self.qualifier { self.qualifier = q.and(qualifier) }
else { self.qualifier = qualifier }
}
mutating func disjoin(qualifier: Qualifier) {
if let q = self.qualifier { self.qualifier = q.or(qualifier) }
else { self.qualifier = qualifier }
}
mutating func setQualifier(_ format: String, _ args: String...) {
qualifier = qualifierWith(format: format, args)
}
mutating func conjoin(_ format: String, _ args: String...) {
guard let q = qualifierWith(format: format, args) else { return }
conjoin(qualifier: q)
}
mutating func disjoin(_ format: String, _ args: String...) {
guard let q = qualifierWith(format: format, args) else { return }
disjoin(qualifier: q)
}
}
| apache-2.0 | 9c74a24d64182512373a52da89d414fb | 24.117647 | 76 | 0.604508 | 3.851184 | false | false | false | false |
a178960320/MyDouyu | Douyu/Douyu/Classes/Home/Controller/HomeLiveViewController.swift | 1 | 2129 | //
// HomeLiveViewController.swift
// Douyu
//
// Created by 住梦iOS on 2017/3/1.
// Copyright © 2017年 qiongjiwuxian. All rights reserved.
//
import UIKit
class HomeLiveViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
//1.拿到系统pop的手势
guard let systemGes = self.navigationController?.interactivePopGestureRecognizer else{return}
//2.获取手势添加到view中
guard let gesView = systemGes.view else { return }
//3.获取target/action
//3.1利用运行时查看所有属性的名称
/*
var count:UInt32 = 0
let ivars = class_copyIvarList(UIGestureRecognizer.self, &count)!
for i in 0..<count{
let ivar = ivars[Int(i)]
let name = ivar_getName(ivar)
print(String(cString:name!))
}
*/
let targets = systemGes.value(forKey: "_targets") as? [NSObject]
guard let targetObjc = targets?.first else { return }
print(targetObjc)
//3.2取出target
guard let target = targetObjc.value(forKey: "target") else { return}
//3.3
let action = Selector(("handleNavigationTransition:"))
//4.创建自己的手势
let panGes = UIPanGestureRecognizer()
gesView.addGestureRecognizer(panGes)
panGes.addTarget(target, action: action)
self.view.backgroundColor = UIColor.orange
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| mit | 41108821e857995daa13fc94f0ed57b6 | 28.171429 | 106 | 0.610676 | 4.630385 | false | false | false | false |
dshamany/CIToolbox | CIToolbox/FormContact.swift | 1 | 7770 | //
// FormContact.swift
// CIToolbox
//
// Created by Daniel Shamany on 6/21/17.
// Copyright © 2017 Daniel Shamany. All rights reserved.
//
import UIKit
class FormContact: UIViewController {
//-------------------------------------------------------------------------------
//MARK: Form Objects
@IBOutlet weak var firstName1Text: UITextField!
@IBOutlet weak var lastName1Text: UITextField!
@IBOutlet weak var phone1Text: UITextField!
@IBOutlet weak var email1Text: UITextField!
//MARK: Error objects
@IBOutlet weak var firstNameMissingLabel: UILabel!
@IBOutlet weak var lastNameMissingLabel: UILabel!
@IBOutlet weak var phoneMissingLabel: UILabel!
//MARK: Second Homeowner Information
@IBOutlet weak var firstName2Text: UITextField!
@IBOutlet weak var lastName2Text: UITextField!
@IBOutlet weak var phone2Text: UITextField!
@IBOutlet weak var email2Text: UITextField!
//MARK: Secondary Homeowner Variable
var secondary: Bool = false
//MARK: Object Locations
@IBOutlet weak var mainHorizontalConstraint: NSLayoutConstraint!
@IBOutlet weak var mainVerticalConstraint: NSLayoutConstraint!
@IBOutlet weak var secondaryHorizontalConstraint: NSLayoutConstraint!
//MARK: SubViews
@IBOutlet weak var mainSubView: UIVisualEffectView!
@IBOutlet weak var secondarySubView: UIVisualEffectView!
@IBOutlet weak var enableSecondaryButtonOutlet: UIButton!
func setInterface(){
mainSubView.layer.cornerRadius = 10
mainSubView.layer.masksToBounds = true
secondarySubView.layer.cornerRadius = 10
secondarySubView.layer.masksToBounds = true
}
//Homeowner Object
var fromPrevious: Lead!
override func viewDidLoad() {
super.viewDidLoad()
setInterface()
firstName1Text.becomeFirstResponder()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
alertFunction(title: "Memory Error.", msg: "Memory is full, please quit the app completely and restart it.")
}
func formatPhoneNumber(input: String) -> String{
var res: [String] = [""]
//Read numbers only
for i in input.characters{
if (i == "0" || i == "1" || i == "2" || i == "3" || i == "4" || i == "5" || i == "6" || i == "7" || i == "8" || i == "9"){
res.append(String(i))
}
}
if input == "" {
return ""
} else if res.count < 11 {
alertFunction(title: "Oops!", msg: "Phone number too short")
phoneMissingLabel.isHidden = false
return input
} else if res.count > 11 {
alertFunction(title: "Oops!", msg: "Phone number too long")
phoneMissingLabel.isHidden = false
return input
} else {
return res[1] + res[2] + res[3] + "-" + res[4] + res[5] + res[6] + "-" + res[7] + res[8] + res[9] + res[10]
}
}
func formComplete() -> Bool {
var isComplete = false
if (fromPrevious.Status == "Lead"){
if (firstName1Text.text == ""){
firstNameMissingLabel.isHidden = false
isComplete = false
} else {
isComplete = true
}
if (lastName1Text.text == ""){
lastNameMissingLabel.isHidden = false
isComplete = false
} else {
isComplete = true
}
if (phone1Text.text == ""){
phoneMissingLabel.isHidden = false
isComplete = false
} else {
isComplete = true
}
}
return isComplete
}
func moveObjects(){
if (!secondary){
secondarySubView.isHidden = true
mainHorizontalConstraint.constant = 0
} else {
secondarySubView.isHidden = false
mainHorizontalConstraint.constant = -179
}
}
@IBAction func enableSecondary(_ sender: Any) {
if (secondary){
secondary = false
enableSecondaryButtonOutlet.setTitle("Secondary Homeowner?", for: .normal)
firstName2Text.text = ""
moveObjects()
secondarySubView.alpha = 0.0
} else {
secondary = true
enableSecondaryButtonOutlet.setTitle("Single Owner?", for: .normal)
lastName2Text.text = lastName1Text.text!
moveObjects()
secondarySubView.alpha = 1.0
}
}
@IBAction func tapAnywhere(_ sender: Any) {
self.view.endEditing(true)
}
@IBAction func goToNext(_ sender: Any) {
fromPrevious.First_1 = firstName1Text.text!
fromPrevious.Last_1 = lastName1Text.text!
fromPrevious.Phone_1 = phone1Text.text!
fromPrevious.Email_1 = email1Text.text!
fromPrevious.First_2 = firstName2Text.text!
fromPrevious.Last_2 = lastName2Text.text!
fromPrevious.Phone_2 = phone2Text.text!
fromPrevious.Email_2 = email2Text.text!
if (formComplete()){
performSegue(withIdentifier: "toAppointmentForm", sender: fromPrevious)
}
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "toAppointmentForm"{
if let destination = segue.destination as? FormAppointment {
destination.fromPrevious = sender as! Lead
}
}
}
// --------------------------------------------------------------------------------
//MARK: TEXTFIELD RETURN-KEY
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
switch (textField){
case firstName1Text:
lastName1Text.becomeFirstResponder()
break
case lastName1Text:
phone1Text.becomeFirstResponder()
break
case phone1Text:
email1Text.becomeFirstResponder()
break
case email1Text:
if(secondary){
firstName2Text.becomeFirstResponder()
} else {
goToNext(self)
}
break
case firstName2Text:
lastName2Text.becomeFirstResponder()
break
case lastName2Text:
phone2Text.becomeFirstResponder()
break
case phone2Text:
email2Text.becomeFirstResponder()
break
case email2Text:
goToNext(self)
break
default:
self.view.endEditing(true)
}
return true
}
func textFieldDidBeginEditing(_ textField: UITextField){
firstNameMissingLabel.isHidden = true
lastNameMissingLabel.isHidden = true
phoneMissingLabel.isHidden = true
if(UIDeviceOrientationIsLandscape(UIDevice.current.orientation)){
mainVerticalConstraint.constant = -150
}
switch(textField){
case phone1Text:
break;
case email1Text:
phone1Text.text = formatPhoneNumber(input: phone1Text.text!)
break;
case phone2Text:
break;
case email2Text:
phone2Text.text = formatPhoneNumber(input: phone2Text.text!)
break;
default:
break;
}
}
func textFieldDidEndEditing(_ textField: UITextField){
if(UIDeviceOrientationIsLandscape(UIDevice.current.orientation)){
mainVerticalConstraint.constant = 0
}
}
}
| gpl-3.0 | aae40ba8630dc1ca2207483035122fe9 | 30.581301 | 134 | 0.55966 | 5.104468 | false | false | false | false |
wangkai678/WKDouYuZB | WKDouYuZB/WKDouYuZB/Classes/Home/Controller/AmuseViewController.swift | 1 | 1260 | //
// AmuseViewController.swift
// WKDouYuZB
//
// Created by wangkai on 2017/5/31.
// Copyright © 2017年 wk. All rights reserved.
//
import UIKit
private let kMenuViewH : CGFloat = 200
class AmuseViewController: BaseAnchorViewController {
fileprivate lazy var amuseVM : AmuseViewModel = AmuseViewModel()
fileprivate lazy var menuView : AmuseMenuView = {
let menuView = AmuseMenuView.amuseMenuView()
menuView.frame = CGRect(x: 0, y: -kMenuViewH, width: kScreenW, height: kMenuViewH)
return menuView
}()
override func viewDidLoad() {
super.viewDidLoad()
}
}
//MARK: - 设置UI界面
extension AmuseViewController{
override func setupUI() {
super.setupUI()
collectionView.addSubview(menuView)
collectionView.contentInset = UIEdgeInsetsMake(kMenuViewH, 0, 0, 0)
}
}
//MARK: - 请求数据
extension AmuseViewController{
override func loadData(){
baseVM = amuseVM;
amuseVM.loadAmuseData {
self.collectionView.reloadData()
var tempGrous = self.amuseVM.anchorGroups
tempGrous.removeFirst()
self.menuView.groups = tempGrous
self.loadDataFinished()
}
}
}
| mit | dc71266825ddb3336beb086184d31fdc | 21.563636 | 90 | 0.64303 | 4.630597 | false | false | false | false |
nalexn/ViewInspector | Sources/ViewInspector/SwiftUI/SecureField.swift | 1 | 2430 | import SwiftUI
@available(iOS 13.0, macOS 10.15, tvOS 13.0, *)
public extension ViewType {
struct SecureField: KnownViewType {
public static var typePrefix: String = "SecureField"
}
}
// MARK: - Extraction from SingleViewContent parent
@available(iOS 13.0, macOS 10.15, tvOS 13.0, *)
public extension InspectableView where View: SingleViewContent {
func secureField() throws -> InspectableView<ViewType.SecureField> {
return try .init(try child(), parent: self)
}
}
// MARK: - Extraction from MultipleViewContent parent
@available(iOS 13.0, macOS 10.15, tvOS 13.0, *)
public extension InspectableView where View: MultipleViewContent {
func secureField(_ index: Int) throws -> InspectableView<ViewType.SecureField> {
return try .init(try child(at: index), parent: self, index: index)
}
}
// MARK: - Non Standard Children
@available(iOS 13.0, macOS 10.15, tvOS 13.0, *)
extension ViewType.SecureField: SupplementaryChildrenLabelView { }
// MARK: - Custom Attributes
@available(iOS 13.0, macOS 10.15, tvOS 13.0, *)
public extension InspectableView where View == ViewType.SecureField {
func labelView() throws -> InspectableView<ViewType.ClassifiedView> {
return try View.supplementaryChildren(self).element(at: 0)
.asInspectableView(ofType: ViewType.ClassifiedView.self)
}
func input() throws -> String {
return try inputBinding().wrappedValue
}
func setInput(_ value: String) throws {
try guardIsResponsive()
try inputBinding().wrappedValue = value
}
private func inputBinding() throws -> Binding<String> {
if let binding = try? Inspector.attribute(
label: "text", value: content.view, type: Binding<String>.self) {
return binding
}
return try Inspector.attribute(
label: "_text", value: content.view, type: Binding<String>.self)
}
func callOnCommit() throws {
typealias Callback = () -> Void
let callback: Callback = try {
if let value = try? Inspector
.attribute(label: "onCommit", value: content.view, type: Callback.self) {
return value
}
return try Inspector
.attribute(path: "deprecatedActions|some|commit", value: content.view, type: Callback.self)
}()
callback()
}
}
| mit | 79089c34d2e8f359cbeb342fed734bcf | 30.973684 | 107 | 0.642798 | 4.354839 | false | false | false | false |
toohotz/IQKeyboardManager | Demo/Swift_Demo/ViewController/SearchViewController.swift | 1 | 4877 | //
// SearchViewController.swift
// Demo
//
// Created by IEMacBook01 on 16/06/16.
// Copyright © 2016 Iftekhar. All rights reserved.
//
import UIKit
class SearchViewController: UITableViewController, UISearchResultsUpdating, UISearchBarDelegate {
let dataList = [["name":"David Smith","email":"[email protected]"],
["name":"Kevin John","email":"[email protected]"],
["name":"Jacob Brown","email":"[email protected]"],
["name":"Paul Johnson","email":"[email protected]"],
["name":"Sam William","email":"[email protected]"],
["name":"Brian Taylor","email":"[email protected]"],
["name":"Charles Smith","email":"[email protected]"],
["name":"Andrew White","email":"[email protected]"],
["name":"Matt Thomas","email":"[email protected]"],
["name":"Michael Clark","email":"[email protected]"]]
var filteredList = [[String:String]]()
let searchController = UISearchController()
override func viewDidLoad() {
super.viewDidLoad()
self.searchController.searchResultsUpdater = self
self.searchController.dimsBackgroundDuringPresentation = false
self.searchController.searchBar.scopeButtonTitles = ["All", "Name", "Email"]
self.searchController.searchBar.delegate = self
self.searchController.searchBar.sizeToFit()
self.tableView.tableHeaderView = self.searchController.searchBar
self.definesPresentationContext = true
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
}
func searchForText(searchText:String?, scope:Int) {
if let text = searchText {
if (text.characters.count != 0)
{
if (scope == 0)
{
self.filteredList = self.dataList.filter({ (obj : [String : String]) -> Bool in
if obj["name"]?.containsString(text) == true || obj["email"]?.containsString(text) == true {
return true
} else {
return false
}
})
}
else if (scope == 1)
{
self.filteredList = self.dataList.filter({ (obj : [String : String]) -> Bool in
if obj["name"]?.containsString(text) == true || obj["email"]?.containsString(text) == true {
return true
} else {
return false
}
})
}
else if (scope == 2)
{
self.filteredList = self.dataList.filter({ (obj : [String : String]) -> Bool in
if obj["email"]?.containsString(text) == true {
return true
} else {
return false
}
})
}
}
else
{
self.filteredList = self.dataList;
}
}
}
func updateSearchResultsForSearchController(searchController: UISearchController) {
self.searchForText(searchController.searchBar.text, scope: searchController.searchBar.selectedScopeButtonIndex)
self.tableView.reloadData()
}
func searchBar(searchBar: UISearchBar, selectedScopeButtonIndexDidChange selectedScope: Int) {
self.updateSearchResultsForSearchController(self.searchController)
}
// MARK: - Table view data source
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if searchController.active == false {
return dataList.count
} else {
return filteredList.count
}
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCellWithIdentifier("UITableViewCell")
if cell == nil {
cell = UITableViewCell(style: .Subtitle, reuseIdentifier: "UITableViewCell")
}
if searchController.active == false {
cell?.textLabel?.text = dataList[indexPath.row]["name"];
cell?.detailTextLabel?.text = dataList[indexPath.row]["email"];
} else {
cell?.textLabel?.text = filteredList[indexPath.row]["name"];
cell?.detailTextLabel?.text = filteredList[indexPath.row]["email"];
}
return cell!
}
}
| mit | fb826b9c642e9675e375aaa35bc9786a | 37.09375 | 119 | 0.528712 | 5.636994 | false | false | false | false |
zbw209/- | StudyNotes/Pods/Alamofire/Source/ResponseSerialization.swift | 5 | 38375 | //
// ResponseSerialization.swift
//
// Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
// MARK: Protocols
/// The type to which all data response serializers must conform in order to serialize a response.
public protocol DataResponseSerializerProtocol {
/// The type of serialized object to be created.
associatedtype SerializedObject
/// Serialize the response `Data` into the provided type..
///
/// - Parameters:
/// - request: `URLRequest` which was used to perform the request, if any.
/// - response: `HTTPURLResponse` received from the server, if any.
/// - data: `Data` returned from the server, if any.
/// - error: `Error` produced by Alamofire or the underlying `URLSession` during the request.
///
/// - Returns: The `SerializedObject`.
/// - Throws: Any `Error` produced during serialization.
func serialize(request: URLRequest?, response: HTTPURLResponse?, data: Data?, error: Error?) throws -> SerializedObject
}
/// The type to which all download response serializers must conform in order to serialize a response.
public protocol DownloadResponseSerializerProtocol {
/// The type of serialized object to be created.
associatedtype SerializedObject
/// Serialize the downloaded response `Data` from disk into the provided type..
///
/// - Parameters:
/// - request: `URLRequest` which was used to perform the request, if any.
/// - response: `HTTPURLResponse` received from the server, if any.
/// - fileURL: File `URL` to which the response data was downloaded.
/// - error: `Error` produced by Alamofire or the underlying `URLSession` during the request.
///
/// - Returns: The `SerializedObject`.
/// - Throws: Any `Error` produced during serialization.
func serializeDownload(request: URLRequest?, response: HTTPURLResponse?, fileURL: URL?, error: Error?) throws -> SerializedObject
}
/// A serializer that can handle both data and download responses.
public protocol ResponseSerializer: DataResponseSerializerProtocol & DownloadResponseSerializerProtocol {
/// `DataPreprocessor` used to prepare incoming `Data` for serialization.
var dataPreprocessor: DataPreprocessor { get }
/// `HTTPMethod`s for which empty response bodies are considered appropriate.
var emptyRequestMethods: Set<HTTPMethod> { get }
/// HTTP response codes for which empty response bodies are considered appropriate.
var emptyResponseCodes: Set<Int> { get }
}
/// Type used to preprocess `Data` before it handled by a serializer.
public protocol DataPreprocessor {
/// Process `Data` before it's handled by a serializer.
/// - Parameter data: The raw `Data` to process.
func preprocess(_ data: Data) throws -> Data
}
/// `DataPreprocessor` that returns passed `Data` without any transform.
public struct PassthroughPreprocessor: DataPreprocessor {
public init() {}
public func preprocess(_ data: Data) throws -> Data { return data }
}
/// `DataPreprocessor` that trims Google's typical `)]}',\n` XSSI JSON header.
public struct GoogleXSSIPreprocessor: DataPreprocessor {
public init() {}
public func preprocess(_ data: Data) throws -> Data {
return (data.prefix(6) == Data(")]}',\n".utf8)) ? data.dropFirst(6) : data
}
}
extension ResponseSerializer {
/// Default `DataPreprocessor`. `PassthroughPreprocessor` by default.
public static var defaultDataPreprocessor: DataPreprocessor { return PassthroughPreprocessor() }
/// Default `HTTPMethod`s for which empty response bodies are considered appropriate. `[.head]` by default.
public static var defaultEmptyRequestMethods: Set<HTTPMethod> { return [.head] }
/// HTTP response codes for which empty response bodies are considered appropriate. `[204, 205]` by default.
public static var defaultEmptyResponseCodes: Set<Int> { return [204, 205] }
public var dataPreprocessor: DataPreprocessor { return Self.defaultDataPreprocessor }
public var emptyRequestMethods: Set<HTTPMethod> { return Self.defaultEmptyRequestMethods }
public var emptyResponseCodes: Set<Int> { return Self.defaultEmptyResponseCodes }
/// Determines whether the `request` allows empty response bodies, if `request` exists.
///
/// - Parameter request: `URLRequest` to evaluate.
///
/// - Returns: `Bool` representing the outcome of the evaluation, or `nil` if `request` was `nil`.
public func requestAllowsEmptyResponseData(_ request: URLRequest?) -> Bool? {
return request.flatMap { $0.httpMethod }
.flatMap(HTTPMethod.init)
.map { emptyRequestMethods.contains($0) }
}
/// Determines whether the `response` allows empty response bodies, if `response` exists`.
///
/// - Parameter response: `HTTPURLResponse` to evaluate.
///
/// - Returns: `Bool` representing the outcome of the evaluation, or `nil` if `response` was `nil`.
public func responseAllowsEmptyResponseData(_ response: HTTPURLResponse?) -> Bool? {
return response.flatMap { $0.statusCode }
.map { emptyResponseCodes.contains($0) }
}
/// Determines whether `request` and `response` allow empty response bodies.
///
/// - Parameters:
/// - request: `URLRequest` to evaluate.
/// - response: `HTTPURLResponse` to evaluate.
///
/// - Returns: `true` if `request` or `response` allow empty bodies, `false` otherwise.
public func emptyResponseAllowed(forRequest request: URLRequest?, response: HTTPURLResponse?) -> Bool {
return (requestAllowsEmptyResponseData(request) == true) || (responseAllowsEmptyResponseData(response) == true)
}
}
/// By default, any serializer declared to conform to both types will get file serialization for free, as it just feeds
/// the data read from disk into the data response serializer.
public extension DownloadResponseSerializerProtocol where Self: DataResponseSerializerProtocol {
func serializeDownload(request: URLRequest?, response: HTTPURLResponse?, fileURL: URL?, error: Error?) throws -> Self.SerializedObject {
guard error == nil else { throw error! }
guard let fileURL = fileURL else {
throw AFError.responseSerializationFailed(reason: .inputFileNil)
}
let data: Data
do {
data = try Data(contentsOf: fileURL)
} catch {
throw AFError.responseSerializationFailed(reason: .inputFileReadFailed(at: fileURL))
}
do {
return try serialize(request: request, response: response, data: data, error: error)
} catch {
throw error
}
}
}
// MARK: - Default
extension DataRequest {
/// Adds a handler to be called once the request has finished.
///
/// - Parameters:
/// - queue: The queue on which the completion handler is dispatched. `.main` by default.
/// - completionHandler: The code to be executed once the request has finished.
///
/// - Returns: The request.
@discardableResult
public func response(queue: DispatchQueue = .main, completionHandler: @escaping (AFDataResponse<Data?>) -> Void) -> Self {
appendResponseSerializer {
// Start work that should be on the serialization queue.
let result = AFResult<Data?>(value: self.data, error: self.error)
// End work that should be on the serialization queue.
self.underlyingQueue.async {
let response = DataResponse(request: self.request,
response: self.response,
data: self.data,
metrics: self.metrics,
serializationDuration: 0,
result: result)
self.eventMonitor?.request(self, didParseResponse: response)
self.responseSerializerDidComplete { queue.async { completionHandler(response) } }
}
}
return self
}
/// Adds a handler to be called once the request has finished.
///
/// - Parameters:
/// - queue: The queue on which the completion handler is dispatched. `.main` by default
/// - responseSerializer: The response serializer responsible for serializing the request, response, and data.
/// - completionHandler: The code to be executed once the request has finished.
///
/// - Returns: The request.
@discardableResult
public func response<Serializer: DataResponseSerializerProtocol>(queue: DispatchQueue = .main,
responseSerializer: Serializer,
completionHandler: @escaping (AFDataResponse<Serializer.SerializedObject>) -> Void)
-> Self {
appendResponseSerializer {
// Start work that should be on the serialization queue.
let start = CFAbsoluteTimeGetCurrent()
let result: AFResult<Serializer.SerializedObject> = Result {
try responseSerializer.serialize(request: self.request,
response: self.response,
data: self.data,
error: self.error)
}.mapError { error in
error.asAFError(or: .responseSerializationFailed(reason: .customSerializationFailed(error: error)))
}
let end = CFAbsoluteTimeGetCurrent()
// End work that should be on the serialization queue.
self.underlyingQueue.async {
let response = DataResponse(request: self.request,
response: self.response,
data: self.data,
metrics: self.metrics,
serializationDuration: end - start,
result: result)
self.eventMonitor?.request(self, didParseResponse: response)
guard let serializerError = result.failure, let delegate = self.delegate else {
self.responseSerializerDidComplete { queue.async { completionHandler(response) } }
return
}
delegate.retryResult(for: self, dueTo: serializerError) { retryResult in
var didComplete: (() -> Void)?
defer {
if let didComplete = didComplete {
self.responseSerializerDidComplete { queue.async { didComplete() } }
}
}
switch retryResult {
case .doNotRetry:
didComplete = { completionHandler(response) }
case let .doNotRetryWithError(retryError):
let result: AFResult<Serializer.SerializedObject> = .failure(retryError.asAFError(orFailWith: "Received retryError was not already AFError"))
let response = DataResponse(request: self.request,
response: self.response,
data: self.data,
metrics: self.metrics,
serializationDuration: end - start,
result: result)
didComplete = { completionHandler(response) }
case .retry, .retryWithDelay:
delegate.retryRequest(self, withDelay: retryResult.delay)
}
}
}
}
return self
}
}
extension DownloadRequest {
/// Adds a handler to be called once the request has finished.
///
/// - Parameters:
/// - queue: The queue on which the completion handler is dispatched. `.main` by default.
/// - completionHandler: The code to be executed once the request has finished.
///
/// - Returns: The request.
@discardableResult
public func response(queue: DispatchQueue = .main,
completionHandler: @escaping (AFDownloadResponse<URL?>) -> Void)
-> Self {
appendResponseSerializer {
// Start work that should be on the serialization queue.
let result = AFResult<URL?>(value: self.fileURL, error: self.error)
// End work that should be on the serialization queue.
self.underlyingQueue.async {
let response = DownloadResponse(request: self.request,
response: self.response,
fileURL: self.fileURL,
resumeData: self.resumeData,
metrics: self.metrics,
serializationDuration: 0,
result: result)
self.eventMonitor?.request(self, didParseResponse: response)
self.responseSerializerDidComplete { queue.async { completionHandler(response) } }
}
}
return self
}
/// Adds a handler to be called once the request has finished.
///
/// - Parameters:
/// - queue: The queue on which the completion handler is dispatched. `.main` by default.
/// - responseSerializer: The response serializer responsible for serializing the request, response, and data
/// contained in the destination `URL`.
/// - completionHandler: The code to be executed once the request has finished.
///
/// - Returns: The request.
@discardableResult
public func response<Serializer: DownloadResponseSerializerProtocol>(queue: DispatchQueue = .main,
responseSerializer: Serializer,
completionHandler: @escaping (AFDownloadResponse<Serializer.SerializedObject>) -> Void)
-> Self {
appendResponseSerializer {
// Start work that should be on the serialization queue.
let start = CFAbsoluteTimeGetCurrent()
let result: AFResult<Serializer.SerializedObject> = Result {
try responseSerializer.serializeDownload(request: self.request,
response: self.response,
fileURL: self.fileURL,
error: self.error)
}.mapError { error in
error.asAFError(or: .responseSerializationFailed(reason: .customSerializationFailed(error: error)))
}
let end = CFAbsoluteTimeGetCurrent()
// End work that should be on the serialization queue.
self.underlyingQueue.async {
let response = DownloadResponse(request: self.request,
response: self.response,
fileURL: self.fileURL,
resumeData: self.resumeData,
metrics: self.metrics,
serializationDuration: end - start,
result: result)
self.eventMonitor?.request(self, didParseResponse: response)
guard let serializerError = result.failure, let delegate = self.delegate else {
self.responseSerializerDidComplete { queue.async { completionHandler(response) } }
return
}
delegate.retryResult(for: self, dueTo: serializerError) { retryResult in
var didComplete: (() -> Void)?
defer {
if let didComplete = didComplete {
self.responseSerializerDidComplete { queue.async { didComplete() } }
}
}
switch retryResult {
case .doNotRetry:
didComplete = { completionHandler(response) }
case let .doNotRetryWithError(retryError):
let result: AFResult<Serializer.SerializedObject> = .failure(retryError.asAFError(orFailWith: "Received retryError was not already AFError"))
let response = DownloadResponse(request: self.request,
response: self.response,
fileURL: self.fileURL,
resumeData: self.resumeData,
metrics: self.metrics,
serializationDuration: end - start,
result: result)
didComplete = { completionHandler(response) }
case .retry, .retryWithDelay:
delegate.retryRequest(self, withDelay: retryResult.delay)
}
}
}
}
return self
}
}
// MARK: - Data
extension DataRequest {
/// Adds a handler to be called once the request has finished.
///
/// - Parameters:
/// - queue: The queue on which the completion handler is dispatched. `.main` by default.
/// - completionHandler: The code to be executed once the request has finished.
///
/// - Returns: The request.
@discardableResult
public func responseData(queue: DispatchQueue = .main,
completionHandler: @escaping (AFDataResponse<Data>) -> Void)
-> Self {
return response(queue: queue,
responseSerializer: DataResponseSerializer(),
completionHandler: completionHandler)
}
}
/// A `ResponseSerializer` that performs minimal response checking and returns any response data as-is. By default, a
/// request returning `nil` or no data is considered an error. However, if the response is has a status code valid for
/// empty responses (`204`, `205`), then an empty `Data` value is returned.
public final class DataResponseSerializer: ResponseSerializer {
public let dataPreprocessor: DataPreprocessor
public let emptyResponseCodes: Set<Int>
public let emptyRequestMethods: Set<HTTPMethod>
/// Creates an instance using the provided values.
///
/// - Parameters:
/// - dataPreprocessor: `DataPreprocessor` used to prepare the received `Data` for serialization.
/// - emptyResponseCodes: The HTTP response codes for which empty responses are allowed. `[204, 205]` by default.
/// - emptyRequestMethods: The HTTP request methods for which empty responses are allowed. `[.head]` by default.
public init(dataPreprocessor: DataPreprocessor = DataResponseSerializer.defaultDataPreprocessor,
emptyResponseCodes: Set<Int> = DataResponseSerializer.defaultEmptyResponseCodes,
emptyRequestMethods: Set<HTTPMethod> = DataResponseSerializer.defaultEmptyRequestMethods) {
self.dataPreprocessor = dataPreprocessor
self.emptyResponseCodes = emptyResponseCodes
self.emptyRequestMethods = emptyRequestMethods
}
public func serialize(request: URLRequest?, response: HTTPURLResponse?, data: Data?, error: Error?) throws -> Data {
guard error == nil else { throw error! }
guard var data = data, !data.isEmpty else {
guard emptyResponseAllowed(forRequest: request, response: response) else {
throw AFError.responseSerializationFailed(reason: .inputDataNilOrZeroLength)
}
return Data()
}
data = try dataPreprocessor.preprocess(data)
return data
}
}
extension DownloadRequest {
/// Adds a handler to be called once the request has finished.
///
/// - Parameters:
/// - queue: The queue on which the completion handler is dispatched. `.main` by default.
/// - completionHandler: The code to be executed once the request has finished.
///
/// - Returns: The request.
@discardableResult
public func responseData(queue: DispatchQueue = .main,
completionHandler: @escaping (AFDownloadResponse<Data>) -> Void)
-> Self {
return response(queue: queue,
responseSerializer: DataResponseSerializer(),
completionHandler: completionHandler)
}
}
// MARK: - String
/// A `ResponseSerializer` that decodes the response data as a `String`. By default, a request returning `nil` or no
/// data is considered an error. However, if the response is has a status code valid for empty responses (`204`, `205`),
/// then an empty `String` is returned.
public final class StringResponseSerializer: ResponseSerializer {
public let dataPreprocessor: DataPreprocessor
/// Optional string encoding used to validate the response.
public let encoding: String.Encoding?
public let emptyResponseCodes: Set<Int>
public let emptyRequestMethods: Set<HTTPMethod>
/// Creates an instance with the provided values.
///
/// - Parameters:
/// - dataPreprocessor: `DataPreprocessor` used to prepare the received `Data` for serialization.
/// - encoding: A string encoding. Defaults to `nil`, in which case the encoding will be determined
/// from the server response, falling back to the default HTTP character set, `ISO-8859-1`.
/// - emptyResponseCodes: The HTTP response codes for which empty responses are allowed. `[204, 205]` by default.
/// - emptyRequestMethods: The HTTP request methods for which empty responses are allowed. `[.head]` by default.
public init(dataPreprocessor: DataPreprocessor = StringResponseSerializer.defaultDataPreprocessor,
encoding: String.Encoding? = nil,
emptyResponseCodes: Set<Int> = StringResponseSerializer.defaultEmptyResponseCodes,
emptyRequestMethods: Set<HTTPMethod> = StringResponseSerializer.defaultEmptyRequestMethods) {
self.dataPreprocessor = dataPreprocessor
self.encoding = encoding
self.emptyResponseCodes = emptyResponseCodes
self.emptyRequestMethods = emptyRequestMethods
}
public func serialize(request: URLRequest?, response: HTTPURLResponse?, data: Data?, error: Error?) throws -> String {
guard error == nil else { throw error! }
guard var data = data, !data.isEmpty else {
guard emptyResponseAllowed(forRequest: request, response: response) else {
throw AFError.responseSerializationFailed(reason: .inputDataNilOrZeroLength)
}
return ""
}
data = try dataPreprocessor.preprocess(data)
var convertedEncoding = encoding
if let encodingName = response?.textEncodingName as CFString?, convertedEncoding == nil {
let ianaCharSet = CFStringConvertIANACharSetNameToEncoding(encodingName)
let nsStringEncoding = CFStringConvertEncodingToNSStringEncoding(ianaCharSet)
convertedEncoding = String.Encoding(rawValue: nsStringEncoding)
}
let actualEncoding = convertedEncoding ?? .isoLatin1
guard let string = String(data: data, encoding: actualEncoding) else {
throw AFError.responseSerializationFailed(reason: .stringSerializationFailed(encoding: actualEncoding))
}
return string
}
}
extension DataRequest {
/// Adds a handler to be called once the request has finished.
///
/// - Parameters:
/// - queue: The queue on which the completion handler is dispatched. `.main` by default.
/// - encoding: The string encoding. Defaults to `nil`, in which case the encoding will be determined from
/// the server response, falling back to the default HTTP character set, `ISO-8859-1`.
/// - completionHandler: A closure to be executed once the request has finished.
///
/// - Returns: The request.
@discardableResult
public func responseString(queue: DispatchQueue = .main,
encoding: String.Encoding? = nil,
completionHandler: @escaping (AFDataResponse<String>) -> Void) -> Self {
return response(queue: queue,
responseSerializer: StringResponseSerializer(encoding: encoding),
completionHandler: completionHandler)
}
}
extension DownloadRequest {
/// Adds a handler to be called once the request has finished.
///
/// - Parameters:
/// - queue: The queue on which the completion handler is dispatched. `.main` by default.
/// - encoding: The string encoding. Defaults to `nil`, in which case the encoding will be determined from
/// the server response, falling back to the default HTTP character set, `ISO-8859-1`.
/// - completionHandler: A closure to be executed once the request has finished.
///
/// - Returns: The request.
@discardableResult
public func responseString(queue: DispatchQueue = .main,
encoding: String.Encoding? = nil,
completionHandler: @escaping (AFDownloadResponse<String>) -> Void)
-> Self {
return response(queue: queue,
responseSerializer: StringResponseSerializer(encoding: encoding),
completionHandler: completionHandler)
}
}
// MARK: - JSON
/// A `ResponseSerializer` that decodes the response data using `JSONSerialization`. By default, a request returning
/// `nil` or no data is considered an error. However, if the response is has a status code valid for empty responses
/// (`204`, `205`), then an `NSNull` value is returned.
public final class JSONResponseSerializer: ResponseSerializer {
public let dataPreprocessor: DataPreprocessor
public let emptyResponseCodes: Set<Int>
public let emptyRequestMethods: Set<HTTPMethod>
/// `JSONSerialization.ReadingOptions` used when serializing a response.
public let options: JSONSerialization.ReadingOptions
/// Creates an instance with the provided values.
///
/// - Parameters:
/// - dataPreprocessor: `DataPreprocessor` used to prepare the received `Data` for serialization.
/// - emptyResponseCodes: The HTTP response codes for which empty responses are allowed. `[204, 205]` by default.
/// - emptyRequestMethods: The HTTP request methods for which empty responses are allowed. `[.head]` by default.
/// - options: The options to use. `.allowFragments` by default.
public init(dataPreprocessor: DataPreprocessor = JSONResponseSerializer.defaultDataPreprocessor,
emptyResponseCodes: Set<Int> = JSONResponseSerializer.defaultEmptyResponseCodes,
emptyRequestMethods: Set<HTTPMethod> = JSONResponseSerializer.defaultEmptyRequestMethods,
options: JSONSerialization.ReadingOptions = .allowFragments) {
self.dataPreprocessor = dataPreprocessor
self.emptyResponseCodes = emptyResponseCodes
self.emptyRequestMethods = emptyRequestMethods
self.options = options
}
public func serialize(request: URLRequest?, response: HTTPURLResponse?, data: Data?, error: Error?) throws -> Any {
guard error == nil else { throw error! }
guard var data = data, !data.isEmpty else {
guard emptyResponseAllowed(forRequest: request, response: response) else {
throw AFError.responseSerializationFailed(reason: .inputDataNilOrZeroLength)
}
return NSNull()
}
data = try dataPreprocessor.preprocess(data)
do {
return try JSONSerialization.jsonObject(with: data, options: options)
} catch {
throw AFError.responseSerializationFailed(reason: .jsonSerializationFailed(error: error))
}
}
}
extension DataRequest {
/// Adds a handler to be called once the request has finished.
///
/// - Parameters:
/// - queue: The queue on which the completion handler is dispatched. `.main` by default.
/// - options: The JSON serialization reading options. `.allowFragments` by default.
/// - completionHandler: A closure to be executed once the request has finished.
///
/// - Returns: The request.
@discardableResult
public func responseJSON(queue: DispatchQueue = .main,
options: JSONSerialization.ReadingOptions = .allowFragments,
completionHandler: @escaping (AFDataResponse<Any>) -> Void) -> Self {
return response(queue: queue,
responseSerializer: JSONResponseSerializer(options: options),
completionHandler: completionHandler)
}
}
extension DownloadRequest {
/// Adds a handler to be called once the request has finished.
///
/// - Parameters:
/// - queue: The queue on which the completion handler is dispatched. `.main` by default.
/// - options: The JSON serialization reading options. `.allowFragments` by default.
/// - completionHandler: A closure to be executed once the request has finished.
///
/// - Returns: The request.
@discardableResult
public func responseJSON(queue: DispatchQueue = .main,
options: JSONSerialization.ReadingOptions = .allowFragments,
completionHandler: @escaping (AFDownloadResponse<Any>) -> Void)
-> Self {
return response(queue: queue,
responseSerializer: JSONResponseSerializer(options: options),
completionHandler: completionHandler)
}
}
// MARK: - Empty
/// Protocol representing an empty response. Use `T.emptyValue()` to get an instance.
public protocol EmptyResponse {
/// Empty value for the conforming type.
///
/// - Returns: Value of `Self` to use for empty values.
static func emptyValue() -> Self
}
/// Type representing an empty response. Use `Empty.value` to get the static instance.
public struct Empty: Decodable {
/// Static `Empty` instance used for all `Empty` responses.
public static let value = Empty()
}
extension Empty: EmptyResponse {
public static func emptyValue() -> Empty {
return value
}
}
// MARK: - DataDecoder Protocol
/// Any type which can decode `Data` into a `Decodable` type.
public protocol DataDecoder {
/// Decode `Data` into the provided type.
///
/// - Parameters:
/// - type: The `Type` to be decoded.
/// - data: The `Data` to be decoded.
///
/// - Returns: The decoded value of type `D`.
/// - Throws: Any error that occurs during decode.
func decode<D: Decodable>(_ type: D.Type, from data: Data) throws -> D
}
/// `JSONDecoder` automatically conforms to `DataDecoder`.
extension JSONDecoder: DataDecoder {}
// MARK: - Decodable
/// A `ResponseSerializer` that decodes the response data as a generic value using any type that conforms to
/// `DataDecoder`. By default, this is an instance of `JSONDecoder`. Additionally, a request returning `nil` or no data
/// is considered an error. However, if the response is has a status code valid for empty responses (`204`, `205`), then
/// the `Empty.value` value is returned.
public final class DecodableResponseSerializer<T: Decodable>: ResponseSerializer {
public let dataPreprocessor: DataPreprocessor
/// The `DataDecoder` instance used to decode responses.
public let decoder: DataDecoder
public let emptyResponseCodes: Set<Int>
public let emptyRequestMethods: Set<HTTPMethod>
/// Creates an instance using the values provided.
///
/// - Parameters:
/// - dataPreprocessor: `DataPreprocessor` used to prepare the received `Data` for serialization.
/// - decoder: The `DataDecoder`. `JSONDecoder()` by default.
/// - emptyResponseCodes: The HTTP response codes for which empty responses are allowed. `[204, 205]` by default.
/// - emptyRequestMethods: The HTTP request methods for which empty responses are allowed. `[.head]` by default.
public init(dataPreprocessor: DataPreprocessor = DecodableResponseSerializer.defaultDataPreprocessor,
decoder: DataDecoder = JSONDecoder(),
emptyResponseCodes: Set<Int> = DecodableResponseSerializer.defaultEmptyResponseCodes,
emptyRequestMethods: Set<HTTPMethod> = DecodableResponseSerializer.defaultEmptyRequestMethods) {
self.dataPreprocessor = dataPreprocessor
self.decoder = decoder
self.emptyResponseCodes = emptyResponseCodes
self.emptyRequestMethods = emptyRequestMethods
}
public func serialize(request: URLRequest?, response: HTTPURLResponse?, data: Data?, error: Error?) throws -> T {
guard error == nil else { throw error! }
guard var data = data, !data.isEmpty else {
guard emptyResponseAllowed(forRequest: request, response: response) else {
throw AFError.responseSerializationFailed(reason: .inputDataNilOrZeroLength)
}
guard let emptyResponseType = T.self as? EmptyResponse.Type, let emptyValue = emptyResponseType.emptyValue() as? T else {
throw AFError.responseSerializationFailed(reason: .invalidEmptyResponse(type: "\(T.self)"))
}
return emptyValue
}
data = try dataPreprocessor.preprocess(data)
do {
return try decoder.decode(T.self, from: data)
} catch {
throw AFError.responseSerializationFailed(reason: .decodingFailed(error: error))
}
}
}
extension DataRequest {
/// Adds a handler to be called once the request has finished.
///
/// - Parameters:
/// - type: `Decodable` type to decode from response data.
/// - queue: The queue on which the completion handler is dispatched. `.main` by default.
/// - decoder: `DataDecoder` to use to decode the response. `JSONDecoder()` by default.
/// - completionHandler: A closure to be executed once the request has finished.
///
/// - Returns: The request.
@discardableResult
public func responseDecodable<T: Decodable>(of type: T.Type = T.self,
queue: DispatchQueue = .main,
decoder: DataDecoder = JSONDecoder(),
completionHandler: @escaping (AFDataResponse<T>) -> Void) -> Self {
return response(queue: queue,
responseSerializer: DecodableResponseSerializer(decoder: decoder),
completionHandler: completionHandler)
}
}
extension DownloadRequest {
/// Adds a handler to be called once the request has finished.
///
/// - Parameters:
/// - type: `Decodable` type to decode from response data.
/// - queue: The queue on which the completion handler is dispatched. `.main` by default.
/// - decoder: `DataDecoder` to use to decode the response. `JSONDecoder()` by default.
/// - completionHandler: A closure to be executed once the request has finished.
///
/// - Returns: The request.
@discardableResult
public func responseDecodable<T: Decodable>(of type: T.Type = T.self,
queue: DispatchQueue = .main,
decoder: DataDecoder = JSONDecoder(),
completionHandler: @escaping (AFDownloadResponse<T>) -> Void) -> Self {
return response(queue: queue,
responseSerializer: DecodableResponseSerializer(decoder: decoder),
completionHandler: completionHandler)
}
}
| mit | 52ee79f7b95dc15c53651216ae050c0e | 46.96875 | 165 | 0.609329 | 5.489986 | false | false | false | false |
turbolent/SwiftParserCombinators | Tests/ParserCombinatorsTests/PatternsTests.swift | 1 | 1615 |
import XCTest
import ParserCombinators
import ParserDescription
import ParserDescriptionOperators
extension String: Token {
public func isTokenLabel(_ label: String, equalTo conditionInput: String) -> Bool {
return label == "text"
&& self == conditionInput
}
public func doesTokenLabel(_ label: String, havePrefix prefix: String) -> Bool {
return label == "text"
&& self.starts(with: prefix)
}
public func isTokenLabel(
_ label: String,
matchingRegularExpression: NSRegularExpression
) -> Bool {
return false
}
}
final class PatternsTests: XCTestCase {
func testCompilation() throws {
let tokenPattern = TokenPattern(condition:
LabelCondition(label: "text", op: .isEqualTo, input: "foo")
|| LabelCondition(label: "text", op: .isEqualTo, input: "bar")
)
let pattern = tokenPattern.capture("token").rep(min: 1)
let parser: Parser<Captures, String> = try pattern.compile()
let reader = CollectionReader(collection: ["foo", "foo", "bar", "baz"])
guard case .success(let captures, _) = parser.parse(reader) else {
XCTFail("parsing should succeed")
return
}
XCTAssertEqual(
String(describing: captures.values),
String(describing: ["foo", "foo", "bar"])
)
XCTAssertEqual(
String(describing: captures.entries.sorted { $0.key < $1.key }),
String(describing: [(key: "token", value: [["foo"], ["foo"], ["bar"]])])
)
}
}
| mit | ea37c63494150f09887b57c3e3494545 | 27.333333 | 87 | 0.590712 | 4.461326 | false | true | false | false |
dvxiaofan/Pro-Swift-Learning | Part-02/07-ArraySorting.playground/Contents.swift | 1 | 453 | //: Playground - noun: a place where people can play
import UIKit
var names = ["xiaofan", "xuming", "xaoling", "xelo", "xk", "xlouou"]
let nums = [1, 3, 5, 6, 12, 4, 9, 7]
let sorted = names.sorted()
names.sort {
print("Comparing \($0) and \($1)")
if ($0 == "xiaofan") {
return true
} else if $1 == "xiaofan" {
return false
} else {
return $0 < $1
}
}
let minNum = nums.min()
let maxNum = nums.max() | mit | f5b76ab87d5ddde1cb76dab07accff6c | 18.73913 | 68 | 0.534216 | 2.903846 | false | false | false | false |
badoo/Chatto | ChattoAdditions/Tests/Chat Items/BaseMessage/FakeMessageInteractionHandler.swift | 1 | 9616 | //
// 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 ChattoAdditions
import UIKit
// swiftlint:disable all
public final class FakeMessageInteractionHandler: BaseMessageInteractionHandlerProtocol {
public typealias MessageType = MessageModel
public typealias ViewModelType = MessageViewModel
private var isNiceMock: Bool
convenience init() {
self.init(isNiceMock: false)
}
static func niceMock() -> FakeMessageInteractionHandler {
return FakeMessageInteractionHandler(isNiceMock: true)
}
private init(isNiceMock: Bool) {
self.isNiceMock = isNiceMock
}
var _userDidTapOnFailIcon = _UserDidTapOnFailIcon()
var _userDidTapOnAvatar = _UserDidTapOnAvatar()
var _userDidTapOnBubble = _UserDidTapOnBubble()
var _userDidDoubleTapOnBubble = _UserDidDoubleTapOnBubble()
var _userDidBeginLongPressOnBubble = _UserDidBeginLongPressOnBubble()
var _userDidEndLongPressOnBubble = _UserDidEndLongPressOnBubble()
var _userDidSelectMessage = _UserDidSelectMessage()
var _userDidDeselectMessage = _UserDidDeselectMessage()
var onUserDidTapOnFailIcon: ((MessageType, ViewModelType, UIView) -> Void)? = nil
public func userDidTapOnFailIcon(message: MessageType, viewModel: ViewModelType, failIconView: UIView) -> Void {
if let fakeImplementation = self.onUserDidTapOnFailIcon {
fakeImplementation(message, viewModel, failIconView)
} else {
if !self.isNiceMock { fatalError("\(String(describing: self)) \(#function) is not implemented. Add your implementation or use .niceMock()") }
self._userDidTapOnFailIcon.history.append((message, viewModel, failIconView))
}
}
var onUserDidTapOnAvatar: ((MessageType, ViewModelType) -> Void)? = nil
public func userDidTapOnAvatar(message: MessageType, viewModel: ViewModelType) -> Void {
if let fakeImplementation = self.onUserDidTapOnAvatar {
fakeImplementation(message, viewModel)
} else {
if !self.isNiceMock { fatalError("\(String(describing: self)) \(#function) is not implemented. Add your implementation or use .niceMock()") }
self._userDidTapOnAvatar.history.append((message, viewModel))
}
}
var onUserDidTapOnBubble: ((MessageType, ViewModelType) -> Void)? = nil
public func userDidTapOnBubble(message: MessageType, viewModel: ViewModelType) -> Void {
if let fakeImplementation = self.onUserDidTapOnBubble {
fakeImplementation(message, viewModel)
} else {
if !self.isNiceMock { fatalError("\(String(describing: self)) \(#function) is not implemented. Add your implementation or use .niceMock()") }
self._userDidTapOnBubble.history.append((message, viewModel))
}
}
var onUserDidDoubleTapOnBubble: ((MessageType, ViewModelType) -> Void)? = nil
public func userDidDoubleTapOnBubble(message: MessageType, viewModel: ViewModelType) -> Void {
if let fakeImplementation = self.onUserDidDoubleTapOnBubble {
fakeImplementation(message, viewModel)
} else {
if !self.isNiceMock { fatalError("\(String(describing: self)) \(#function) is not implemented. Add your implementation or use .niceMock()") }
self._userDidDoubleTapOnBubble.history.append((message, viewModel))
}
}
var onUserDidBeginLongPressOnBubble: ((MessageType, ViewModelType) -> Void)? = nil
public func userDidBeginLongPressOnBubble(message: MessageType, viewModel: ViewModelType) -> Void {
if let fakeImplementation = self.onUserDidBeginLongPressOnBubble {
fakeImplementation(message, viewModel)
} else {
if !self.isNiceMock { fatalError("\(String(describing: self)) \(#function) is not implemented. Add your implementation or use .niceMock()") }
self._userDidBeginLongPressOnBubble.history.append((message, viewModel))
}
}
var onUserDidEndLongPressOnBubble: ((MessageType, ViewModelType) -> Void)? = nil
public func userDidEndLongPressOnBubble(message: MessageType, viewModel: ViewModelType) -> Void {
if let fakeImplementation = self.onUserDidEndLongPressOnBubble {
fakeImplementation(message, viewModel)
} else {
if !self.isNiceMock { fatalError("\(String(describing: self)) \(#function) is not implemented. Add your implementation or use .niceMock()") }
self._userDidEndLongPressOnBubble.history.append((message, viewModel))
}
}
var onUserDidSelectMessage: ((MessageType, ViewModelType) -> Void)? = nil
public func userDidSelectMessage(message: MessageType, viewModel: ViewModelType) -> Void {
if let fakeImplementation = self.onUserDidSelectMessage {
fakeImplementation(message, viewModel)
} else {
if !self.isNiceMock { fatalError("\(String(describing: self)) \(#function) is not implemented. Add your implementation or use .niceMock()") }
self._userDidSelectMessage.history.append((message, viewModel))
}
}
var onUserDidDeselectMessage: ((MessageType, ViewModelType) -> Void)? = nil
public func userDidDeselectMessage(message: MessageType, viewModel: ViewModelType) -> Void {
if let fakeImplementation = self.onUserDidDeselectMessage {
fakeImplementation(message, viewModel)
} else {
if !self.isNiceMock { fatalError("\(String(describing: self)) \(#function) is not implemented. Add your implementation or use .niceMock()") }
self._userDidDeselectMessage.history.append((message, viewModel))
}
}
}
public extension FakeMessageInteractionHandler {
struct _UserDidTapOnFailIcon {
var history: [(message: MessageType, viewModel: ViewModelType, failIconView: UIView)] = []
var lastArgs: (message: MessageType, viewModel: ViewModelType, failIconView: UIView)! { return self.history.last }
var callsCount: Int { return self.history.count }
var wasCalled: Bool { return self.callsCount > 0 }
}
struct _UserDidTapOnAvatar {
var history: [(message: MessageType, viewModel: ViewModelType)] = []
var lastArgs: (message: MessageType, viewModel: ViewModelType)! { return self.history.last }
var callsCount: Int { return self.history.count }
var wasCalled: Bool { return self.callsCount > 0 }
}
struct _UserDidTapOnBubble {
var history: [(message: MessageType, viewModel: ViewModelType)] = []
var lastArgs: (message: MessageType, viewModel: ViewModelType)! { return self.history.last }
var callsCount: Int { return self.history.count }
var wasCalled: Bool { return self.callsCount > 0 }
}
struct _UserDidDoubleTapOnBubble {
var history: [(message: MessageType, viewModel: ViewModelType)] = []
var lastArgs: (message: MessageType, viewModel: ViewModelType)! { return self.history.last }
var callsCount: Int { return self.history.count }
var wasCalled: Bool { return self.callsCount > 0 }
}
struct _UserDidBeginLongPressOnBubble {
var history: [(message: MessageType, viewModel: ViewModelType)] = []
var lastArgs: (message: MessageType, viewModel: ViewModelType)! { return self.history.last }
var callsCount: Int { return self.history.count }
var wasCalled: Bool { return self.callsCount > 0 }
}
struct _UserDidEndLongPressOnBubble {
var history: [(message: MessageType, viewModel: ViewModelType)] = []
var lastArgs: (message: MessageType, viewModel: ViewModelType)! { return self.history.last }
var callsCount: Int { return self.history.count }
var wasCalled: Bool { return self.callsCount > 0 }
}
struct _UserDidSelectMessage {
var history: [(message: MessageType, viewModel: ViewModelType)] = []
var lastArgs: (message: MessageType, viewModel: ViewModelType)! { return self.history.last }
var callsCount: Int { return self.history.count }
var wasCalled: Bool { return self.callsCount > 0 }
}
struct _UserDidDeselectMessage {
var history: [(message: MessageType, viewModel: ViewModelType)] = []
var lastArgs: (message: MessageType, viewModel: ViewModelType)! { return self.history.last }
var callsCount: Int { return self.history.count }
var wasCalled: Bool { return self.callsCount > 0 }
}
}
// swiftlint:enable all
| mit | 760018262ba605931d4578390094cd43 | 47.812183 | 153 | 0.696339 | 4.758041 | false | false | false | false |
javibm/fastlane | snapshot/lib/assets/SnapshotHelperXcode8.swift | 11 | 6225 | //
// SnapshotHelperXcode8.swift
// Example
//
// Created by Felix Krause on 10/8/15.
// Copyright © 2015 Felix Krause. All rights reserved.
//
// -----------------------------------------------------
// IMPORTANT: When modifying this file, make sure to
// increment the version number at the very
// bottom of the file to notify users about
// the new SnapshotHelperXcode8.swift
// -----------------------------------------------------
import Foundation
import XCTest
var deviceLanguage = ""
var locale = ""
@available(*, deprecated, message: "use setupSnapshot: instead")
func setLanguage(_ app: XCUIApplication) {
setupSnapshot(app)
}
func setupSnapshot(_ app: XCUIApplication) {
Snapshot.setupSnapshot(app)
}
func snapshot(_ name: String, waitForLoadingIndicator: Bool = true) {
Snapshot.snapshot(name, waitForLoadingIndicator: waitForLoadingIndicator)
}
open class Snapshot: NSObject {
open class func setupSnapshot(_ app: XCUIApplication) {
setLanguage(app)
setLocale(app)
setLaunchArguments(app)
}
class func setLanguage(_ app: XCUIApplication) {
guard let prefix = pathPrefix() else {
return
}
let path = prefix.appendingPathComponent("language.txt")
do {
let trimCharacterSet = CharacterSet.whitespacesAndNewlines
deviceLanguage = try String(contentsOf: path, encoding: .utf8).trimmingCharacters(in: trimCharacterSet)
app.launchArguments += ["-AppleLanguages", "(\(deviceLanguage))"]
} catch {
print("Couldn't detect/set language...")
}
}
class func setLocale(_ app: XCUIApplication) {
guard let prefix = pathPrefix() else {
return
}
let path = prefix.appendingPathComponent("locale.txt")
do {
let trimCharacterSet = CharacterSet.whitespacesAndNewlines
locale = try String(contentsOf: path, encoding: .utf8).trimmingCharacters(in: trimCharacterSet)
} catch {
print("Couldn't detect/set locale...")
}
if locale.isEmpty {
locale = Locale(identifier: deviceLanguage).identifier
}
app.launchArguments += ["-AppleLocale", "\"\(locale)\""]
}
class func setLaunchArguments(_ app: XCUIApplication) {
guard let prefix = pathPrefix() else {
return
}
let path = prefix.appendingPathComponent("snapshot-launch_arguments.txt")
app.launchArguments += ["-FASTLANE_SNAPSHOT", "YES", "-ui_testing"]
do {
let launchArguments = try String(contentsOf: path, encoding: String.Encoding.utf8)
let regex = try NSRegularExpression(pattern: "(\\\".+?\\\"|\\S+)", options: [])
let matches = regex.matches(in: launchArguments, options: [], range: NSRange(location:0, length:launchArguments.characters.count))
let results = matches.map { result -> String in
(launchArguments as NSString).substring(with: result.range)
}
app.launchArguments += results
} catch {
print("Couldn't detect/set launch_arguments...")
}
}
open class func snapshot(_ name: String, waitForLoadingIndicator: Bool = true) {
if waitForLoadingIndicator {
waitForLoadingIndicatorToDisappear()
}
print("snapshot: \(name)") // more information about this, check out https://github.com/fastlane/fastlane/tree/master/snapshot#how-does-it-work
sleep(1) // Waiting for the animation to be finished (kind of)
#if os(tvOS)
XCUIApplication().childrenMatchingType(.Browser).count
#elseif os(OSX)
XCUIApplication().typeKey(XCUIKeyboardKeySecondaryFn, modifierFlags: [])
#else
XCUIDevice.shared().orientation = .unknown
#endif
}
class func waitForLoadingIndicatorToDisappear() {
#if os(tvOS)
return
#endif
let query = XCUIApplication().statusBars.children(matching: .other).element(boundBy: 1).children(matching: .other)
while (0..<query.count).map({ query.element(boundBy: $0) }).contains(where: { $0.isLoadingIndicator }) {
sleep(1)
print("Waiting for loading indicator to disappear...")
}
}
class func pathPrefix() -> URL? {
let homeDir: URL
// on OSX config is stored in /Users/<username>/Library
// and on iOS/tvOS/WatchOS it's in simulator's home dir
#if os(OSX)
guard let user = ProcessInfo().environment["USER"] else {
print("Couldn't find Snapshot configuration files - can't detect current user ")
return nil
}
guard let usersDir = FileManager.default.urls(for: .userDirectory, in: .localDomainMask).first else {
print("Couldn't find Snapshot configuration files - can't detect `Users` dir")
return nil
}
homeDir = usersDir.appendingPathComponent(user)
#else
guard let simulatorHostHome = ProcessInfo().environment["SIMULATOR_HOST_HOME"] else {
print("Couldn't find simulator home location. Please, check SIMULATOR_HOST_HOME env variable.")
return nil
}
guard let homeDirUrl = URL(string: simulatorHostHome) else {
print("Can't prepare environment. Simulator home location is inaccessible. Does \(simulatorHostHome) exist?")
return nil
}
homeDir = URL(fileURLWithPath: homeDirUrl.path)
#endif
return homeDir.appendingPathComponent("Library/Caches/tools.fastlane")
}
}
extension XCUIElement {
var isLoadingIndicator: Bool {
let whiteListedLoaders = ["GeofenceLocationTrackingOn", "StandardLocationTrackingOn"]
if whiteListedLoaders.contains(self.identifier) {
return false
}
return self.frame.size == CGSize(width: 10, height: 20)
}
}
// Please don't remove the lines below
// They are used to detect outdated configuration files
// SnapshotHelperXcode8Version [1.4]
| mit | bb27c14d2731df41795667937cb7ece9 | 34.976879 | 151 | 0.61295 | 5.072535 | false | false | false | false |
xedin/swift | test/SILGen/witness_tables.swift | 12 | 42441 |
// RUN: %target-swift-emit-silgen -module-name witness_tables -I %S/Inputs -enable-source-import %s -disable-objc-attr-requires-foundation-module -enable-objc-interop > %t.sil
// RUN: %FileCheck -check-prefix=TABLE -check-prefix=TABLE-ALL %s < %t.sil
// RUN: %FileCheck -check-prefix=SYMBOL %s < %t.sil
// RUN: %target-swift-emit-silgen -module-name witness_tables -I %S/Inputs -enable-source-import %s -disable-objc-attr-requires-foundation-module -enable-objc-interop -enable-testing > %t.testable.sil
// RUN: %FileCheck -check-prefix=TABLE-TESTABLE -check-prefix=TABLE-ALL %s < %t.testable.sil
// RUN: %FileCheck -check-prefix=SYMBOL-TESTABLE %s < %t.testable.sil
import witness_tables_b
struct Arg {}
@objc class ObjCClass {}
infix operator <~>
protocol AssocReqt {
func requiredMethod()
}
protocol ArchetypeReqt {
func requiredMethod()
}
protocol AnyProtocol {
associatedtype AssocType
associatedtype AssocWithReqt: AssocReqt
func method(x: Arg, y: Self)
func generic<A: ArchetypeReqt>(x: A, y: Self)
func assocTypesMethod(x: AssocType, y: AssocWithReqt)
static func staticMethod(x: Self)
static func <~>(x: Self, y: Self)
}
protocol ClassProtocol : class {
associatedtype AssocType
associatedtype AssocWithReqt: AssocReqt
func method(x: Arg, y: Self)
func generic<B: ArchetypeReqt>(x: B, y: Self)
func assocTypesMethod(x: AssocType, y: AssocWithReqt)
static func staticMethod(x: Self)
static func <~>(x: Self, y: Self)
}
@objc protocol ObjCProtocol {
func method(x: ObjCClass)
static func staticMethod(y: ObjCClass)
}
class SomeAssoc {}
struct ConformingAssoc : AssocReqt {
func requiredMethod() {}
}
// TABLE-LABEL: sil_witness_table hidden ConformingAssoc: AssocReqt module witness_tables {
// TABLE-TESTABLE-LABEL: sil_witness_table [serialized] ConformingAssoc: AssocReqt module witness_tables {
// TABLE-ALL-NEXT: method #AssocReqt.requiredMethod!1: {{.*}} : @$s14witness_tables15ConformingAssocVAA0D4ReqtA2aDP14requiredMethod{{[_0-9a-zA-Z]*}}FTW
// TABLE-ALL-NEXT: }
// SYMBOL: sil private [transparent] [thunk] [ossa] @$s14witness_tables15ConformingAssocVAA0D4ReqtA2aDP14requiredMethod{{[_0-9a-zA-Z]*}}FTW : $@convention(witness_method: AssocReqt) (@in_guaranteed ConformingAssoc) -> ()
// SYMBOL-TESTABLE: sil shared [transparent] [serialized] [thunk] [ossa] @$s14witness_tables15ConformingAssocVAA0D4ReqtA2aDP14requiredMethod{{[_0-9a-zA-Z]*}}FTW : $@convention(witness_method: AssocReqt) (@in_guaranteed ConformingAssoc) -> ()
struct ConformingStruct : AnyProtocol {
typealias AssocType = SomeAssoc
typealias AssocWithReqt = ConformingAssoc
func method(x: Arg, y: ConformingStruct) {}
func generic<D: ArchetypeReqt>(x: D, y: ConformingStruct) {}
func assocTypesMethod(x: SomeAssoc, y: ConformingAssoc) {}
static func staticMethod(x: ConformingStruct) {}
}
func <~>(x: ConformingStruct, y: ConformingStruct) {}
// TABLE-LABEL: sil_witness_table hidden ConformingStruct: AnyProtocol module witness_tables {
// TABLE-NEXT: associated_type_protocol (AssocWithReqt: AssocReqt): ConformingAssoc: AssocReqt module witness_tables
// TABLE-NEXT: associated_type AssocType: SomeAssoc
// TABLE-NEXT: associated_type AssocWithReqt: ConformingAssoc
// TABLE-NEXT: method #AnyProtocol.method!1: {{.*}} : @$s14witness_tables16ConformingStructVAA11AnyProtocolA2aDP6method{{[_0-9a-zA-Z]*}}FTW
// TABLE-NEXT: method #AnyProtocol.generic!1: {{.*}} : @$s14witness_tables16ConformingStructVAA11AnyProtocolA2aDP7generic{{[_0-9a-zA-Z]*}}FTW
// TABLE-NEXT: method #AnyProtocol.assocTypesMethod!1: {{.*}} : @$s14witness_tables16ConformingStructVAA11AnyProtocolA2aDP16assocTypesMethod{{[_0-9a-zA-Z]*}}FTW
// TABLE-NEXT: method #AnyProtocol.staticMethod!1: {{.*}} : @$s14witness_tables16ConformingStructVAA11AnyProtocolA2aDP12staticMethod{{[_0-9a-zA-Z]*}}FZTW
// TABLE-NEXT: method #AnyProtocol."<~>"!1: {{.*}} : @$s14witness_tables16ConformingStructVAA11AnyProtocolA2aDP3ltgoi{{[_0-9a-zA-Z]*}}FZTW
// TABLE-NEXT: }
// SYMBOL: sil private [transparent] [thunk] [ossa] @$s14witness_tables16ConformingStructVAA11AnyProtocolA2aDP6method{{[_0-9a-zA-Z]*}}FTW : $@convention(witness_method: AnyProtocol) (Arg, @in_guaranteed ConformingStruct, @in_guaranteed ConformingStruct) -> ()
// SYMBOL: sil private [transparent] [thunk] [ossa] @$s14witness_tables16ConformingStructVAA11AnyProtocolA2aDP7generic{{[_0-9a-zA-Z]*}}FTW {{.*}}: ArchetypeReqt> (@in_guaranteed τ_0_0, @in_guaranteed ConformingStruct, @in_guaranteed ConformingStruct) -> ()
// SYMBOL: sil private [transparent] [thunk] [ossa] @$s14witness_tables16ConformingStructVAA11AnyProtocolA2aDP16assocTypesMethod{{[_0-9a-zA-Z]*}}FTW : $@convention(witness_method: AnyProtocol) (@in_guaranteed SomeAssoc, @in_guaranteed ConformingAssoc, @in_guaranteed ConformingStruct) -> ()
// SYMBOL: sil private [transparent] [thunk] [ossa] @$s14witness_tables16ConformingStructVAA11AnyProtocolA2aDP12staticMethod{{[_0-9a-zA-Z]*}}FZTW : $@convention(witness_method: AnyProtocol) (@in_guaranteed ConformingStruct, @thick ConformingStruct.Type) -> ()
// SYMBOL: sil private [transparent] [thunk] [ossa] @$s14witness_tables16ConformingStructVAA11AnyProtocolA2aDP3ltgoi{{[_0-9a-zA-Z]*}}FZTW : $@convention(witness_method: AnyProtocol) (@in_guaranteed ConformingStruct, @in_guaranteed ConformingStruct, @thick ConformingStruct.Type) -> ()
// SYMBOL-TESTABLE: sil shared [transparent] [serialized] [thunk] [ossa] @$s14witness_tables16ConformingStructVAA11AnyProtocolA2aDP6method{{[_0-9a-zA-Z]*}}FTW : $@convention(witness_method: AnyProtocol) (Arg, @in_guaranteed ConformingStruct, @in_guaranteed ConformingStruct) -> ()
// SYMBOL-TESTABLE: sil shared [transparent] [serialized] [thunk] [ossa] @$s14witness_tables16ConformingStructVAA11AnyProtocolA2aDP7generic{{[_0-9a-zA-Z]*}}FTW : $@convention(witness_method: AnyProtocol) <τ_0_0 where τ_0_0 : ArchetypeReqt> (@in_guaranteed τ_0_0, @in_guaranteed ConformingStruct, @in_guaranteed ConformingStruct) -> ()
// SYMBOL-TESTABLE: sil shared [transparent] [serialized] [thunk] [ossa] @$s14witness_tables16ConformingStructVAA11AnyProtocolA2aDP16assocTypesMethod{{[_0-9a-zA-Z]*}}FTW : $@convention(witness_method: AnyProtocol) (@in_guaranteed SomeAssoc, @in_guaranteed ConformingAssoc, @in_guaranteed ConformingStruct) -> ()
// SYMBOL-TESTABLE: sil shared [transparent] [serialized] [thunk] [ossa] @$s14witness_tables16ConformingStructVAA11AnyProtocolA2aDP12staticMethod{{[_0-9a-zA-Z]*}}FZTW : $@convention(witness_method: AnyProtocol) (@in_guaranteed ConformingStruct, @thick ConformingStruct.Type) -> ()
// SYMBOL-TESTABLE: sil shared [transparent] [serialized] [thunk] [ossa] @$s14witness_tables16ConformingStructVAA11AnyProtocolA2aDP3ltgoi{{[_0-9a-zA-Z]*}}FZTW : $@convention(witness_method: AnyProtocol) (@in_guaranteed ConformingStruct, @in_guaranteed ConformingStruct, @thick ConformingStruct.Type) -> ()
protocol AddressOnly {}
struct ConformingAddressOnlyStruct : AnyProtocol {
var p: AddressOnly // force address-only layout with a protocol-type field
typealias AssocType = SomeAssoc
typealias AssocWithReqt = ConformingAssoc
func method(x: Arg, y: ConformingAddressOnlyStruct) {}
func generic<E: ArchetypeReqt>(x: E, y: ConformingAddressOnlyStruct) {}
func assocTypesMethod(x: SomeAssoc, y: ConformingAssoc) {}
static func staticMethod(x: ConformingAddressOnlyStruct) {}
}
func <~>(x: ConformingAddressOnlyStruct, y: ConformingAddressOnlyStruct) {}
// TABLE-LABEL: sil_witness_table hidden ConformingAddressOnlyStruct: AnyProtocol module witness_tables {
// TABLE-NEXT: associated_type_protocol (AssocWithReqt: AssocReqt): ConformingAssoc: AssocReqt module witness_tables
// TABLE-NEXT: associated_type AssocType: SomeAssoc
// TABLE-NEXT: associated_type AssocWithReqt: ConformingAssoc
// TABLE-NEXT: method #AnyProtocol.method!1: {{.*}} : @$s14witness_tables27ConformingAddressOnlyStructVAA11AnyProtocolA2aDP6method{{[_0-9a-zA-Z]*}}FTW
// TABLE-NEXT: method #AnyProtocol.generic!1: {{.*}} : @$s14witness_tables27ConformingAddressOnlyStructVAA11AnyProtocolA2aDP7generic{{[_0-9a-zA-Z]*}}FTW
// TABLE-NEXT: method #AnyProtocol.assocTypesMethod!1: {{.*}} : @$s14witness_tables27ConformingAddressOnlyStructVAA11AnyProtocolA2aDP16assocTypesMethod{{[_0-9a-zA-Z]*}}FTW
// TABLE-NEXT: method #AnyProtocol.staticMethod!1: {{.*}} : @$s14witness_tables27ConformingAddressOnlyStructVAA11AnyProtocolA2aDP12staticMethod{{[_0-9a-zA-Z]*}}FZTW
// TABLE-NEXT: method #AnyProtocol."<~>"!1: {{.*}} : @$s14witness_tables27ConformingAddressOnlyStructVAA11AnyProtocolA2aDP3ltgoi{{[_0-9a-zA-Z]*}}FZTW
// TABLE-NEXT: }
// SYMBOL: sil private [transparent] [thunk] [ossa] @$s14witness_tables27ConformingAddressOnlyStructVAA11AnyProtocolA2aDP6method{{[_0-9a-zA-Z]*}}FTW : $@convention(witness_method: AnyProtocol) (Arg, @in_guaranteed ConformingAddressOnlyStruct, @in_guaranteed ConformingAddressOnlyStruct) -> ()
// SYMBOL: sil private [transparent] [thunk] [ossa] @$s14witness_tables27ConformingAddressOnlyStructVAA11AnyProtocolA2aDP7generic{{[_0-9a-zA-Z]*}}FTW : $@convention(witness_method: AnyProtocol) <τ_0_0 where τ_0_0 : ArchetypeReqt> (@in_guaranteed τ_0_0, @in_guaranteed ConformingAddressOnlyStruct, @in_guaranteed ConformingAddressOnlyStruct) -> ()
// SYMBOL: sil private [transparent] [thunk] [ossa] @$s14witness_tables27ConformingAddressOnlyStructVAA11AnyProtocolA2aDP16assocTypesMethod{{[_0-9a-zA-Z]*}}FTW : $@convention(witness_method: AnyProtocol) (@in_guaranteed SomeAssoc, @in_guaranteed ConformingAssoc, @in_guaranteed ConformingAddressOnlyStruct) -> ()
// SYMBOL: sil private [transparent] [thunk] [ossa] @$s14witness_tables27ConformingAddressOnlyStructVAA11AnyProtocolA2aDP12staticMethod{{[_0-9a-zA-Z]*}}FZTW : $@convention(witness_method: AnyProtocol) (@in_guaranteed ConformingAddressOnlyStruct, @thick ConformingAddressOnlyStruct.Type) -> ()
// SYMBOL: sil private [transparent] [thunk] [ossa] @$s14witness_tables27ConformingAddressOnlyStructVAA11AnyProtocolA2aDP3ltgoi{{[_0-9a-zA-Z]*}}FZTW : $@convention(witness_method: AnyProtocol) (@in_guaranteed ConformingAddressOnlyStruct, @in_guaranteed ConformingAddressOnlyStruct, @thick ConformingAddressOnlyStruct.Type) -> ()
class ConformingClass : AnyProtocol {
typealias AssocType = SomeAssoc
typealias AssocWithReqt = ConformingAssoc
func method(x: Arg, y: ConformingClass) {}
func generic<F: ArchetypeReqt>(x: F, y: ConformingClass) {}
func assocTypesMethod(x: SomeAssoc, y: ConformingAssoc) {}
class func staticMethod(x: ConformingClass) {}
}
func <~>(x: ConformingClass, y: ConformingClass) {}
// TABLE-LABEL: sil_witness_table hidden ConformingClass: AnyProtocol module witness_tables {
// TABLE-NEXT: associated_type_protocol (AssocWithReqt: AssocReqt): ConformingAssoc: AssocReqt module witness_tables
// TABLE-NEXT: associated_type AssocType: SomeAssoc
// TABLE-NEXT: associated_type AssocWithReqt: ConformingAssoc
// TABLE-NEXT: method #AnyProtocol.method!1: {{.*}} : @$s14witness_tables15ConformingClassCAA11AnyProtocolA2aDP6method{{[_0-9a-zA-Z]*}}FTW
// TABLE-NEXT: method #AnyProtocol.generic!1: {{.*}} : @$s14witness_tables15ConformingClassCAA11AnyProtocolA2aDP7generic{{[_0-9a-zA-Z]*}}FTW
// TABLE-NEXT: method #AnyProtocol.assocTypesMethod!1: {{.*}} : @$s14witness_tables15ConformingClassCAA11AnyProtocolA2aDP16assocTypesMethod{{[_0-9a-zA-Z]*}}FTW
// TABLE-NEXT: method #AnyProtocol.staticMethod!1: {{.*}} : @$s14witness_tables15ConformingClassCAA11AnyProtocolA2aDP12staticMethod{{[_0-9a-zA-Z]*}}FZTW
// TABLE-NEXT: method #AnyProtocol."<~>"!1: {{.*}} : @$s14witness_tables15ConformingClassCAA11AnyProtocolA2aDP3ltgoi{{[_0-9a-zA-Z]*}}FZTW
// TABLE-NEXT: }
// SYMBOL: sil private [transparent] [thunk] [ossa] @$s14witness_tables15ConformingClassCAA11AnyProtocolA2aDP6method{{[_0-9a-zA-Z]*}}FTW : $@convention(witness_method: AnyProtocol) (Arg, @in_guaranteed ConformingClass, @in_guaranteed ConformingClass) -> ()
// SYMBOL: sil private [transparent] [thunk] [ossa] @$s14witness_tables15ConformingClassCAA11AnyProtocolA2aDP7generic{{[_0-9a-zA-Z]*}}FTW : $@convention(witness_method: AnyProtocol) <τ_0_0 where τ_0_0 : ArchetypeReqt> (@in_guaranteed τ_0_0, @in_guaranteed ConformingClass, @in_guaranteed ConformingClass) -> ()
// SYMBOL: sil private [transparent] [thunk] [ossa] @$s14witness_tables15ConformingClassCAA11AnyProtocolA2aDP16assocTypesMethod{{[_0-9a-zA-Z]*}}FTW : $@convention(witness_method: AnyProtocol) (@in_guaranteed SomeAssoc, @in_guaranteed ConformingAssoc, @in_guaranteed ConformingClass) -> ()
// SYMBOL: sil private [transparent] [thunk] [ossa] @$s14witness_tables15ConformingClassCAA11AnyProtocolA2aDP12staticMethod{{[_0-9a-zA-Z]*}}FZTW : $@convention(witness_method: AnyProtocol) (@in_guaranteed ConformingClass, @thick ConformingClass.Type) -> ()
// SYMBOL: sil private [transparent] [thunk] [ossa] @$s14witness_tables15ConformingClassCAA11AnyProtocolA2aDP3ltgoi{{[_0-9a-zA-Z]*}}FZTW : $@convention(witness_method: AnyProtocol) (@in_guaranteed ConformingClass, @in_guaranteed ConformingClass, @thick ConformingClass.Type) -> ()
struct ConformsByExtension {}
extension ConformsByExtension : AnyProtocol {
typealias AssocType = SomeAssoc
typealias AssocWithReqt = ConformingAssoc
func method(x: Arg, y: ConformsByExtension) {}
func generic<G: ArchetypeReqt>(x: G, y: ConformsByExtension) {}
func assocTypesMethod(x: SomeAssoc, y: ConformingAssoc) {}
static func staticMethod(x: ConformsByExtension) {}
}
func <~>(x: ConformsByExtension, y: ConformsByExtension) {}
// TABLE-LABEL: sil_witness_table hidden ConformsByExtension: AnyProtocol module witness_tables {
// TABLE-NEXT: associated_type_protocol (AssocWithReqt: AssocReqt): ConformingAssoc: AssocReqt module witness_tables
// TABLE-NEXT: associated_type AssocType: SomeAssoc
// TABLE-NEXT: associated_type AssocWithReqt: ConformingAssoc
// TABLE-NEXT: method #AnyProtocol.method!1: {{.*}} : @$s14witness_tables19ConformsByExtensionVAA11AnyProtocolA2aDP6method{{[_0-9a-zA-Z]*}}FTW
// TABLE-NEXT: method #AnyProtocol.generic!1: {{.*}} : @$s14witness_tables19ConformsByExtensionVAA11AnyProtocolA2aDP7generic{{[_0-9a-zA-Z]*}}FTW
// TABLE-NEXT: method #AnyProtocol.assocTypesMethod!1: {{.*}} : @$s14witness_tables19ConformsByExtensionVAA11AnyProtocolA2aDP16assocTypesMethod{{[_0-9a-zA-Z]*}}FTW
// TABLE-NEXT: method #AnyProtocol.staticMethod!1: {{.*}} : @$s14witness_tables19ConformsByExtensionVAA11AnyProtocolA2aDP12staticMethod{{[_0-9a-zA-Z]*}}FZTW
// TABLE-NEXT: method #AnyProtocol."<~>"!1: {{.*}} : @$s14witness_tables19ConformsByExtensionVAA11AnyProtocolA2aDP3ltgoi{{[_0-9a-zA-Z]*}}FZTW
// TABLE-NEXT: }
// SYMBOL: sil private [transparent] [thunk] [ossa] @$s14witness_tables19ConformsByExtensionVAA11AnyProtocolA2aDP6method{{[_0-9a-zA-Z]*}}FTW : $@convention(witness_method: AnyProtocol) (Arg, @in_guaranteed ConformsByExtension, @in_guaranteed ConformsByExtension) -> ()
// SYMBOL: sil private [transparent] [thunk] [ossa] @$s14witness_tables19ConformsByExtensionVAA11AnyProtocolA2aDP7generic{{[_0-9a-zA-Z]*}}FTW : $@convention(witness_method: AnyProtocol) <τ_0_0 where τ_0_0 : ArchetypeReqt> (@in_guaranteed τ_0_0, @in_guaranteed ConformsByExtension, @in_guaranteed ConformsByExtension) -> ()
// SYMBOL: sil private [transparent] [thunk] [ossa] @$s14witness_tables19ConformsByExtensionVAA11AnyProtocolA2aDP16assocTypesMethod{{[_0-9a-zA-Z]*}}FTW : $@convention(witness_method: AnyProtocol) (@in_guaranteed SomeAssoc, @in_guaranteed ConformingAssoc, @in_guaranteed ConformsByExtension) -> ()
// SYMBOL: sil private [transparent] [thunk] [ossa] @$s14witness_tables19ConformsByExtensionVAA11AnyProtocolA2aDP12staticMethod{{[_0-9a-zA-Z]*}}FZTW : $@convention(witness_method: AnyProtocol) (@in_guaranteed ConformsByExtension, @thick ConformsByExtension.Type) -> ()
// SYMBOL: sil private [transparent] [thunk] [ossa] @$s14witness_tables19ConformsByExtensionVAA11AnyProtocolA2aDP3ltgoi{{[_0-9a-zA-Z]*}}FZTW : $@convention(witness_method: AnyProtocol) (@in_guaranteed ConformsByExtension, @in_guaranteed ConformsByExtension, @thick ConformsByExtension.Type) -> ()
extension OtherModuleStruct : AnyProtocol {
typealias AssocType = SomeAssoc
typealias AssocWithReqt = ConformingAssoc
func method(x: Arg, y: OtherModuleStruct) {}
func generic<H: ArchetypeReqt>(x: H, y: OtherModuleStruct) {}
func assocTypesMethod(x: SomeAssoc, y: ConformingAssoc) {}
static func staticMethod(x: OtherModuleStruct) {}
}
func <~>(x: OtherModuleStruct, y: OtherModuleStruct) {}
// TABLE-LABEL: sil_witness_table hidden OtherModuleStruct: AnyProtocol module witness_tables {
// TABLE-NEXT: associated_type_protocol (AssocWithReqt: AssocReqt): ConformingAssoc: AssocReqt module witness_tables
// TABLE-NEXT: associated_type AssocType: SomeAssoc
// TABLE-NEXT: associated_type AssocWithReqt: ConformingAssoc
// TABLE-NEXT: method #AnyProtocol.method!1: {{.*}} : @$s16witness_tables_b17OtherModuleStructV0a1_B011AnyProtocolA2dEP6method{{[_0-9a-zA-Z]*}}FTW
// TABLE-NEXT: method #AnyProtocol.generic!1: {{.*}} : @$s16witness_tables_b17OtherModuleStructV0a1_B011AnyProtocolA2dEP7generic{{[_0-9a-zA-Z]*}}FTW
// TABLE-NEXT: method #AnyProtocol.assocTypesMethod!1: {{.*}} : @$s16witness_tables_b17OtherModuleStructV0a1_B011AnyProtocolA2dEP16assocTypesMethod{{[_0-9a-zA-Z]*}}FTW
// TABLE-NEXT: method #AnyProtocol.staticMethod!1: {{.*}} : @$s16witness_tables_b17OtherModuleStructV0a1_B011AnyProtocolA2dEP12staticMethod{{[_0-9a-zA-Z]*}}FZTW
// TABLE-NEXT: method #AnyProtocol."<~>"!1: {{.*}} : @$s16witness_tables_b17OtherModuleStructV0a1_B011AnyProtocolA2dEP3ltgoi{{[_0-9a-zA-Z]*}}FZTW
// TABLE-NEXT: }
// SYMBOL: sil private [transparent] [thunk] [ossa] @$s16witness_tables_b17OtherModuleStructV0a1_B011AnyProtocolA2dEP6method{{[_0-9a-zA-Z]*}}FTW : $@convention(witness_method: AnyProtocol) (Arg, @in_guaranteed OtherModuleStruct, @in_guaranteed OtherModuleStruct) -> ()
// SYMBOL: sil private [transparent] [thunk] [ossa] @$s16witness_tables_b17OtherModuleStructV0a1_B011AnyProtocolA2dEP7generic{{[_0-9a-zA-Z]*}}FTW : $@convention(witness_method: AnyProtocol) <τ_0_0 where τ_0_0 : ArchetypeReqt> (@in_guaranteed τ_0_0, @in_guaranteed OtherModuleStruct, @in_guaranteed OtherModuleStruct) -> ()
// SYMBOL: sil private [transparent] [thunk] [ossa] @$s16witness_tables_b17OtherModuleStructV0a1_B011AnyProtocolA2dEP16assocTypesMethod{{[_0-9a-zA-Z]*}}FTW : $@convention(witness_method: AnyProtocol) (@in_guaranteed SomeAssoc, @in_guaranteed ConformingAssoc, @in_guaranteed OtherModuleStruct) -> ()
// SYMBOL: sil private [transparent] [thunk] [ossa] @$s16witness_tables_b17OtherModuleStructV0a1_B011AnyProtocolA2dEP12staticMethod{{[_0-9a-zA-Z]*}}FZTW : $@convention(witness_method: AnyProtocol) (@in_guaranteed OtherModuleStruct, @thick OtherModuleStruct.Type) -> ()
// SYMBOL: sil private [transparent] [thunk] [ossa] @$s16witness_tables_b17OtherModuleStructV0a1_B011AnyProtocolA2dEP3ltgoi{{[_0-9a-zA-Z]*}}FZTW : $@convention(witness_method: AnyProtocol) (@in_guaranteed OtherModuleStruct, @in_guaranteed OtherModuleStruct, @thick OtherModuleStruct.Type) -> ()
protocol OtherProtocol {}
struct ConformsWithMoreGenericWitnesses : AnyProtocol, OtherProtocol {
typealias AssocType = SomeAssoc
typealias AssocWithReqt = ConformingAssoc
func method<I, J>(x: I, y: J) {}
func generic<K, L>(x: K, y: L) {}
func assocTypesMethod<M, N>(x: M, y: N) {}
static func staticMethod<O>(x: O) {}
}
func <~> <P: OtherProtocol>(x: P, y: P) {}
// TABLE-LABEL: sil_witness_table hidden ConformsWithMoreGenericWitnesses: AnyProtocol module witness_tables {
// TABLE-NEXT: associated_type_protocol (AssocWithReqt: AssocReqt): ConformingAssoc: AssocReqt module witness_tables
// TABLE-NEXT: associated_type AssocType: SomeAssoc
// TABLE-NEXT: associated_type AssocWithReqt: ConformingAssoc
// TABLE-NEXT: method #AnyProtocol.method!1: {{.*}} : @$s14witness_tables32ConformsWithMoreGenericWitnessesVAA11AnyProtocolA2aDP6method{{[_0-9a-zA-Z]*}}FTW
// TABLE-NEXT: method #AnyProtocol.generic!1: {{.*}} : @$s14witness_tables32ConformsWithMoreGenericWitnessesVAA11AnyProtocolA2aDP7generic{{[_0-9a-zA-Z]*}}FTW
// TABLE-NEXT: method #AnyProtocol.assocTypesMethod!1: {{.*}} : @$s14witness_tables32ConformsWithMoreGenericWitnessesVAA11AnyProtocolA2aDP16assocTypesMethod{{[_0-9a-zA-Z]*}}FTW
// TABLE-NEXT: method #AnyProtocol.staticMethod!1: {{.*}} : @$s14witness_tables32ConformsWithMoreGenericWitnessesVAA11AnyProtocolA2aDP12staticMethod{{[_0-9a-zA-Z]*}}FZTW
// TABLE-NEXT: method #AnyProtocol."<~>"!1: {{.*}} : @$s14witness_tables32ConformsWithMoreGenericWitnessesVAA11AnyProtocolA2aDP3ltgoi{{[_0-9a-zA-Z]*}}FZTW
// TABLE-NEXT: }
// SYMBOL: sil private [transparent] [thunk] [ossa] @$s14witness_tables32ConformsWithMoreGenericWitnessesVAA11AnyProtocolA2aDP6method{{[_0-9a-zA-Z]*}}FTW : $@convention(witness_method: AnyProtocol) (Arg, @in_guaranteed ConformsWithMoreGenericWitnesses, @in_guaranteed ConformsWithMoreGenericWitnesses) -> ()
// SYMBOL: sil private [transparent] [thunk] [ossa] @$s14witness_tables32ConformsWithMoreGenericWitnessesVAA11AnyProtocolA2aDP7generic{{[_0-9a-zA-Z]*}}FTW : $@convention(witness_method: AnyProtocol) <τ_0_0 where τ_0_0 : ArchetypeReqt> (@in_guaranteed τ_0_0, @in_guaranteed ConformsWithMoreGenericWitnesses, @in_guaranteed ConformsWithMoreGenericWitnesses) -> ()
// SYMBOL: sil private [transparent] [thunk] [ossa] @$s14witness_tables32ConformsWithMoreGenericWitnessesVAA11AnyProtocolA2aDP16assocTypesMethod{{[_0-9a-zA-Z]*}}FTW : $@convention(witness_method: AnyProtocol) (@in_guaranteed SomeAssoc, @in_guaranteed ConformingAssoc, @in_guaranteed ConformsWithMoreGenericWitnesses) -> ()
// SYMBOL: sil private [transparent] [thunk] [ossa] @$s14witness_tables32ConformsWithMoreGenericWitnessesVAA11AnyProtocolA2aDP12staticMethod{{[_0-9a-zA-Z]*}}FZTW : $@convention(witness_method: AnyProtocol) (@in_guaranteed ConformsWithMoreGenericWitnesses, @thick ConformsWithMoreGenericWitnesses.Type) -> ()
// SYMBOL: sil private [transparent] [thunk] [ossa] @$s14witness_tables32ConformsWithMoreGenericWitnessesVAA11AnyProtocolA2aDP3ltgoi{{[_0-9a-zA-Z]*}}FZTW : $@convention(witness_method: AnyProtocol) (@in_guaranteed ConformsWithMoreGenericWitnesses, @in_guaranteed ConformsWithMoreGenericWitnesses, @thick ConformsWithMoreGenericWitnesses.Type) -> ()
class ConformingClassToClassProtocol : ClassProtocol {
typealias AssocType = SomeAssoc
typealias AssocWithReqt = ConformingAssoc
func method(x: Arg, y: ConformingClassToClassProtocol) {}
func generic<Q: ArchetypeReqt>(x: Q, y: ConformingClassToClassProtocol) {}
func assocTypesMethod(x: SomeAssoc, y: ConformingAssoc) {}
class func staticMethod(x: ConformingClassToClassProtocol) {}
}
func <~>(x: ConformingClassToClassProtocol,
y: ConformingClassToClassProtocol) {}
// TABLE-LABEL: sil_witness_table hidden ConformingClassToClassProtocol: ClassProtocol module witness_tables {
// TABLE-NEXT: associated_type_protocol (AssocWithReqt: AssocReqt): ConformingAssoc: AssocReqt module witness_tables
// TABLE-NEXT: associated_type AssocType: SomeAssoc
// TABLE-NEXT: associated_type AssocWithReqt: ConformingAssoc
// TABLE-NEXT: method #ClassProtocol.method!1: {{.*}} : @$s14witness_tables017ConformingClassToD8ProtocolCAA0dF0A2aDP6method{{[_0-9a-zA-Z]*}}FTW
// TABLE-NEXT: method #ClassProtocol.generic!1: {{.*}} : @$s14witness_tables017ConformingClassToD8ProtocolCAA0dF0A2aDP7generic{{[_0-9a-zA-Z]*}}FTW
// TABLE-NEXT: method #ClassProtocol.assocTypesMethod!1: {{.*}} : @$s14witness_tables017ConformingClassToD8ProtocolCAA0dF0A2aDP16assocTypesMethod{{[_0-9a-zA-Z]*}}FTW
// TABLE-NEXT: method #ClassProtocol.staticMethod!1: {{.*}} : @$s14witness_tables017ConformingClassToD8ProtocolCAA0dF0A2aDP12staticMethod{{[_0-9a-zA-Z]*}}FZTW
// TABLE-NEXT: method #ClassProtocol."<~>"!1: {{.*}} : @$s14witness_tables017ConformingClassToD8ProtocolCAA0dF0A2aDP3ltgoi{{[_0-9a-zA-Z]*}}FZTW
// TABLE-NEXT: }
// SYMBOL: sil private [transparent] [thunk] [ossa] @$s14witness_tables017ConformingClassToD8ProtocolCAA0dF0A2aDP6method{{[_0-9a-zA-Z]*}}FTW : $@convention(witness_method: ClassProtocol) (Arg, @guaranteed ConformingClassToClassProtocol, @guaranteed ConformingClassToClassProtocol) -> ()
// SYMBOL: sil private [transparent] [thunk] [ossa] @$s14witness_tables017ConformingClassToD8ProtocolCAA0dF0A2aDP7generic{{[_0-9a-zA-Z]*}}FTW : $@convention(witness_method: ClassProtocol) <τ_0_0 where τ_0_0 : ArchetypeReqt> (@in_guaranteed τ_0_0, @guaranteed ConformingClassToClassProtocol, @guaranteed ConformingClassToClassProtocol) -> ()
// SYMBOL: sil private [transparent] [thunk] [ossa] @$s14witness_tables017ConformingClassToD8ProtocolCAA0dF0A2aDP16assocTypesMethod{{[_0-9a-zA-Z]*}}FTW : $@convention(witness_method: ClassProtocol) (@in_guaranteed SomeAssoc, @in_guaranteed ConformingAssoc, @guaranteed ConformingClassToClassProtocol) -> ()
// SYMBOL: sil private [transparent] [thunk] [ossa] @$s14witness_tables017ConformingClassToD8ProtocolCAA0dF0A2aDP12staticMethod{{[_0-9a-zA-Z]*}}FZTW : $@convention(witness_method: ClassProtocol) (@guaranteed ConformingClassToClassProtocol, @thick ConformingClassToClassProtocol.Type) -> ()
// SYMBOL: sil private [transparent] [thunk] [ossa] @$s14witness_tables017ConformingClassToD8ProtocolCAA0dF0A2aDP3ltgoi{{[_0-9a-zA-Z]*}}FZTW : $@convention(witness_method: ClassProtocol) (@guaranteed ConformingClassToClassProtocol, @guaranteed ConformingClassToClassProtocol, @thick ConformingClassToClassProtocol.Type) -> ()
class ConformingClassToObjCProtocol : ObjCProtocol {
@objc func method(x: ObjCClass) {}
@objc class func staticMethod(y: ObjCClass) {}
}
// TABLE-NOT: sil_witness_table hidden ConformingClassToObjCProtocol
struct ConformingGeneric<R: AssocReqt> : AnyProtocol {
typealias AssocType = SomeAssoc
typealias AssocWithReqt = R
func method(x: Arg, y: ConformingGeneric) {}
func generic<Q: ArchetypeReqt>(x: Q, y: ConformingGeneric) {}
func assocTypesMethod(x: SomeAssoc, y: R) {}
static func staticMethod(x: ConformingGeneric) {}
}
func <~> <R: AssocReqt>(x: ConformingGeneric<R>, y: ConformingGeneric<R>) {}
// TABLE-LABEL: sil_witness_table hidden <R where R : AssocReqt> ConformingGeneric<R>: AnyProtocol module witness_tables {
// TABLE-NEXT: associated_type_protocol (AssocWithReqt: AssocReqt): dependent
// TABLE-NEXT: associated_type AssocType: SomeAssoc
// TABLE-NEXT: associated_type AssocWithReqt: R
// TABLE-NEXT: method #AnyProtocol.method!1: {{.*}} : @$s14witness_tables17ConformingGenericVyxGAA11AnyProtocolA2aEP6method{{[_0-9a-zA-Z]*}}FTW
// TABLE-NEXT: method #AnyProtocol.generic!1: {{.*}} : @$s14witness_tables17ConformingGenericVyxGAA11AnyProtocolA2aEP7generic{{[_0-9a-zA-Z]*}}FTW
// TABLE-NEXT: method #AnyProtocol.assocTypesMethod!1: {{.*}} : @$s14witness_tables17ConformingGenericVyxGAA11AnyProtocolA2aEP16assocTypesMetho{{[_0-9a-zA-Z]*}}FTW
// TABLE-NEXT: method #AnyProtocol.staticMethod!1: {{.*}} : @$s14witness_tables17ConformingGenericVyxGAA11AnyProtocolA2aEP12staticMethod{{[_0-9a-zA-Z]*}}FZTW
// TABLE-NEXT: method #AnyProtocol."<~>"!1: {{.*}} : @$s14witness_tables17ConformingGenericVyxGAA11AnyProtocolA2aEP3ltgoi{{[_0-9a-zA-Z]*}}FZTW
// TABLE-NEXT: }
protocol AnotherProtocol {}
struct ConformingGenericWithMoreGenericWitnesses<S: AssocReqt>
: AnyProtocol, AnotherProtocol
{
typealias AssocType = SomeAssoc
typealias AssocWithReqt = S
func method<T, U>(x: T, y: U) {}
func generic<V, W>(x: V, y: W) {}
func assocTypesMethod<X, Y>(x: X, y: Y) {}
static func staticMethod<Z>(x: Z) {}
}
func <~> <AA: AnotherProtocol, BB: AnotherProtocol>(x: AA, y: BB) {}
// TABLE-LABEL: sil_witness_table hidden <S where S : AssocReqt> ConformingGenericWithMoreGenericWitnesses<S>: AnyProtocol module witness_tables {
// TABLE-NEXT: associated_type_protocol (AssocWithReqt: AssocReqt): dependent
// TABLE-NEXT: associated_type AssocType: SomeAssoc
// TABLE-NEXT: associated_type AssocWithReqt: S
// TABLE-NEXT: method #AnyProtocol.method!1: {{.*}} : @$s14witness_tables025ConformingGenericWithMoreD9WitnessesVyxGAA11AnyProtocolA2aEP6method{{[_0-9a-zA-Z]*}}FTW
// TABLE-NEXT: method #AnyProtocol.generic!1: {{.*}} : @$s14witness_tables025ConformingGenericWithMoreD9WitnessesVyxGAA11AnyProtocolA2aEP7{{[_0-9a-zA-Z]*}}FTW
// TABLE-NEXT: method #AnyProtocol.assocTypesMethod!1: {{.*}} : @$s14witness_tables025ConformingGenericWithMoreD9WitnessesVyxGAA11AnyProtocolA2aEP16assocTypesMethod{{[_0-9a-zA-Z]*}}FTW
// TABLE-NEXT: method #AnyProtocol.staticMethod!1: {{.*}} : @$s14witness_tables025ConformingGenericWithMoreD9WitnessesVyxGAA11AnyProtocolA2aEP12staticMethod{{[_0-9a-zA-Z]*}}FZTW
// TABLE-NEXT: method #AnyProtocol."<~>"!1: {{.*}} : @$s14witness_tables025ConformingGenericWithMoreD9WitnessesVyxGAA11AnyProtocolA2aEP3ltgoi{{[_0-9a-zA-Z]*}}FZTW
// TABLE-NEXT: }
protocol InheritedProtocol1 : AnyProtocol {
func inheritedMethod()
}
protocol InheritedProtocol2 : AnyProtocol {
func inheritedMethod()
}
protocol InheritedClassProtocol : class, AnyProtocol {
func inheritedMethod()
}
struct InheritedConformance : InheritedProtocol1 {
typealias AssocType = SomeAssoc
typealias AssocWithReqt = ConformingAssoc
func method(x: Arg, y: InheritedConformance) {}
func generic<H: ArchetypeReqt>(x: H, y: InheritedConformance) {}
func assocTypesMethod(x: SomeAssoc, y: ConformingAssoc) {}
static func staticMethod(x: InheritedConformance) {}
func inheritedMethod() {}
}
func <~>(x: InheritedConformance, y: InheritedConformance) {}
// TABLE-LABEL: sil_witness_table hidden InheritedConformance: InheritedProtocol1 module witness_tables {
// TABLE-NEXT: base_protocol AnyProtocol: InheritedConformance: AnyProtocol module witness_tables
// TABLE-NEXT: method #InheritedProtocol1.inheritedMethod!1: {{.*}} : @$s14witness_tables20InheritedConformanceVAA0C9Protocol1A2aDP15inheritedMethod{{[_0-9a-zA-Z]*}}FTW
// TABLE-NEXT: }
// TABLE-LABEL: sil_witness_table hidden InheritedConformance: AnyProtocol module witness_tables {
// TABLE-NEXT: associated_type_protocol (AssocWithReqt: AssocReqt): ConformingAssoc: AssocReqt module witness_tables
// TABLE-NEXT: associated_type AssocType: SomeAssoc
// TABLE-NEXT: associated_type AssocWithReqt: ConformingAssoc
// TABLE-NEXT: method #AnyProtocol.method!1: {{.*}} : @$s14witness_tables20InheritedConformanceVAA11AnyProtocolA2aDP6method{{[_0-9a-zA-Z]*}}FTW
// TABLE-NEXT: method #AnyProtocol.generic!1: {{.*}} : @$s14witness_tables20InheritedConformanceVAA11AnyProtocolA2aDP7generic{{[_0-9a-zA-Z]*}}FTW
// TABLE-NEXT: method #AnyProtocol.assocTypesMethod!1: {{.*}} : @$s14witness_tables20InheritedConformanceVAA11AnyProtocolA2aDP16assocTypesMethod{{[_0-9a-zA-Z]*}}FTW
// TABLE-NEXT: method #AnyProtocol.staticMethod!1: {{.*}} : @$s14witness_tables20InheritedConformanceVAA11AnyProtocolA2aDP12staticMethod{{[_0-9a-zA-Z]*}}FZTW
// TABLE-NEXT: method #AnyProtocol."<~>"!1: {{.*}} : @$s14witness_tables20InheritedConformanceVAA11AnyProtocolA2aDP3ltgoi{{[_0-9a-zA-Z]*}}FZTW
// TABLE-NEXT: }
struct RedundantInheritedConformance : InheritedProtocol1, AnyProtocol {
typealias AssocType = SomeAssoc
typealias AssocWithReqt = ConformingAssoc
func method(x: Arg, y: RedundantInheritedConformance) {}
func generic<H: ArchetypeReqt>(x: H, y: RedundantInheritedConformance) {}
func assocTypesMethod(x: SomeAssoc, y: ConformingAssoc) {}
static func staticMethod(x: RedundantInheritedConformance) {}
func inheritedMethod() {}
}
func <~>(x: RedundantInheritedConformance, y: RedundantInheritedConformance) {}
// TABLE-LABEL: sil_witness_table hidden RedundantInheritedConformance: InheritedProtocol1 module witness_tables {
// TABLE-NEXT: base_protocol AnyProtocol: RedundantInheritedConformance: AnyProtocol module witness_tables
// TABLE-NEXT: method #InheritedProtocol1.inheritedMethod!1: {{.*}} : @$s14witness_tables29RedundantInheritedConformanceVAA0D9Protocol1A2aDP15inheritedMethod{{[_0-9a-zA-Z]*}}FTW
// TABLE-NEXT: }
// TABLE-LABEL: sil_witness_table hidden RedundantInheritedConformance: AnyProtocol module witness_tables {
// TABLE-NEXT: associated_type_protocol (AssocWithReqt: AssocReqt): ConformingAssoc: AssocReqt module witness_tables
// TABLE-NEXT: associated_type AssocType: SomeAssoc
// TABLE-NEXT: associated_type AssocWithReqt: ConformingAssoc
// TABLE-NEXT: method #AnyProtocol.method!1: {{.*}} : @$s14witness_tables29RedundantInheritedConformanceVAA11AnyProtocolA2aDP6method{{[_0-9a-zA-Z]*}}FTW
// TABLE-NEXT: method #AnyProtocol.generic!1: {{.*}} : @$s14witness_tables29RedundantInheritedConformanceVAA11AnyProtocolA2aDP7generic{{[_0-9a-zA-Z]*}}FTW
// TABLE-NEXT: method #AnyProtocol.assocTypesMethod!1: {{.*}} : @$s14witness_tables29RedundantInheritedConformanceVAA11AnyProtocolA2aDP16assocTypesMethod{{[_0-9a-zA-Z]*}}FTW
// TABLE-NEXT: method #AnyProtocol.staticMethod!1: {{.*}} : @$s14witness_tables29RedundantInheritedConformanceVAA11AnyProtocolA2aDP12staticMethod{{[_0-9a-zA-Z]*}}FZTW
// TABLE-NEXT: method #AnyProtocol."<~>"!1: {{.*}} : @$s14witness_tables29RedundantInheritedConformanceVAA11AnyProtocolA2aDP3ltgoi{{[_0-9a-zA-Z]*}}FZTW
// TABLE-NEXT: }
struct DiamondInheritedConformance : InheritedProtocol1, InheritedProtocol2 {
typealias AssocType = SomeAssoc
typealias AssocWithReqt = ConformingAssoc
func method(x: Arg, y: DiamondInheritedConformance) {}
func generic<H: ArchetypeReqt>(x: H, y: DiamondInheritedConformance) {}
func assocTypesMethod(x: SomeAssoc, y: ConformingAssoc) {}
static func staticMethod(x: DiamondInheritedConformance) {}
func inheritedMethod() {}
}
func <~>(x: DiamondInheritedConformance, y: DiamondInheritedConformance) {}
// TABLE-LABEL: sil_witness_table hidden DiamondInheritedConformance: InheritedProtocol1 module witness_tables {
// TABLE-NEXT: base_protocol AnyProtocol: DiamondInheritedConformance: AnyProtocol module witness_tables
// TABLE-NEXT: method #InheritedProtocol1.inheritedMethod!1: {{.*}} : @$s14witness_tables27DiamondInheritedConformanceVAA0D9Protocol1A2aDP15inheritedMethod{{[_0-9a-zA-Z]*}}FTW
// TABLE-NEXT: }
// TABLE-LABEL: sil_witness_table hidden DiamondInheritedConformance: InheritedProtocol2 module witness_tables {
// TABLE-NEXT: base_protocol AnyProtocol: DiamondInheritedConformance: AnyProtocol module witness_tables
// TABLE-NEXT: method #InheritedProtocol2.inheritedMethod!1: {{.*}} : @$s14witness_tables27DiamondInheritedConformanceVAA0D9Protocol2A2aDP15inheritedMethod{{[_0-9a-zA-Z]*}}FTW
// TABLE-NEXT: }
// TABLE-LABEL: sil_witness_table hidden DiamondInheritedConformance: AnyProtocol module witness_tables {
// TABLE-NEXT: associated_type_protocol (AssocWithReqt: AssocReqt): ConformingAssoc: AssocReqt module witness_tables
// TABLE-NEXT: associated_type AssocType: SomeAssoc
// TABLE-NEXT: associated_type AssocWithReqt: ConformingAssoc
// TABLE-NEXT: method #AnyProtocol.method!1: {{.*}} : @$s14witness_tables27DiamondInheritedConformanceVAA11AnyProtocolA2aDP6method{{[_0-9a-zA-Z]*}}FTW
// TABLE-NEXT: method #AnyProtocol.generic!1: {{.*}} : @$s14witness_tables27DiamondInheritedConformanceVAA11AnyProtocolA2aDP7generic{{[_0-9a-zA-Z]*}}FTW
// TABLE-NEXT: method #AnyProtocol.assocTypesMethod!1: {{.*}} : @$s14witness_tables27DiamondInheritedConformanceVAA11AnyProtocolA2aDP16assocTypesMethod{{[_0-9a-zA-Z]*}}FTW
// TABLE-NEXT: method #AnyProtocol.staticMethod!1: {{.*}} : @$s14witness_tables27DiamondInheritedConformanceVAA11AnyProtocolA2aDP12staticMethod{{[_0-9a-zA-Z]*}}FZTW
// TABLE-NEXT: method #AnyProtocol."<~>"!1: {{.*}} : @$s14witness_tables27DiamondInheritedConformanceVAA11AnyProtocolA2aDP3ltgoi{{[_0-9a-zA-Z]*}}FZTW
// TABLE-NEXT: }
class ClassInheritedConformance : InheritedClassProtocol {
typealias AssocType = SomeAssoc
typealias AssocWithReqt = ConformingAssoc
func method(x: Arg, y: ClassInheritedConformance) {}
func generic<H: ArchetypeReqt>(x: H, y: ClassInheritedConformance) {}
func assocTypesMethod(x: SomeAssoc, y: ConformingAssoc) {}
class func staticMethod(x: ClassInheritedConformance) {}
func inheritedMethod() {}
}
func <~>(x: ClassInheritedConformance, y: ClassInheritedConformance) {}
// TABLE-LABEL: sil_witness_table hidden ClassInheritedConformance: InheritedClassProtocol module witness_tables {
// TABLE-NEXT: base_protocol AnyProtocol: ClassInheritedConformance: AnyProtocol module witness_tables
// TABLE-NEXT: method #InheritedClassProtocol.inheritedMethod!1: {{.*}} : @$s14witness_tables25ClassInheritedConformanceCAA0dC8ProtocolA2aDP15inheritedMethod{{[_0-9a-zA-Z]*}}FTW
// TABLE-NEXT: }
// TABLE-LABEL: sil_witness_table hidden ClassInheritedConformance: AnyProtocol module witness_tables {
// TABLE-NEXT: associated_type_protocol (AssocWithReqt: AssocReqt): ConformingAssoc: AssocReqt module witness_tables
// TABLE-NEXT: associated_type AssocType: SomeAssoc
// TABLE-NEXT: associated_type AssocWithReqt: ConformingAssoc
// TABLE-NEXT: method #AnyProtocol.method!1: {{.*}} : @$s14witness_tables25ClassInheritedConformanceCAA11AnyProtocolA2aDP6method{{[_0-9a-zA-Z]*}}FTW
// TABLE-NEXT: method #AnyProtocol.generic!1: {{.*}} : @$s14witness_tables25ClassInheritedConformanceCAA11AnyProtocolA2aDP7generic{{[_0-9a-zA-Z]*}}FTW
// TABLE-NEXT: method #AnyProtocol.assocTypesMethod!1: {{.*}} : @$s14witness_tables25ClassInheritedConformanceCAA11AnyProtocolA2aDP16assocTypesMethod{{[_0-9a-zA-Z]*}}FTW
// TABLE-NEXT: method #AnyProtocol.staticMethod!1: {{.*}} : @$s14witness_tables25ClassInheritedConformanceCAA11AnyProtocolA2aDP12staticMethod{{[_0-9a-zA-Z]*}}FZTW
// TABLE-NEXT: method #AnyProtocol."<~>"!1: {{.*}} : @$s14witness_tables25ClassInheritedConformanceCAA11AnyProtocolA2aDP3ltgoi{{[_0-9a-zA-Z]*}}FZTW
// TABLE-NEXT: }
// -- Witnesses have the 'self' abstraction level of their protocol.
// AnyProtocol has no class bound, so its witnesses treat Self as opaque.
// InheritedClassProtocol has a class bound, so its witnesses treat Self as
// a reference value.
// SYMBOL: sil private [transparent] [thunk] [ossa] @$s14witness_tables25ClassInheritedConformanceCAA0dC8ProtocolA2aDP15inheritedMethod{{[_0-9a-zA-Z]*}}FTW : $@convention(witness_method: InheritedClassProtocol) (@guaranteed ClassInheritedConformance) -> ()
// SYMBOL: sil private [transparent] [thunk] [ossa] @$s14witness_tables25ClassInheritedConformanceCAA11AnyProtocolA2aDP6method{{[_0-9a-zA-Z]*}}FTW : $@convention(witness_method: AnyProtocol) (Arg, @in_guaranteed ClassInheritedConformance, @in_guaranteed ClassInheritedConformance) -> ()
struct GenericAssocType<T> : AssocReqt {
func requiredMethod() {}
}
protocol AssocTypeWithReqt {
associatedtype AssocType : AssocReqt
}
struct ConformsWithDependentAssocType1<CC: AssocReqt> : AssocTypeWithReqt {
typealias AssocType = CC
}
// TABLE-LABEL: sil_witness_table hidden <CC where CC : AssocReqt> ConformsWithDependentAssocType1<CC>: AssocTypeWithReqt module witness_tables {
// TABLE-NEXT: associated_type_protocol (AssocType: AssocReqt): dependent
// TABLE-NEXT: associated_type AssocType: CC
// TABLE-NEXT: }
struct ConformsWithDependentAssocType2<DD> : AssocTypeWithReqt {
typealias AssocType = GenericAssocType<DD>
}
// TABLE-LABEL: sil_witness_table hidden <DD> ConformsWithDependentAssocType2<DD>: AssocTypeWithReqt module witness_tables {
// TABLE-NEXT: associated_type_protocol (AssocType: AssocReqt): <T> GenericAssocType<T>: AssocReqt module witness_tables
// TABLE-NEXT: associated_type AssocType: GenericAssocType<DD>
// TABLE-NEXT: }
protocol InheritedFromObjC : ObjCProtocol {
func inheritedMethod()
}
class ConformsInheritedFromObjC : InheritedFromObjC {
@objc func method(x: ObjCClass) {}
@objc class func staticMethod(y: ObjCClass) {}
func inheritedMethod() {}
}
// TABLE-LABEL: sil_witness_table hidden ConformsInheritedFromObjC: InheritedFromObjC module witness_tables {
// TABLE-NEXT: method #InheritedFromObjC.inheritedMethod!1: {{.*}} : @$s14witness_tables25ConformsInheritedFromObjCCAA0deF1CA2aDP15inheritedMethod{{[_0-9a-zA-Z]*}}FTW
// TABLE-NEXT: }
protocol ObjCAssoc {
associatedtype AssocType : ObjCProtocol
}
struct HasObjCAssoc : ObjCAssoc {
typealias AssocType = ConformsInheritedFromObjC
}
// TABLE-LABEL: sil_witness_table hidden HasObjCAssoc: ObjCAssoc module witness_tables {
// TABLE-NEXT: associated_type AssocType: ConformsInheritedFromObjC
// TABLE-NEXT: }
protocol Initializer {
init(arg: Arg)
}
// TABLE-LABEL: sil_witness_table hidden HasInitializerStruct: Initializer module witness_tables {
// TABLE-NEXT: method #Initializer.init!allocator.1: {{.*}} : @$s14witness_tables20HasInitializerStructVAA0D0A2aDP{{[_0-9a-zA-Z]*}}fCTW
// TABLE-NEXT: }
// SYMBOL: sil private [transparent] [thunk] [ossa] @$s14witness_tables20HasInitializerStructVAA0D0A2aDP{{[_0-9a-zA-Z]*}}fCTW : $@convention(witness_method: Initializer) (Arg, @thick HasInitializerStruct.Type) -> @out HasInitializerStruct
struct HasInitializerStruct : Initializer {
init(arg: Arg) { }
}
// TABLE-LABEL: sil_witness_table hidden HasInitializerClass: Initializer module witness_tables {
// TABLE-NEXT: method #Initializer.init!allocator.1: {{.*}} : @$s14witness_tables19HasInitializerClassCAA0D0A2aDP{{[_0-9a-zA-Z]*}}fCTW
// TABLE-NEXT: }
// SYMBOL: sil private [transparent] [thunk] [ossa] @$s14witness_tables19HasInitializerClassCAA0D0A2aDP{{[_0-9a-zA-Z]*}}fCTW : $@convention(witness_method: Initializer) (Arg, @thick HasInitializerClass.Type) -> @out HasInitializerClass
class HasInitializerClass : Initializer {
required init(arg: Arg) { }
}
// TABLE-LABEL: sil_witness_table hidden HasInitializerEnum: Initializer module witness_tables {
// TABLE-NEXT: method #Initializer.init!allocator.1: {{.*}} : @$s14witness_tables18HasInitializerEnumOAA0D0A2aDP{{[_0-9a-zA-Z]*}}fCTW
// TABLE-NEXT: }
// SYMBOL: sil private [transparent] [thunk] [ossa] @$s14witness_tables18HasInitializerEnumOAA0D0A2aDP{{[_0-9a-zA-Z]*}}fCTW : $@convention(witness_method: Initializer) (Arg, @thick HasInitializerEnum.Type) -> @out HasInitializerEnum
enum HasInitializerEnum : Initializer {
case A
init(arg: Arg) { self = .A }
}
| apache-2.0 | a3c7f019074619f18b5a02eae0b2b66e | 75.985481 | 366 | 0.760178 | 3.641741 | false | false | false | false |
brentsimmons/Frontier | BeforeTheRename/UserTalk/UserTalk/Tables/Builtins.swift | 1 | 1444 | //
// Builtins.swift
// UserTalk
//
// Created by Brent Simmons on 4/30/17.
// Copyright © 2017 Ranchero Software. All rights reserved.
//
import Foundation
import FrontierData
// OrigFrontier: langstartup.c
// system.compiler.language.builtins
let appleeventfunc = 0
let complexeventfunc = 1
let findereventfunc = 2
let tableeventfunc = 3
let objspecfunc = 4
let setobjspecfunc = 5
let packfunc = 6
let unpackfunc = 7
let definedfunc = 8
let typeoffunc = 9
let sizeoffunc = 10
let nameoffunc = 11
let parentoffunc = 12
let indexoffunc = 13
let gestaltfunc = 14
let syscrashfunc = 15
let myMooffunc = 16
struct Builtins {
static let builtinsTable: HashTable = {
let t = HashTable("builtins", Tables.languageTable)
t.add("appleevent", appleeventfunc)
t.add("complexevent", complexeventfunc)
t.add("finderevent", findereventfunc)
t.add("tableevent", tableeventfunc)
t.add("objspec", objspecfunc)
t.add("setobj", setobjspecfunc)
t.add("pack", packfunc)
t.add("unpack", unpackfunc)
t.add("defined", definedfunc)
t.add("typeof", typeoffunc)
t.add("sizeof", sizeoffunc)
t.add("nameof", nameoffunc)
t.add("parentof", parentoffunc)
t.add("indexof", indexoffunc)
t.add("gestalt", gestaltfunc)
t.add("syscrash", syscrashfunc)
t.add("myMoof", myMooffunc)
t.isReadOnly = true
return t
}()
static func lookup(_ identifier: String) -> Int? {
return builtinsTable.lookup(identifier) as? Int
}
}
| gpl-2.0 | 7a96cc3fc55573a7eee7e6bede9c5742 | 20.220588 | 60 | 0.71587 | 2.926978 | false | false | false | false |
tilomba/GMap1 | GMap1/PlaceMarker.swift | 1 | 520 | //
// PlaceMarker.swift
// GMap1
//
// Created by Michael Myles on 7/19/15.
// Copyright (c) 2015 Ron Kliffer. All rights reserved.
//
import Foundation
class PlaceMarker: GMSMarker {
// 1
let place: GooglePlace
// 2
init(place: GooglePlace) {
self.place = place
super.init()
position = place.coordinate
icon = UIImage(named: place.placeType+"_pin")
groundAnchor = CGPoint(x: 0.5, y: 1)
appearAnimation = kGMSMarkerAnimationPop
}
} | cc0-1.0 | c2f8f51e0fa6b398b343b4eb1f42de25 | 19.038462 | 56 | 0.6 | 3.768116 | false | false | false | false |
azukinohiroki/positionmaker2 | positionmaker2/DashDrawingView.swift | 1 | 833 | //
// DashDrawingView.swift
// positionmaker2
//
// Created by Hiroki Taoka on 2015/06/23.
// Copyright (c) 2015年 azukinohiroki. All rights reserved.
//
import Foundation
import UIKit
class DashDrawingView: UIView {
private var _drawingRect = CGRect.zero
private var _draw = false
override func draw(_ rect: CGRect) {
if _draw {
let bezier = UIBezierPath(rect: _drawingRect)
UIColor.black.setStroke()
let pattern: [CGFloat] = [5, 5]
bezier.setLineDash(pattern, count: 2, phase: 0)
bezier.stroke()
}
}
func setDrawingRect(rect: CGRect) {
_draw = true
_drawingRect = rect
setNeedsDisplay()
}
func clear() {
_draw = false
_drawingRect = CGRect.zero
setNeedsDisplay()
}
func getDrawingRect() -> CGRect {
return _drawingRect
}
}
| mit | dfac3d6bb5f74b23d617467cd9131db4 | 18.785714 | 59 | 0.636582 | 3.676991 | false | false | false | false |
jannainm/wingman | Wingman/Wingman/MasterViewController.swift | 1 | 3668 | //
// MasterViewController.swift
// Wingman
//
// Created by Michael Jannain on 10/3/15.
// Copyright (c) 2015 Michael Jannain. All rights reserved.
//
import UIKit
class MasterViewController: UITableViewController {
var detailViewController: DetailViewController? = nil
var objects = [AnyObject]()
override func awakeFromNib() {
super.awakeFromNib()
if UIDevice.currentDevice().userInterfaceIdiom == .Pad {
self.clearsSelectionOnViewWillAppear = false
self.preferredContentSize = CGSize(width: 320.0, height: 600.0)
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.navigationItem.leftBarButtonItem = self.editButtonItem()
let addButton = UIBarButtonItem(barButtonSystemItem: .Add, target: self, action: "insertNewObject:")
self.navigationItem.rightBarButtonItem = addButton
if let split = self.splitViewController {
let controllers = split.viewControllers
self.detailViewController = controllers[controllers.count-1].topViewController as? DetailViewController
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func insertNewObject(sender: AnyObject) {
objects.insert(NSDate(), atIndex: 0)
let indexPath = NSIndexPath(forRow: 0, inSection: 0)
self.tableView.insertRowsAtIndexPaths([indexPath], withRowAnimation: .Automatic)
}
// MARK: - Segues
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "showDetail" {
if let indexPath = self.tableView.indexPathForSelectedRow() {
let object = objects[indexPath.row] as! NSDate
let controller = (segue.destinationViewController as! UINavigationController).topViewController as! DetailViewController
controller.detailItem = object
controller.navigationItem.leftBarButtonItem = self.splitViewController?.displayModeButtonItem()
controller.navigationItem.leftItemsSupplementBackButton = true
}
}
}
// MARK: - Table View
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return objects.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! UITableViewCell
let object = objects[indexPath.row] as! NSDate
cell.textLabel!.text = object.description
return cell
}
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
objects.removeAtIndex(indexPath.row)
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
} else if editingStyle == .Insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view.
}
}
}
| gpl-2.0 | f6081d9c47eba49b128d2f0a4d77b8fe | 36.814433 | 157 | 0.685932 | 5.686822 | false | false | false | false |
gnachman/iTerm2 | BetterFontPicker/BetterFontPicker/SizePickerView.swift | 2 | 4292 | //
// SizePickerView.swift
// BetterFontPicker
//
// Created by George Nachman on 4/8/19.
// Copyright © 2019 George Nachman. All rights reserved.
//
import Cocoa
@objc(BFPSizePickerViewDelegate)
public protocol SizePickerViewDelegate: NSObjectProtocol {
func sizePickerView(_ sizePickerView: SizePickerView,
didChangeSizeTo size: Double)
}
@objc(BFPSizePickerView)
public class SizePickerView: NSView, NSTextFieldDelegate {
@objc public weak var delegate: SizePickerViewDelegate?
private var internalSize = 12.0
@objc public var size: Double {
set {
internalSet(newValue, withSideEffects: false, updateTextField: true)
}
get {
return internalSize
}
}
public override var fittingSize: NSSize {
return NSSize(width: 54.0, height: 27.0)
}
@objc public let textField = NSTextField()
let stepper = NSStepper()
@objc
public func clamp(min: Int, max: Int) {
stepper.minValue = Double(min)
stepper.maxValue = Double(max)
}
public override init(frame frameRect: NSRect) {
super.init(frame: frameRect)
postInit()
}
public required init?(coder decoder: NSCoder) {
super.init(coder: decoder)
postInit()
}
private func postInit() {
addSubview(textField)
textField.delegate = self
textField.isEditable = true
textField.isSelectable = true
textField.usesSingleLineMode = true
textField.doubleValue = size
stepper.doubleValue = size
addSubview(stepper)
stepper.target = self
stepper.action = #selector(stepper(_:))
stepper.valueWraps = false
layoutSubviews()
}
private func internalSet(_ newValue: Double,
withSideEffects: Bool,
updateTextField: Bool) {
if newValue <= 0 {
return
}
if newValue == internalSize {
return
}
internalSize = newValue
if updateTextField {
textField.stringValue = String(format: "%g", newValue)
}
stepper.doubleValue = internalSize
if withSideEffects {
delegate?.sizePickerView(self, didChangeSizeTo: internalSize)
}
}
private func layoutSubviews() {
textField.sizeToFit()
stepper.sizeToFit()
let margin = CGFloat(0)
let stepperHeight = stepper.frame.size.height
stepper.frame = CGRect(x: NSMaxX(bounds) - stepper.frame.size.width,
y: 0,
width: stepper.frame.size.width,
height: stepperHeight)
let textFieldHeight = CGFloat(21)
textField.frame = CGRect(x: 0,
y: (stepperHeight - textFieldHeight) / 2,
width: bounds.size.width - NSWidth(stepper.frame) - margin,
height: textFieldHeight)
}
public override func resizeSubviews(withOldSize oldSize: NSSize) {
layoutSubviews()
}
@objc(stepper:)
public func stepper(_ sender: Any?) {
let stepper = sender as! NSStepper
if stepper.doubleValue < 1 {
stepper.doubleValue = 1
}
internalSet(stepper.doubleValue, withSideEffects: true, updateTextField: true)
}
public func controlTextDidEndEditing(_ obj: Notification) {
let value = min(stepper.maxValue, max(stepper.minValue, textField.doubleValue))
textField.doubleValue = value
if value > 0 {
internalSet(value, withSideEffects: true, updateTextField: true)
} else {
textField.doubleValue = internalSize
}
}
public func controlTextDidChange(_ obj: Notification) {
let value = textField.doubleValue
if value > 0 {
// Notify client only if the value is in the legal range. Otherwise let the user edit
// in peace until they end editing.
internalSet(value,
withSideEffects: value >= stepper.minValue && value <= stepper.maxValue,
updateTextField: false)
}
}
}
| gpl-2.0 | 37d0f01d31dc8ec01e6058aea4bbb4c7 | 30.785185 | 97 | 0.588208 | 4.98374 | false | false | false | false |
kstaring/swift | benchmark/single-source/NSDictionaryCastToSwift.swift | 4 | 1168 | //===--- NSDictionaryCastToSwift.swift ------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
// Performance benchmark for casting NSDictionary to Swift Dictionary
// rdar://problem/18539730
//
// Description:
// Create an NSDictionary instance and cast it to [String: NSObject].
import Foundation
import TestsUtils
@inline(never)
public func run_NSDictionaryCastToSwift(_ N: Int) {
let NSDict = NSDictionary()
var swiftDict = [String: NSObject]()
for _ in 1...10000*N {
swiftDict = NSDict as! [String: NSObject]
if !swiftDict.isEmpty {
break
}
}
CheckResults(swiftDict.isEmpty,
"Incorrect result in swiftDict.isEmpty: " +
"\(swiftDict.isEmpty) != true\n")
}
| apache-2.0 | 4f076263ed340a4577560579524d6035 | 33.352941 | 80 | 0.609589 | 4.616601 | false | false | false | false |
wikimedia/wikipedia-ios | Wikipedia/Code/ColumnarCollectionViewLayoutManager.swift | 1 | 3823 | import UIKit
class ColumnarCollectionViewLayoutManager {
private var placeholders: [String:UICollectionReusableView] = [:]
weak var view: UIView!
weak var collectionView: UICollectionView!
required init(view: UIView, collectionView: UICollectionView) {
self.view = view
self.collectionView = collectionView
}
// MARK: - Cell & View Registration
final private func placeholderForIdentifier(_ identifier: String) -> UICollectionReusableView? {
let view = placeholders[identifier]
view?.prepareForReuse()
return view
}
final public func placeholder(forCellWithReuseIdentifier identifier: String) -> UICollectionViewCell? {
return placeholderForIdentifier(identifier) as? UICollectionViewCell
}
final public func placeholder(forSupplementaryViewOfKind elementKind: String, withReuseIdentifier identifier: String) -> UICollectionReusableView? {
return placeholderForIdentifier("\(elementKind)-\(identifier)")
}
@objc(registerCellClass:forCellWithReuseIdentifier:addPlaceholder:)
final func register(_ cellClass: Swift.AnyClass?, forCellWithReuseIdentifier identifier: String, addPlaceholder: Bool) {
collectionView.register(cellClass, forCellWithReuseIdentifier: identifier)
guard addPlaceholder else {
return
}
guard let cellClass = cellClass as? UICollectionViewCell.Type else {
return
}
let cell = cellClass.init(frame: view.bounds)
cell.isHidden = true
view.insertSubview(cell, at: 0) // so that the trait collections are updated
placeholders[identifier] = cell
}
@objc(registerNib:forCellWithReuseIdentifier:)
final func register(_ nib: UINib?, forCellWithReuseIdentifier identifier: String) {
collectionView.register(nib, forCellWithReuseIdentifier: identifier)
guard let cell = nib?.instantiate(withOwner: nil, options: nil).first as? UICollectionViewCell else {
return
}
cell.isHidden = true
view.insertSubview(cell, at: 0) // so that the trait collections are updated
placeholders[identifier] = cell
}
@objc(registerViewClass:forSupplementaryViewOfKind:withReuseIdentifier:addPlaceholder:)
final func register(_ viewClass: Swift.AnyClass?, forSupplementaryViewOfKind elementKind: String, withReuseIdentifier identifier: String, addPlaceholder: Bool) {
collectionView.register(viewClass, forSupplementaryViewOfKind: elementKind, withReuseIdentifier: identifier)
guard addPlaceholder else {
return
}
guard let viewClass = viewClass as? UICollectionReusableView.Type else {
return
}
let reusableView = viewClass.init(frame: view.bounds)
reusableView.isHidden = true
view.insertSubview(reusableView, at: 0) // so that the trait collections are updated
placeholders["\(elementKind)-\(identifier)"] = reusableView
}
@objc(registerNib:forSupplementaryViewOfKind:withReuseIdentifier:addPlaceholder:)
final func register(_ nib: UINib?, forSupplementaryViewOfKind elementKind: String, withReuseIdentifier identifier: String, addPlaceholder: Bool) {
collectionView.register(nib, forSupplementaryViewOfKind: elementKind, withReuseIdentifier: identifier)
guard addPlaceholder else {
return
}
guard let reusableView = nib?.instantiate(withOwner: nil, options: nil).first as? UICollectionReusableView else {
return
}
reusableView.isHidden = true
view.insertSubview(reusableView, at: 0) // so that the trait collections are updated
placeholders["\(elementKind)-\(identifier)"] = reusableView
}
}
| mit | af53a53232a4f392fdc5c598a9a39528 | 44.511905 | 165 | 0.702851 | 6.011006 | false | false | false | false |
Donny8028/Swift-TinyFeatures | Simple Stop Watch/Project 1 - Simple Stop Watch/ViewController.swift | 1 | 4530 | //
// ViewController.swift
// Project 1 - Simple Stop Watch
//
// Created by 賢瑭 何 on 2016/5/10.
// Copyright © 2016年 Donny. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var timer: UILabel!
@IBOutlet weak var secondTimer: UILabel!
private var currentTime: NSTimeInterval?
private var startWithTimer: NSTimer?
private var stopTime: String?
private var secondStopTime: String?
private var newStopTime: String?
private var newSecondTime: String?
private var timerStatus = false
private var forOneTime = false
private var buttonSecure = false
@IBOutlet weak var start: UIButton!
@IBOutlet weak var pause: UIButton!
@IBAction func reset() {
timer.text = "00"
secondTimer.text = "00"
startWithTimer?.invalidate()
timerStatus = false
start.enabled = !buttonSecure
pause.enabled = buttonSecure
}
@IBAction func startTimer() {
startWithTimer = NSTimer.scheduledTimerWithTimeInterval(0.01, target: self, selector: #selector(self.updateTimer), userInfo: nil, repeats: true)
currentTime = NSDate.timeIntervalSinceReferenceDate()
forOneTime = true
start.enabled = buttonSecure
pause.enabled = !buttonSecure
}
@IBAction func stopTimer() {
if startWithTimer?.valid == true {
startWithTimer?.invalidate()
timerStatus = true
start.enabled = !buttonSecure
pause.enabled = buttonSecure
if newStopTime != nil {
stopTime = newStopTime!
}
if newSecondTime != nil {
secondStopTime = newSecondTime
}
}
}
var plusMillisecond:UInt?
var plusSecond:UInt?
func updateTimer() {
let fromCurrentTime = NSDate.timeIntervalSinceReferenceDate()
var timePassed = fromCurrentTime - currentTime!
let second = UInt(timePassed)
timePassed -= NSTimeInterval(second)
let millisecond = UInt(timePassed * 100)
if !timerStatus {
let secondText = String(format: "%02d", second)
let millisecondText = String(format: "%02d", millisecond)
timer.text = "\(secondText)"
stopTime = timer.text
secondTimer.text = "\(millisecondText)"
secondStopTime = secondTimer.text
}else {
if forOneTime { //Grab the data one time
plusSecond = UInt(stopTime!)
plusMillisecond = UInt(secondStopTime!)
}
if plusSecond != nil && plusMillisecond != nil {
plusMillisecond! += 1
let secondText = String(format: "%02d", plusSecond!)
let millisecondText = String(format: "%02d", plusMillisecond!)
newStopTime = "\(secondText)"
newSecondTime = "\(millisecondText)"
timer.text = newStopTime
secondTimer.text = newSecondTime
forOneTime = false
if plusMillisecond == 99 {
plusMillisecond = 0
plusSecond! += 1
}
}
}
if timer.text == "60" {
startWithTimer?.invalidate()
timer.text = "00"
secondTimer.text = "00"
stopTime = nil
timerStatus = false
let timeUpAlert = UIAlertController(title: "Time's up", message: "", preferredStyle: .Alert)
let alert = UIAlertAction(title: "OK", style: .Default, handler: { action in
self.start.enabled = !self.buttonSecure
self.pause.enabled = self.buttonSecure
})
timeUpAlert.addAction(alert)
presentViewController(timeUpAlert, animated: true, completion: nil)
}
}
override func viewDidLoad() {
super.viewDidLoad()
timer.text = "00"
secondTimer.text = "00"
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func preferredStatusBarStyle() -> UIStatusBarStyle {
return UIStatusBarStyle.LightContent
//Only for black background usage.
}
}
| mit | edfbce29ebbf9766aded99a170c6f6cd | 32.488889 | 152 | 0.564256 | 5.24478 | false | false | false | false |
remlostime/one | one/one/Views/FollowViewCell.swift | 1 | 4851 | //
// FollowViewCell.swift
// one
//
// Created by Kai Chen on 12/24/16.
// Copyright © 2016 Kai Chen. All rights reserved.
//
import UIKit
import Parse
import QuartzCore
enum FollowState: Int {
case following = 0
case notFollowing
}
class FollowViewCell: UITableViewCell {
@IBOutlet weak var profielImageView: UIImageView!
@IBOutlet weak var usernameLabel: UILabel!
@IBOutlet weak var followingButton: UIButton!
let currentUsername = (PFUser.current()?.username)!
// MARK: Lifecycle
override func awakeFromNib() {
super.awakeFromNib()
followingButton.layer.cornerRadius = 3
followingButton.clipsToBounds = true
followingButton.contentEdgeInsets = UIEdgeInsets(top: 5, left: 10, bottom: 5, right: 10)
}
// MARK: Actions
@IBAction func followingButtonTapped(_ sender: UIButton) {
let title = sender.title(for: .normal)
if title == FollowUI.followButtonText.rawValue {
configure(withState: .following)
let object = PFObject(className: Follow.modelName.rawValue)
object[Follow.follower.rawValue] = currentUsername
object[Follow.following.rawValue] = usernameLabel.text!
object.saveInBackground(block: { [weak self](success: Bool, error: Error?) in
guard let strongSelf = self else {
return
}
if !success {
strongSelf.configure(withState: .notFollowing)
// TODO: pop an error message
print("error:\(error?.localizedDescription)")
}
})
let notificationObject = PFObject(className: Notifications.modelName.rawValue)
notificationObject[Notifications.sender.rawValue] = currentUsername
notificationObject[Notifications.receiver.rawValue] = usernameLabel.text!
notificationObject[Notifications.action.rawValue] = NotificationsAction.follow.rawValue
notificationObject.saveEventually()
} else {
configure(withState: .notFollowing)
let query = PFQuery(className: Follow.modelName.rawValue)
query.whereKey(Follow.follower.rawValue, equalTo: currentUsername)
let followingUsername = usernameLabel.text!
query.whereKey(Follow.following.rawValue, equalTo: followingUsername)
query.findObjectsInBackground(block: { [weak self](objects: [PFObject]?, error: Error?) in
guard let strongSelf = self else {
return
}
if error == nil {
for object in objects! {
object.deleteInBackground(block: { (success: Bool, error: Error?) in
if !success {
strongSelf.configure(withState: .following)
print("error:\(error?.localizedDescription)")
}
})
}
} else {
strongSelf.followingButton.setTitle(FollowUI.followingButtonText.rawValue, for: .normal)
strongSelf.followingButton.backgroundColor = .white
print("error:\(error?.localizedDescription)")
}
})
let notificationQuery = PFQuery(className: Notifications.modelName.rawValue)
notificationQuery.whereKey(Notifications.sender.rawValue, equalTo: currentUsername)
notificationQuery.whereKey(Notifications.receiver.rawValue, equalTo: usernameLabel.text!)
notificationQuery.whereKey(Notifications.action.rawValue, equalTo: NotificationsAction.follow.rawValue)
notificationQuery.findObjectsInBackground(block: { (objects: [PFObject]?, error: Error?) in
for object in objects! {
object.deleteEventually()
}
})
}
}
// MARK: Helpers
func configure(withState state: FollowState) {
switch state {
case .following:
followingButton.setTitle(FollowUI.followingButtonText.rawValue, for: .normal)
followingButton.setTitleColor(.black, for: .normal)
followingButton.layer.borderWidth = 1
followingButton.layer.borderColor = UIColor.gray.cgColor
followingButton.backgroundColor = .white
case .notFollowing:
followingButton.setTitle(FollowUI.followButtonText.rawValue, for: .normal)
followingButton.setTitleColor(.white, for: .normal)
followingButton.layer.borderWidth = 0
followingButton.setTitleColor(.white, for: .normal)
followingButton.backgroundColor = .followButtonLightBlue
}
}
}
| gpl-3.0 | 4fe74da5c91e3338a2a6679d92ac4bd0 | 39.082645 | 115 | 0.609278 | 5.461712 | false | false | false | false |
blochberger/swift-sodium | Sodium/Sodium.swift | 2 | 798 | import Foundation
import Clibsodium
public struct Sodium {
public let box = Box()
public let secretBox = SecretBox()
public let genericHash = GenericHash()
public let pwHash = PWHash()
public let randomBytes = RandomBytes()
public let shortHash = ShortHash()
public let sign = Sign()
public let utils = Utils()
public let keyExchange = KeyExchange()
public let auth = Auth()
public let stream = Stream()
public let keyDerivation = KeyDerivation()
public let secretStream = SecretStream()
public let aead = Aead()
public init() {
_ = Sodium.once
}
}
extension Sodium {
private static let once: Void = {
guard sodium_init() >= 0 else {
fatalError("Failed to initialize libsodium")
}
}()
}
| isc | 7a75625b0d6bd8ebec263888438bb0d4 | 24.741935 | 56 | 0.636591 | 4.050761 | false | false | false | false |
mownier/photostream | Photostream/UI/User Timeline/UserTimelineControl.swift | 1 | 3366 | //
// UserTimelineControl.swift
// Photostream
//
// Created by Mounir Ybanez on 12/12/2016.
// Copyright © 2016 Mounir Ybanez. All rights reserved.
//
import UIKit
protocol UserTimelineControlDelegate: class {
func didSelectGrid()
func didSelectList()
func didSelectLiked()
}
@objc protocol UserTimelineControlAction: class {
func didTapGrid()
func didTapList()
func didTapLiked()
}
class UserTimelineControl: UIView {
weak var delegate: UserTimelineControlDelegate?
var gridButton: UIButton!
var listButton: UIButton!
var likedButton: UIButton!
var stripTopView: UIView!
var stripBottomView: UIView!
override init(frame: CGRect) {
super.init(frame: frame)
initSetup()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
initSetup()
}
override func layoutSubviews() {
var rect = CGRect.zero
rect.size.width = frame.width
rect.size.height = 1
stripTopView.frame = rect
rect.origin.y = rect.maxY
rect.size.width = frame.width / 3
rect.size.height = 48
gridButton.frame = rect
rect.origin.x = rect.maxX
listButton.frame = rect
rect.origin.x = rect.maxX
likedButton.frame = rect
rect.origin.x = 0
rect.origin.y = rect.maxY
rect.size.width = frame.width
rect.size.height = 1
stripBottomView.frame = rect
}
func initSetup() {
gridButton = UIButton()
gridButton.setImage(#imageLiteral(resourceName: "grid_icon"), for: .normal)
gridButton.setImage(#imageLiteral(resourceName: "grid_icon_selected"), for: .selected)
gridButton.addTarget(self, action: #selector(self.didTapGrid), for: .touchUpInside)
gridButton.isSelected = true
listButton = UIButton()
listButton.setImage(#imageLiteral(resourceName: "list_icon"), for: .normal)
listButton.setImage(#imageLiteral(resourceName: "list_icon_selected"), for: .selected)
listButton.addTarget(self, action: #selector(self.didTapList), for: .touchUpInside)
likedButton = UIButton()
likedButton.setImage(#imageLiteral(resourceName: "timeline_likes_icon"), for: .normal)
likedButton.addTarget(self, action: #selector(self.didTapLiked), for: .touchUpInside)
likedButton.tintColor = gridButton.tintColor
stripTopView = UIView()
stripTopView.backgroundColor = UIColor(red: 223/255, green: 223/255, blue: 223/255, alpha: 1)
stripBottomView = UIView()
stripBottomView.backgroundColor = stripTopView.backgroundColor
addSubview(gridButton)
addSubview(listButton)
addSubview(likedButton)
addSubview(stripTopView)
addSubview(stripBottomView)
}
}
extension UserTimelineControl: UserTimelineControlAction {
func didTapGrid() {
gridButton.isSelected = true
listButton.isSelected = false
delegate?.didSelectGrid()
}
func didTapList() {
gridButton.isSelected = false
listButton.isSelected = true
delegate?.didSelectList()
}
func didTapLiked() {
delegate?.didSelectLiked()
}
}
| mit | a8ab359af71833aa559a94d4bdd1fb20 | 27.516949 | 101 | 0.633581 | 4.641379 | false | false | false | false |
usbong/UsbongKit | UsbongKit/Usbong/XML/XMLNameInfo.swift | 2 | 7309 | //
// XMLNameInfo.swift
// UsbongKit
//
// Created by Chris Amanse on 12/31/15.
// Copyright © 2015 Usbong Social Systems, Inc. All rights reserved.
//
import Foundation
/// Decomposes a task node name into components
internal struct XMLNameInfo {
/// Background image identifier
static let backgroundImageIdentifier = "bg"
/// Background audio identifier
static let backgroundAudioIdentifier = "bgAudioName"
/// Audio identifier
static let audioIdentifier = "audioName"
/// Supported image formats
static let supportedImageFormats = ["jpg", "jpeg", "png", "gif", "bmp", "tiff", "tif", "ico", "cur", "BMPf", "xbm"]
/// Components of string (separated by "~")
let components: [String]
/// Target language
let language: String
/// Tree root URL. Used for getting resources.
let treeRootURL: URL
/// Creates an `XMLNameInfo` from `name`, `language`, and `treeRootURL`
init(name: String, language: String, treeRootURL: URL) {
self.components = name.components(separatedBy: "~")
self.language = language
self.treeRootURL = treeRootURL
}
/// The type identifier for the task node. It is usually the first component. For `classification` type task node, there is no type identifier.
var typeIdentifier: String {
if components.count > 1 {
return components.first ?? ""
} else {
// Only one component, probably classification
return "classification"
}
}
/// The `TaskNodeType`, which is based on the type identifier
var type: TaskNodeType? {
return TaskNodeType(rawValue: typeIdentifier)
}
/// The text for the task node
var text: String {
return components.last ?? ""
}
/// The image file name
var imageFileName: String? {
guard components.count >= 2 else {
return nil
}
return components[1]
}
/// The target number of choices
var targetNumberOfChoices: Int {
guard TaskNodeType(rawValue: typeIdentifier) == .Checklist && components.count >= 2 else {
return 0
}
return NSString(string: components[1]).integerValue
}
/// The URL for the image
var imageURL: URL? {
// Make sure imageFileName is nil, else, return nil
guard let fileName = imageFileName else {
return nil
}
let resURL = treeRootURL.appendingPathComponent("res")
let imageURLWithoutExtension = resURL.appendingPathComponent(fileName)
// Check for images with supported image formats
let fileManager = FileManager.default
let supportedImageFormats = XMLNameInfo.supportedImageFormats
for format in supportedImageFormats {
let url = imageURLWithoutExtension.appendingPathExtension(format)
if fileManager.fileExists(atPath: url.path) {
return url
}
}
return nil
}
/// The image object
var image: UIImage? {
guard let path = imageURL?.path else {
return nil
}
return UIImage(contentsOfFile: path)
}
// MARK: Fetch value of identifier
/// Get the value for an identifier
func valueOfIdentifer(_ identifier: String) -> String? {
for component in components {
if component.hasPrefix(identifier) {
let endIndex = component.characters.index(component.startIndex, offsetBy: identifier.characters.count)
return component.substring(from: endIndex)
}
}
return nil
}
// MARK: Background image
/// The file name for the background image
var backgroundImageFileName: String {
let fullIdentifier = "@" + XMLNameInfo.backgroundImageIdentifier + "="
return valueOfIdentifer(fullIdentifier) ?? "bg"
}
/// The background image URL
var backgroundImageURL: URL? {
let resURL = treeRootURL.appendingPathComponent("res")
// Check for images with supported image formats
let fileManager = FileManager.default
guard let contents = try? fileManager.contentsOfDirectory(at: resURL,
includingPropertiesForKeys: nil, options: .skipsSubdirectoryDescendants) else {
return nil
}
for content in contents {
let fileName = content.deletingPathExtension().lastPathComponent
if fileName.compare(backgroundImageFileName, options: .caseInsensitive,
range: nil, locale: nil) == .orderedSame {
return content
}
}
return nil
}
// MARK: Background audio
/// The file name for the background audio
var backgroundAudioFileName: String? {
let fullIdentifier = "@" + XMLNameInfo.backgroundAudioIdentifier + "="
return valueOfIdentifer(fullIdentifier)
}
/// The URL for the background audio
var backgroundAudioURL: URL? {
let audioURL = treeRootURL.appendingPathComponent("audio")
let targetFileName = backgroundAudioFileName ?? ""
// Finds files in audio/ with file name same to backgroundAudioFileName
if let contents = try? FileManager.default.contentsOfDirectory(at: audioURL,
includingPropertiesForKeys: nil, options: .skipsSubdirectoryDescendants) {
for content in contents {
let fileName = content.deletingPathExtension().lastPathComponent
if fileName.compare(targetFileName, options: .caseInsensitive,
range: nil, locale: nil) == .orderedSame {
return content
}
}
}
return nil
}
// MARK: Audio
/// The file name for the audio
var audioFileName: String? {
let fullIdentifier = "@" + XMLNameInfo.audioIdentifier + "="
return valueOfIdentifer(fullIdentifier)
}
/// The URL for the audio
var audioURL: URL? {
let audioURL = treeRootURL.appendingPathComponent("audio")
let audioLanguageURL = audioURL.appendingPathComponent(language)
let targetFileName = audioFileName ?? ""
// Find files in audio/{language} with file name same to audioFileName
if let contents = try? FileManager.default.contentsOfDirectory(at: audioLanguageURL,
includingPropertiesForKeys: nil, options: .skipsSubdirectoryDescendants) {
for content in contents {
let fileName = content.deletingPathExtension().lastPathComponent
if fileName.compare(targetFileName, options: .caseInsensitive,
range: nil, locale: nil) == .orderedSame {
return content
}
}
}
return nil
}
// MARK: TextField
/// The unit for a text field
var unit: String? {
guard components.count >= 2 else {
return nil
}
return components[1]
}
}
| apache-2.0 | 4892518ab849ecd1495f4cb46f4ef606 | 32.369863 | 147 | 0.598522 | 5.405325 | false | false | false | false |
angelvasa/AVXCAssets-Generator | AVXCAssetsGenerator/AVAssetCatalogCreator/FolderGenerator.swift | 1 | 2405 | //
// FolderGenerator.swift
// AVXCAssetsGenerator
//
// Created by Angel Vasa on 23/04/16.
// Copyright © 2016 Angel Vasa. All rights reserved.
//
import Foundation
import Cocoa
class FolderGenerator: AnyObject {
func generateFolders(atLocation destinationLocation:String, originLocation origin: String, withContents folderContent: [String]) -> Bool {
let xcAssetPath = destinationLocation + "/" + "Assets.xcassets"
let contentCreator = ContentCreator()
do {
try NSFileManager.defaultManager().createDirectoryAtPath(xcAssetPath, withIntermediateDirectories: true, attributes: nil)
contentCreator.writeDictionaryContent(contentCreator.defaultXcassetDictionary(), atPath: xcAssetPath)
} catch let error as NSError {
print(error.localizedDescription)
}
for image in folderContent {
if image == ".DS_Store" { /*ignore that file*/ } else {
let imageSet = image.removeExtension()
let imagePath = origin + "/" + image
if imageSet == "Icon" || imageSet == "icon" {
guard let isImage = NSImage(contentsOfFile: imagePath) else {
continue
}
let appIconPath = xcAssetPath + "/" + "AppIcon.appiconset"
do {
try NSFileManager.defaultManager().createDirectoryAtPath(appIconPath, withIntermediateDirectories: true, attributes: nil)
AVIconScalar().scaleImage(isImage, withImageName: imageSet, andSaveAtPath: appIconPath)
} catch {
}
} else {
guard let isImage = NSImage(contentsOfFile: imagePath) else {
continue
}
let imageSetPath = xcAssetPath + "/" + imageSet + ".imageset"
do {
try NSFileManager.defaultManager().createDirectoryAtPath(imageSetPath, withIntermediateDirectories: true, attributes: nil)
AVImageScalar().scaleImage(isImage, withImageName: imageSet, andSaveAtPath: imageSetPath)
} catch {
}
}
}
}
return true
}
} | mit | 46c9345241ad0e3483020dc99f9dc43e | 36 | 146 | 0.552413 | 5.778846 | false | false | false | false |
ekgorter/MyWikiTravel | MyWikiTravel/MyWikiTravel/CoreData.swift | 1 | 2873 | //
// CoreData.swift
// MyWikiTravel
//
// Created by Elias Gorter on 25-06-15.
// Copyright (c) 2015 EliasGorter6052274. All rights reserved.
//
// All Core Data functionality used in app is defined here.
import Foundation
import UIKit
import CoreData
class CoreData {
let managedObjectContext = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext
// Retrieve all existing guides from Core Data.
func fetchGuides() -> [Guide] {
var guides = [Guide]()
let fetchRequest = NSFetchRequest(entityName: "Guide")
let sortDescriptor = NSSortDescriptor(key: "title", ascending: true)
fetchRequest.sortDescriptors = [sortDescriptor]
if let fetchResults = managedObjectContext!.executeFetchRequest(fetchRequest, error: nil) as? [Guide] {
guides = fetchResults
}
return guides
}
// Retrieves the selected guide from Core Data.
func fetchGuide(title: String) -> [Guide] {
var guide = [Guide]()
let fetchRequest = NSFetchRequest(entityName: "Guide")
let sortDescriptor = NSSortDescriptor(key: "title", ascending: true)
let predicate = NSPredicate(format: "title == %@", title)
fetchRequest.sortDescriptors = [sortDescriptor]
fetchRequest.predicate = predicate
if let fetchResults = managedObjectContext!.executeFetchRequest(fetchRequest, error: nil) as? [Guide] {
guide = fetchResults
}
return guide
}
// Retrieves the articles belonging to this guide from Core Data.
func fetchArticles(guide: [Guide]) -> [Article] {
var articles = [Article]()
for article in guide[0].guideContent.allObjects as! [Article] {
articles.append(article)
}
return articles
}
// Creates a new Guide entity.
func createNewGuide(title: String) -> Guide {
let newGuide = Guide.createInManagedObjectContext(self.managedObjectContext!, title: title)
return newGuide
}
// Creates a new Article entity
func createNewArticle(title: String, text: String, image: NSData, guide: Guide) {
Article.createInManagedObjectContext(self.managedObjectContext!, title: title, text: text, image: image, guide: guide)
}
// Saves data to Core Data.
func save() {
var error : NSError?
if(managedObjectContext!.save(&error) ) {
println(error?.localizedDescription)
}
}
// Deletes guide from Core Data.
func delete(objectToDelete: Guide) {
managedObjectContext?.deleteObject(objectToDelete)
}
// Deletes article from Core Data.
func delete(objectToDelete: Article) {
managedObjectContext?.deleteObject(objectToDelete)
}
}
| unlicense | a43827b5ccd2fd090788517cc700564c | 31.647727 | 126 | 0.641838 | 5.031524 | false | false | false | false |
sharath-cliqz/browser-ios | Sync/KeyBundle.swift | 2 | 10471 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
import Shared
import FxA
import Account
import SwiftyJSON
private let KeyLength = 32
open class KeyBundle: Hashable {
let encKey: Data
let hmacKey: Data
open class func fromKB(_ kB: Data) -> KeyBundle {
let salt = Data()
let contextInfo = FxAClient10.KW("oldsync")
let len: UInt = 64 // KeyLength + KeyLength, without type nonsense.
let derived = (kB as NSData).deriveHKDFSHA256Key(withSalt: salt, contextInfo: contextInfo, length: len)!
return KeyBundle(encKey: derived.subdata(in: 0..<KeyLength),
hmacKey: derived.subdata(in: KeyLength..<(2 * KeyLength)))
}
open class func random() -> KeyBundle {
// Bytes.generateRandomBytes uses SecRandomCopyBytes, which hits /dev/random, which
// on iOS is populated by the OS from kernel-level sources of entropy.
// That should mean that we don't need to seed or initialize anything before calling
// this. That is probably not true on (some versions of) OS X.
return KeyBundle(encKey: Bytes.generateRandomBytes(32), hmacKey: Bytes.generateRandomBytes(32))
}
open class var invalid: KeyBundle {
return KeyBundle(encKeyB64: "deadbeef", hmacKeyB64: "deadbeef")
}
public init(encKeyB64: String, hmacKeyB64: String) {
self.encKey = Bytes.decodeBase64(encKeyB64)
self.hmacKey = Bytes.decodeBase64(hmacKeyB64)
}
public init(encKey: Data, hmacKey: Data) {
self.encKey = encKey
self.hmacKey = hmacKey
}
fileprivate func _hmac(_ ciphertext: Data) -> (data: UnsafeMutablePointer<CUnsignedChar>, len: Int) {
let hmacAlgorithm = CCHmacAlgorithm(kCCHmacAlgSHA256)
let digestLen: Int = Int(CC_SHA256_DIGEST_LENGTH)
let result = UnsafeMutablePointer<CUnsignedChar>.allocate(capacity: digestLen)
CCHmac(hmacAlgorithm, hmacKey.getBytes(), hmacKey.count, ciphertext.getBytes(), ciphertext.count, result)
return (result, digestLen)
}
open func hmac(_ ciphertext: Data) -> Data {
let (result, digestLen) = _hmac(ciphertext)
let data = NSMutableData(bytes: result, length: digestLen)
result.deinitialize()
return data as Data
}
/**
* Returns a hex string for the HMAC.
*/
open func hmacString(_ ciphertext: Data) -> String {
let (result, digestLen) = _hmac(ciphertext)
let hash = NSMutableString()
for i in 0..<digestLen {
hash.appendFormat("%02x", result[i])
}
result.deinitialize()
return String(hash)
}
open func encrypt(_ cleartext: Data, iv: Data?=nil) -> (ciphertext: Data, iv: Data)? {
let iv = iv ?? Bytes.generateRandomBytes(16)
let (success, b, copied) = self.crypt(cleartext, iv: iv, op: CCOperation(kCCEncrypt))
let byteCount = cleartext.count + kCCBlockSizeAES128
if success == CCCryptorStatus(kCCSuccess) {
// Hooray!
let d = Data(bytes: b, count: Int(copied))
b.deallocate(bytes: byteCount, alignedTo: MemoryLayout<Void>.size)
return (d, iv)
}
b.deallocate(bytes: byteCount, alignedTo: MemoryLayout<Void>.size)
return nil
}
// You *must* verify HMAC before calling this.
open func decrypt(_ ciphertext: Data, iv: Data) -> String? {
let (success, b, copied) = self.crypt(ciphertext, iv: iv, op: CCOperation(kCCDecrypt))
let byteCount = ciphertext.count + kCCBlockSizeAES128
if success == CCCryptorStatus(kCCSuccess) {
// Hooray!
let d = Data(bytes: b, count: Int(copied))
let s = NSString(data: d, encoding: String.Encoding.utf8.rawValue)
b.deallocate(bytes: byteCount, alignedTo: MemoryLayout<Void>.size)
return s as String?
}
b.deallocate(bytes: byteCount, alignedTo: MemoryLayout<Void>.size)
return nil
}
fileprivate func crypt(_ input: Data, iv: Data, op: CCOperation) -> (status: CCCryptorStatus, buffer: UnsafeMutableRawPointer, count: Int) {
let resultSize = input.count + kCCBlockSizeAES128
let result = UnsafeMutableRawPointer.allocate(bytes: resultSize, alignedTo: MemoryLayout<Void>.size)
var copied: Int = 0
let success: CCCryptorStatus =
CCCrypt(op,
CCHmacAlgorithm(kCCAlgorithmAES128),
CCOptions(kCCOptionPKCS7Padding),
encKey.getBytes(),
kCCKeySizeAES256,
iv.getBytes(),
input.getBytes(),
input.count,
result,
resultSize,
&copied
);
return (success, result, copied)
}
open func verify(hmac: Data, ciphertextB64: Data) -> Bool {
let expectedHMAC = hmac
let computedHMAC = self.hmac(ciphertextB64)
return (expectedHMAC == computedHMAC)
}
/**
* Swift can't do functional factories. I would like to have one of the following
* approaches be viable:
*
* 1. Derive the constructor from the consumer of the factory.
* 2. Accept a type as input.
*
* Neither of these are viable, so we instead pass an explicit constructor closure.
*
* Most of these approaches produce either odd compiler errors, or -- worse --
* compile and then yield runtime EXC_BAD_ACCESS (see Radar 20230159).
*
* For this reason, be careful trying to simplify or improve this code.
*/
open func factory<T: CleartextPayloadJSON>(_ f: @escaping (JSON) -> T) -> (String) -> T? {
return { (payload: String) -> T? in
let potential = EncryptedJSON(json: payload, keyBundle: self)
if !(potential.isValid()) {
return nil
}
let cleartext = potential.cleartext
if (cleartext == nil) {
return nil
}
return f(cleartext!)
}
}
// TODO: how much do we want to move this into EncryptedJSON?
open func serializer<T: CleartextPayloadJSON>(_ f: @escaping (T) -> JSON) -> (Record<T>) -> JSON? {
return { (record: Record<T>) -> JSON? in
let json = f(record.payload)
let data = (json.rawString([writingOptionsKeys.castNilToNSNull: true]) ?? "").utf8EncodedData
// We pass a null IV, which means "generate me a new one".
// We then include the generated IV in the resulting record.
if let (ciphertext, iv) = self.encrypt(data, iv: nil) {
// So we have the encrypted payload. Now let's build the envelope around it.
let ciphertext = ciphertext.base64EncodedString
// The HMAC is computed over the base64 string. As bytes. Yes, I know.
if let encodedCiphertextBytes = ciphertext.data(using: String.Encoding.ascii, allowLossyConversion: false) {
let hmac = self.hmacString(encodedCiphertextBytes)
let iv = iv.base64EncodedString
// The payload is stringified JSON. Yes, I know.
let payload: Any = JSON(object: ["ciphertext": ciphertext, "IV": iv, "hmac": hmac]).stringValue()! as Any
let obj = ["id": record.id, "sortindex": record.sortindex, "ttl": record.ttl as Any, "payload": payload]
return JSON(object: obj)
}
}
return nil
}
}
open func asPair() -> [String] {
return [self.encKey.base64EncodedString, self.hmacKey.base64EncodedString]
}
open var hashValue: Int {
return "\(self.encKey.base64EncodedString) \(self.hmacKey.base64EncodedString)".hashValue
}
}
public func == (lhs: KeyBundle, rhs: KeyBundle) -> Bool {
return (lhs.encKey == rhs.encKey) &&
(lhs.hmacKey == rhs.hmacKey)
}
open class Keys: Equatable {
let valid: Bool
let defaultBundle: KeyBundle
var collectionKeys: [String: KeyBundle] = [String: KeyBundle]()
public init(defaultBundle: KeyBundle) {
self.defaultBundle = defaultBundle
self.valid = true
}
public init(payload: KeysPayload?) {
if let payload = payload, payload.isValid() {
if let keys = payload.defaultKeys {
self.defaultBundle = keys
self.collectionKeys = payload.collectionKeys
self.valid = true
return
}
}
self.defaultBundle = KeyBundle.invalid
self.valid = false
}
public convenience init(downloaded: EnvelopeJSON, master: KeyBundle) {
let f: (JSON) -> KeysPayload = { KeysPayload($0) }
let keysRecord = Record<KeysPayload>.fromEnvelope(downloaded, payloadFactory: master.factory(f))
self.init(payload: keysRecord?.payload)
}
open class func random() -> Keys {
return Keys(defaultBundle: KeyBundle.random())
}
open func forCollection(_ collection: String) -> KeyBundle {
if let bundle = collectionKeys[collection] {
return bundle
}
return defaultBundle
}
open func encrypter<T: CleartextPayloadJSON>(_ collection: String, encoder: RecordEncoder<T>) -> RecordEncrypter<T> {
return RecordEncrypter(bundle: forCollection(collection), encoder: encoder)
}
open func asPayload() -> KeysPayload {
let json: JSON = JSON([
"id": "keys",
"collection": "crypto",
"default": self.defaultBundle.asPair(),
"collections": mapValues(self.collectionKeys, f: { $0.asPair() })
])
return KeysPayload(json)
}
}
/**
* Yup, these are basically typed tuples.
*/
public struct RecordEncoder<T: CleartextPayloadJSON> {
let decode: (JSON) -> T
let encode: (T) -> JSON
}
public struct RecordEncrypter<T: CleartextPayloadJSON> {
let serializer: (Record<T>) -> JSON?
let factory: (String) -> T?
init(bundle: KeyBundle, encoder: RecordEncoder<T>) {
self.serializer = bundle.serializer(encoder.encode)
self.factory = bundle.factory(encoder.decode)
}
init(serializer: @escaping (Record<T>) -> JSON?, factory: @escaping (String) -> T?) {
self.serializer = serializer
self.factory = factory
}
}
public func ==(lhs: Keys, rhs: Keys) -> Bool {
return lhs.valid == rhs.valid &&
lhs.defaultBundle == rhs.defaultBundle &&
lhs.collectionKeys == rhs.collectionKeys
}
| mpl-2.0 | 336cd01ce646ee6f1d9eff5bf308c97f | 34.859589 | 144 | 0.630599 | 4.353846 | false | false | false | false |
TeamYYZ/DineApp | Dine/FriendsViewController.swift | 1 | 10149 | //
// FriendsViewController.swift
// Dine
//
// Created by you wu on 3/13/16.
// Copyright © 2016 YYZ. All rights reserved.
//
import UIKit
class FriendsViewController: UITableViewController {
weak var activityInProgress: Activity?
var isInvitationVC = false
var checked = [String: User]()
@IBOutlet weak var inviteButton: UIBarButtonItem!
//var friendsIdList = User.currentUser?.friendList
var friendsIdList = [String]()
var friendsUserList = [User]()
var friendsUserDict = [String : [User]]()
var friendScreenNameInitial = [String]()
let friendScreenNameInitialTable = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"]
func refreshControlAction(refreshControl: UIRefreshControl) {
fetchFriendList()
}
override func viewDidLoad() {
super.viewDidLoad()
self.navigationItem.backBarButtonItem = UIBarButtonItem(title: "", style: UIBarButtonItemStyle.Plain, target: nil, action: nil)
if isInvitationVC {
inviteButton.enabled = false
inviteButton.image = nil
inviteButton.title = "Invite"
inviteButton.tag = 0
}else{
inviteButton.enabled = true
inviteButton.tag = 1
}
tableView.dataSource = self
tableView.delegate = self
tableView.rowHeight = UITableViewAutomaticDimension
tableView.estimatedRowHeight = 120
refreshControl = UIRefreshControl()
refreshControl?.addTarget(self, action: #selector(FriendsViewController.refreshControlAction(_:)), forControlEvents: UIControlEvents.ValueChanged)
tableView.insertSubview(refreshControl!, atIndex: 0)
fetchFriendList()
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
if activityInProgress == nil {
self.setNavigationBarItem()
}
}
func fetchFriendList() {
User.currentUser?.getFriendsList({ (friendList: [String]?) -> () in
if let fetchedfriendList = friendList {
self.friendsIdList = fetchedfriendList
self.generateFriendDic()
self.checked = [String: User]()
self.refreshControl?.endRefreshing()
}
})
}
func generateFriendDic(){
let query = PFUser.query()
query?.whereKey("objectId", containedIn: friendsIdList)
query?.findObjectsInBackgroundWithBlock({ (friendObjects:[PFObject]?, error: NSError?) -> Void in
if error == nil && friendObjects != nil {
self.friendsUserList = [User]()
self.friendsUserDict = [String : [User]]()
for friendObject in friendObjects! {
let friend = User(pfUser: friendObject as! PFUser)
Log.info(friend.username)
self.friendsUserList.append(friend)
let username = friend.screenName
let usernameKey = username!.substringToIndex(username!.startIndex.advancedBy(1)).uppercaseString
if var usernameValues = self.friendsUserDict[usernameKey] {
usernameValues.append(friend)
self.friendsUserDict[usernameKey] = usernameValues
} else {
self.friendsUserDict[usernameKey] = [friend]
self.friendScreenNameInitial.append(usernameKey)
self.friendScreenNameInitial.sortInPlace()
}
}
self.tableView.reloadData()
} else {
print("Fail to get the friendList")
print(error)
}
})
}
override func sectionIndexTitlesForTableView(tableView: UITableView) -> [String]? {
return self.friendScreenNameInitialTable
}
override func tableView(tableView: UITableView, sectionForSectionIndexTitle title: String, atIndex index: Int) -> Int {
guard let index = self.friendScreenNameInitial.indexOf(title) else {
return -1
}
return index
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
tableView.deselectRowAtIndexPath(indexPath, animated: true)
let screenNameInitial = self.friendScreenNameInitial[indexPath.section]
let userListUnderGivenInitial = self.friendsUserDict[screenNameInitial]
let user = userListUnderGivenInitial![indexPath.row]
if isInvitationVC == true {
if let _ = checked[user.userId!] {
self.checked[user.userId!] = nil
} else {
self.checked[user.userId!] = user
}
if checked.count > 0 {
inviteButton.enabled = true
} else {
inviteButton.enabled = false
}
tableView.reloadRowsAtIndexPaths([indexPath], withRowAnimation: .Automatic)
} else {
performSegueWithIdentifier("toUserProfile", sender: indexPath)
}
}
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return friendsUserDict.count
}
override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return friendScreenNameInitial[section]
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
let usernameKey = self.friendScreenNameInitial[section]
if let usernameValues = self.friendsUserDict[usernameKey] {
return usernameValues.count
}
return 0
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("friendCell", forIndexPath: indexPath) as! FriendCell
let usernameKey = self.friendScreenNameInitial[indexPath.section]
if let usernameValues = self.friendsUserDict[usernameKey] {
let index = indexPath.row
let user = usernameValues[index]
if isInvitationVC == true {
if let _ = checked[user.userId!] {
cell.accessoryType = .Checkmark
cell.inviteLabel.text = "Invited"
cell.inviteLabel.textColor = UIColor.flatGrayColor()
} else {
cell.accessoryType = .None
cell.inviteLabel.text = "Invite"
cell.inviteLabel.textColor = UIColor.flatSkyBlueColor()
}
} else {
cell.inviteLabel.hidden = true
}
if let file = user.avatarImagePFFile {
file.getDataInBackgroundWithBlock({
(result, error) in
cell.avatarImage.image = UIImage(data: result!)
})
}else{
cell.avatarImage.image = UIImage(named: "User")
}
cell.userNameLabel.text = user.screenName
if cell.avatarImage.userInteractionEnabled == false {
cell.avatarImage.userInteractionEnabled = true
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(FriendsViewController.profileTap(_:)))
cell.avatarImage.addGestureRecognizer(tapGesture)
cell.avatarImage.layer.cornerRadius = 10.0
}
}
cell.selectionStyle = UITableViewCellSelectionStyle.None
return cell
}
func profileTap (sender: AnyObject) {
let position: CGPoint = sender.locationInView(self.tableView)
let indexPath: NSIndexPath = self.tableView.indexPathForRowAtPoint(position)!
performSegueWithIdentifier("toUserProfile", sender: indexPath)
}
override func tableView(tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
let headerView = view as! UITableViewHeaderFooterView
headerView.textLabel?.textColor = UIColor.orangeColor()
headerView.textLabel?.font = UIFont(name: "Avenir", size: 14.0)
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "toUserProfile"{
let indexPath = sender as! NSIndexPath
let vc = segue.destinationViewController as! UserProfileViewController
let section = indexPath.section
let row = indexPath.row
let title = self.friendScreenNameInitial[section]
vc.uid = self.friendsUserDict[title]![row].userId
}
else {
if let button = sender as? UIBarButtonItem {
if button.tag == 0 {
var invitedIdList = [GroupMember]()
for (_, user) in checked {
invitedIdList.append(GroupMember(user: user))
Log.info(user.username)
}
activityInProgress?.setupGroup(invitedIdList)
self.performSegueWithIdentifier("toMapViewSegue", sender: self)
}
}
}
}
}
| gpl-3.0 | d8a4410b4de1c425bd051047433315cf | 35.113879 | 170 | 0.565136 | 5.697923 | false | false | false | false |
haawa799/WaniKani-iOS | WaniTimie Extension/ExtensionDelegate.swift | 1 | 1312 | //
// ExtensionDelegate.swift
// WaniTimie Extension
//
// Created by Andriy K. on 2/18/16.
// Copyright © 2016 Andriy K. All rights reserved.
//
import WatchKit
import WatchConnectivity
import DataKitWatch
class ExtensionDelegate: NSObject, WKExtensionDelegate {
func applicationDidFinishLaunching() {
setupWatchConnectivity()
}
func setupWatchConnectivity() {
guard WCSession.isSupported() else { return }
let session = WCSession.defaultSession()
session.delegate = self
session.activateSession()
requestInitialInfoIfNeeded()
}
private func requestInitialInfoIfNeeded() {
let curLevel = dataManager.currentLevel?.kanji.first?.level ?? 0
let session = WCSession.defaultSession()
session.sendMessage([Communication.myLevel: curLevel], replyHandler: nil) { (error) -> Void in
print(error)
}
}
}
extension ExtensionDelegate: WCSessionDelegate {
func session(session: WCSession, didReceiveUserInfo userInfo: [String : AnyObject]) {
guard let updateData = userInfo[Communication.newCurrentLevelUpdate] as? NSData else { return }
guard let kanjiUpdate = KanjiUpdateObject.kanjiUpdateObjectFrom(updateData) else { return }
dataManager.updateCurrentLevelKanji(kanjiUpdate)
}
}
let dataManager = DataManager() | gpl-3.0 | 419563009234d7888e082413d9daa66f | 25.77551 | 99 | 0.73074 | 4.66548 | false | false | false | false |
Den-Ree/InstagramAPI | src/InstagramAPI/InstagramAPI/Instagram/Helpers/Instagram+AnyNetworkRouter.swift | 2 | 2240 | //
// InstagramNetworkManager.swift
// ConceptOffice
//
// Created by Kirill Averyanov on 28/05/2017.
// Copyright © 2017 Den Ree. All rights reserved.
//
import ObjectMapper
import Alamofire
enum InstagramNetworkError: Error {
case wrongUrlComponents
// MARK: - Protected
var localizedDescription: String {
switch self {
case .wrongUrlComponents:
return "Can't create request from url components"
}
}
}
protocol AnyNetworkRoutable {
var path: String { get }
var parameters: InstagramRequestParameters { get }
var method: HTTPMethod { get }
}
protocol AnyInstagramNetworkRouter: AnyNetworkRoutable {
func asURLRequest(withAccessToken: String) throws -> URLRequest
}
extension AnyInstagramNetworkRouter {
// MARK: - AnyInstagramNetworkRouter
func asURLRequest(withAccessToken accessToken: String) throws -> URLRequest {
/// Setup path
var urlComponents = Instagram.Constants.baseUrlComponents
urlComponents.path = "/v1" + path
/// Setup parameters
var items = [URLQueryItem]()
items.append(URLQueryItem(name: Instagram.Keys.Auth.accessToken, value: accessToken))
if parameters.count > 0 {
parameters.forEach({ (parameter) in
let item = URLQueryItem(name: parameter.key, value: "\(parameter.value)")
items.append(item)
})
}
// Fill parameters
var httpBody: Data?
if method == .post {
let parametersString = items.map({$0.name + "=" + ($0.value ?? "")}).joined(separator: "&")
httpBody = parametersString.data(using: .utf8)
} else {
urlComponents.queryItems = items
}
// Create request
if let url = urlComponents.url {
print(url)
var request = URLRequest(url: url)
request.httpMethod = method.rawValue
request.httpBody = httpBody
return request
} else {
throw InstagramNetworkError.wrongUrlComponents
}
}
}
extension AnyInstagramNetworkRouter {
func describe() {
print("\n")
print("Instagram Network Router Description...")
print("Path: \(self.path)")
if self.parameters.isEmpty {
print("Parameters: nil")
} else {
print("Parameters: \(self.parameters)")
}
print("HTTPMethod: \(self.method)")
}
}
| mit | a7b838e20145e491941c232467689c1e | 26.304878 | 97 | 0.672622 | 4.356031 | false | false | false | false |
zhukov-ever/instagram-popular | instagram-popular/PopularTVC.swift | 1 | 4337 | //
// ViewController.swift
// instagram-popular
//
// Created by Zhn on 19/09/2015.
// Copyright (c) 2015 zhn. All rights reserved.
//
import UIKit
class PopularCell: UITableViewCell {
@IBOutlet weak var imageViewPopular: UIImageView!
@IBOutlet weak var labelCaption: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
NSNotificationCenter.defaultCenter().addObserver(self, selector: "imageDidLoadHandler:", name: kImageDidLoadNotification, object: nil)
}
func imageDidLoadHandler(sender:NSNotification) {
let _dict:Dictionary = sender.userInfo as Dictionary!
let _stringUrl = _dict[kImageDidLoadUrlKey] as! String
if (_stringUrl == self.info?.imageUrl) {
self.imageViewPopular.image = info?.image
}
}
var info:PopularInfo? {
didSet {
if info == nil || info?.caption == nil {
self.labelCaption.hidden = true
} else {
self.labelCaption.hidden = false
self.labelCaption.text = info?.caption;
}
self.imageViewPopular.image = info?.image
}
}
}
class PopularTVC: UITableViewController {
let dataManager = PopularDataManager()
override func viewDidLoad() {
super.viewDidLoad()
self.dataManager.delegate = self
self.dataManager.apiReload()
self.refreshControl = UIRefreshControl()
self.refreshControl?.addTarget(self, action: "refreshHandler", forControlEvents: UIControlEvents.ValueChanged)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "refreshHandler", name: UIApplicationDidBecomeActiveNotification, object: nil)
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
self.dataManager.apiReload()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func refreshHandler() {
self.dataManager.apiReload()
}
@IBAction func logoutHandler(sender: AnyObject) {
AuthDataStorage.authToken = nil
InstagramAuthRouter.show(self, animated: true)
}
func showAlert() {
if self.presentedViewController != nil {
return
}
let _alert = UIAlertController.new()
_alert.title = "Ошибка"
_alert.message = "Не удалось обновить данные. Попробовать еще раз?"
let _alertActionOk = UIAlertAction(title: "Ok", style: UIAlertActionStyle.Default) { (action:UIAlertAction!) -> Void in
self.dataManager.apiReload()
}
let _alertActionCancel = UIAlertAction(title: "Отмена", style: UIAlertActionStyle.Cancel) { (action:UIAlertAction!) -> Void in }
_alert.addAction(_alertActionOk)
_alert.addAction(_alertActionCancel)
self.presentViewController(_alert, animated: true, completion: nil)
}
}
extension PopularTVC: PopularDataManagerDelegate {
func dataManagerReloadApiFailed(dataManager: PopularDataManager, error: NSError) {
self.showAlert()
self.refreshControl?.endRefreshing()
}
func dataManagerReloadApiSuccessfully(dataManager: PopularDataManager) {
self.refreshControl?.endRefreshing()
self.tableView.reloadData()
}
}
extension PopularTVC: UITableViewDelegate, UITableViewDataSource {
override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return CGRectGetWidth(UIScreen.mainScreen().bounds)
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if self.dataManager.data != nil {
return self.dataManager.data!.count
}
return 0
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let _cell = tableView.dequeueReusableCellWithIdentifier("cell") as! PopularCell
let _info = self.dataManager.data![indexPath.row] as! PopularInfo
_cell.info = _info
return _cell;
}
} | mit | 2b832ab9938316e0838167b33f590978 | 29.834532 | 151 | 0.64154 | 5.107271 | false | false | false | false |
loudnate/LoopKit | LoopKit/QuantityFormatter.swift | 1 | 8332 | //
// QuantityFormatter.swift
// LoopKit
//
// Copyright © 2018 LoopKit Authors. All rights reserved.
//
import Foundation
import HealthKit
/// Formats unit quantities as localized strings
open class QuantityFormatter {
public init() {
}
/// The unit style determines how the unit strings are abbreviated, and spacing between the value and unit
open var unitStyle: Formatter.UnitStyle = .medium {
didSet {
if hasMeasurementFormatter {
measurementFormatter.unitStyle = unitStyle
}
if hasMassFormatter {
massFormatter.unitStyle = unitStyle
}
}
}
open var locale: Locale = Locale.current {
didSet {
if hasNumberFormatter {
numberFormatter.locale = locale
}
if hasMeasurementFormatter {
measurementFormatter.locale = locale
}
}
}
/// Updates `numberFormatter` configuration for the specified unit
///
/// - Parameter unit: The unit
open func setPreferredNumberFormatter(for unit: HKUnit) {
numberFormatter.numberStyle = .decimal
numberFormatter.minimumFractionDigits = unit.preferredFractionDigits
numberFormatter.maximumFractionDigits = unit.preferredFractionDigits
}
private var hasNumberFormatter = false
/// The formatter used for the quantity values
open private(set) lazy var numberFormatter: NumberFormatter = {
hasNumberFormatter = true
let formatter = NumberFormatter()
formatter.numberStyle = .decimal
formatter.locale = self.locale
return formatter
}()
private var hasMeasurementFormatter = false
/// MeasurementFormatter is used for gram measurements, mg/dL units, and mmol/L units.
/// It does not properly handle glucose measurements, as it changes unit scales: 100 mg/dL -> 1 g/L
private lazy var measurementFormatter: MeasurementFormatter = {
hasMeasurementFormatter = true
let formatter = MeasurementFormatter()
formatter.unitOptions = [.providedUnit]
formatter.numberFormatter = self.numberFormatter
formatter.locale = self.locale
formatter.unitStyle = self.unitStyle
return formatter
}()
private var hasMassFormatter = false
/// MassFormatter properly creates unit strings for grams in .short/.medium style as "g", where MeasurementFormatter uses "gram"/"grams"
private lazy var massFormatter: MassFormatter = {
hasMassFormatter = true
let formatter = MassFormatter()
formatter.numberFormatter = self.numberFormatter
formatter.unitStyle = self.unitStyle
return formatter
}()
/// Formats a quantity and unit as a localized string
///
/// - Parameters:
/// - quantity: The quantity
/// - unit: The value. An exception is thrown if `quantity` is not compatible with the unit.
/// - Returns: A localized string, or nil if `numberFormatter` is unable to format the quantity value
open func string(from quantity: HKQuantity, for unit: HKUnit) -> String? {
let value = quantity.doubleValue(for: unit)
if let foundationUnit = unit.foundationUnit, unit.usesMeasurementFormatterForMeasurement {
return measurementFormatter.string(from: Measurement(value: value, unit: foundationUnit))
}
return numberFormatter.string(from: value, unit: string(from: unit, forValue: value), style: unitStyle)
}
/// Formats a unit as a localized string
///
/// - Parameters:
/// - unit: The unit
/// - value: An optional value for determining the plurality of the unit string
/// - Returns: A string for the unit. If no localization entry is available, the unlocalized `unitString` is returned.
open func string(from unit: HKUnit, forValue value: Double = 10) -> String {
if let string = unit.localizedUnitString(in: unitStyle, singular: abs(1.0 - value) < .ulpOfOne) {
return string
}
if unit.usesMassFormatterForUnitString {
return massFormatter.unitString(fromValue: value, unit: HKUnit.massFormatterUnit(from: unit))
}
if let foundationUnit = unit.foundationUnit {
return measurementFormatter.string(from: foundationUnit)
}
// Fallback, unlocalized
return unit.unitString
}
}
public extension HKUnit {
var usesMassFormatterForUnitString: Bool {
return self == .gram()
}
var usesMeasurementFormatterForMeasurement: Bool {
return self == .gram()
}
var preferredFractionDigits: Int {
if self == HKUnit.millimolesPerLiter || self == HKUnit.millimolesPerLiter.unitDivided(by: .internationalUnit()) {
return 1
} else {
return 0
}
}
// Short localized unit string with unlocalized fallback
func shortLocalizedUnitString() -> String {
return localizedUnitString(in: .short) ?? unitString
}
func localizedUnitString(in style: Formatter.UnitStyle, singular: Bool = false) -> String? {
if self == .internationalUnit() {
switch style {
case .short, .medium:
return LocalizedString("U", comment: "The short unit display string for international units of insulin")
case .long:
fallthrough
@unknown default:
if singular {
return LocalizedString("Unit", comment: "The long unit display string for a singular international unit of insulin")
} else {
return LocalizedString("Units", comment: "The long unit display string for international units of insulin")
}
}
}
if self == .internationalUnitsPerHour {
switch style {
case .short, .medium:
return LocalizedString("U/hr", comment: "The short unit display string for international units of insulin per hour")
case .long:
fallthrough
@unknown default:
if singular {
return LocalizedString("Unit/hour", comment: "The long unit display string for a singular international unit of insulin per hour")
} else {
return LocalizedString("Units/hour", comment: "The long unit display string for international units of insulin per hour")
}
}
}
if self == HKUnit.millimolesPerLiter {
switch style {
case .short, .medium:
return LocalizedString("mmol/L", comment: "The short unit display string for millimoles per liter")
case .long:
break // Fallback to the MeasurementFormatter localization
@unknown default:
break
}
}
if self == HKUnit.milligramsPerDeciliter.unitDivided(by: HKUnit.internationalUnit()) {
switch style {
case .short, .medium:
return LocalizedString("mg/dL/U", comment: "The short unit display string for milligrams per deciliter per U")
case .long:
break // Fallback to the MeasurementFormatter localization
@unknown default:
break
}
}
if self == HKUnit.millimolesPerLiter.unitDivided(by: HKUnit.internationalUnit()) {
switch style {
case .short, .medium:
return LocalizedString("mmol/L/U", comment: "The short unit display string for millimoles per liter per U")
case .long:
break // Fallback to the MeasurementFormatter localization
@unknown default:
break
}
}
if self == HKUnit.gram().unitDivided(by: HKUnit.internationalUnit()) {
switch style {
case .short, .medium:
return LocalizedString("g/U", comment: "The short unit display string for grams per U")
case .long:
fallthrough
@unknown default:
break // Fallback to the MeasurementFormatter localization
}
}
return nil
}
}
| mit | 8ddb3d94bf3a143748a2b73ae6e27bce | 35.064935 | 150 | 0.615772 | 5.289524 | false | false | false | false |
FandyLiu/FDDemoCollection | Swift/Apply/Apply/CommonTableViewCell.swift | 1 | 12931 | //
// CustomTableViewCell.swift
// Apply
//
// Created by QianTuFD on 2017/3/28.
// Copyright © 2017年 fandy. All rights reserved.
//
import UIKit
enum CommonTableViewCellType {
case describe(title: String, subtitle: String)
case input0(title: String, placeholder: String)
case input1(title: String, rightplaceholder: String)
case input2(placeholder: String)
case verification(placeholder: String)
}
class CommonTableViewCell: ApplyTableViewCell, ApplyTableViewCellProtocol {
static let indentifier = "CommonTableViewCell"
var titleLabelWidth: CGFloat {
let text: NSString = "你好你好:"
let contentSize = CGSize(width: CGFloat(MAXFLOAT) , height: CGFloat(MAXFLOAT))
return text.textSizeWith(contentSize: contentSize, font: titleLabel.font).width
}
var separatorLeftConstraint: NSLayoutConstraint?
var textFieldRightConstraint: NSLayoutConstraint?
var textFieldLeftConstraint: NSLayoutConstraint?
var myType: CommonTableViewCellType = .describe(title: "", subtitle: "") {
didSet {
self.cellType = ApplyTableViewCellType.common(myType)
switch myType {
case let .describe(title: title, subtitle: subtitle):
self.descriptionLabel.text(contents: (text: title, font: FONT_28PX), (text: subtitle, font: FONT_24PX))
separatorLeftConstraint?.constant = 0
show(views: descriptionLabel)
case let .input0(title: title, placeholder: placeholder):
titleLabel.text = title
textField.placeholder = placeholder
separatorLeftConstraint?.constant = 15
textFieldLeftConstraint?.constant = 0.0
textFieldRightConstraint?.constant = 0.0
titleLabel.alignmentJustify_colon(withWidth: titleLabelWidth)
show(views: titleLabel, textField)
case let .input1(title: title, rightplaceholder: rightplaceholder):
titleLabel.text = title
textField.placeholder = rightplaceholder
separatorLeftConstraint?.constant = 15
textFieldLeftConstraint?.constant = 0.0
textFieldRightConstraint?.constant = -25.0
textField.textAlignment = NSTextAlignment.right
titleLabel.alignmentJustify_colon(withWidth: titleLabelWidth)
show(views: titleLabel, textField, arrowImageView)
case let .input2(placeholder: placeholder):
textField.placeholder = placeholder
separatorLeftConstraint?.constant = 15
textFieldLeftConstraint?.constant = -titleLabelWidth
textFieldRightConstraint?.constant = 0.0
show(views: textField)
case let .verification(placeholder: placeholder):
textField.placeholder = placeholder
separatorLeftConstraint?.constant = 15
textFieldLeftConstraint?.constant = -titleLabelWidth
textFieldRightConstraint?.constant = -100.0
show(views: textField, verificationButton)
}
}
}
override var textFieldText: String? {
didSet {
textField.text = textFieldText
}
}
func show(views: UIView...) {
for view in mycontentView.subviews {
if views.contains(view) {
view.isHidden = false
}else {
view.isHidden = true
}
}
}
let separatorView: UIView = {
let separatorView = UIView()
separatorView.translatesAutoresizingMaskIntoConstraints = false
separatorView.backgroundColor = COLOR_dadada
return separatorView
}()
let descriptionLabel: UILabel = {
let descriptionLabel = UILabel()
descriptionLabel.translatesAutoresizingMaskIntoConstraints = false
// descriptionLabel.backgroundColor = UIColor.red
descriptionLabel.textColor = COLOR_666666
descriptionLabel.font = FONT_28PX
return descriptionLabel
}()
let titleLabel: UILabel = {
let titleLabel = UILabel()
titleLabel.translatesAutoresizingMaskIntoConstraints = false
// titleLabel.backgroundColor = UIColor.green
titleLabel.textColor = COLOR_222222
titleLabel.font = FONT_28PX
return titleLabel
}()
let textField: UITextField = {
let textField = UITextField()
textField.translatesAutoresizingMaskIntoConstraints = false
// textField.backgroundColor = UIColor.blue
textField.textColor = COLOR_222222
textField.font = FONT_28PX
return textField
}()
let arrowImageView: UIImageView = {
let arrow = UIImageView(image: UIImage(named: "icon"))
arrow.translatesAutoresizingMaskIntoConstraints = false
return arrow
}()
let verificationButton: UIButton = {
let btn = UIButton(type: .custom)
btn.translatesAutoresizingMaskIntoConstraints = false
btn.setTitle("获取验证码", for: .normal)
btn.backgroundColor = COLOR_1478b8
btn.setTitleColor(UIColor.white, for: .normal)
btn.titleLabel?.font = FONT_24PX
btn.layer.cornerRadius = 5.f
btn.layer.masksToBounds = true
return btn
}()
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
cellHeight = 50.0
textField.delegate = self
verificationButton.addTarget(self, action: #selector(CommonTableViewCell.btnClick(btn:)), for: .touchUpInside)
setupUI()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func btnClick(btn: UIButton) {
delegate?.commonCell?(self, verificationButtonClick: btn)
}
}
// MARK: - UITextFieldDelegate
extension CommonTableViewCell: UITextFieldDelegate {
func textFieldDidEndEditing(_ textField: UITextField) {
delegate?.commonCell?(self, textFieldDidEndEditing: textField)
}
func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
delegate?.commonCell?(self, textFieldShouldBeginEditing: textField)
switch myType {
case .input1:
delegate?.commonCell?(self, arrowCellClick: textField)
return false
default:
return true
}
}
}
// MARK: - UI
extension CommonTableViewCell {
fileprivate func setupUI() {
contentView.addSubview(separatorView)
mycontentView.addSubview(descriptionLabel)
mycontentView.addSubview(titleLabel)
mycontentView.addSubview(textField)
mycontentView.addSubview(arrowImageView)
mycontentView.addSubview(verificationButton)
// separatorView
({
let leftConstraint = NSLayoutConstraint(item: separatorView, attribute: NSLayoutAttribute.left, relatedBy: NSLayoutRelation.equal, toItem: contentView, attribute: NSLayoutAttribute.left, multiplier: 1.0, constant: 0.0)
separatorLeftConstraint = leftConstraint
let rightConstraint = NSLayoutConstraint(item: separatorView, attribute: NSLayoutAttribute.right, relatedBy: NSLayoutRelation.equal, toItem: contentView, attribute: NSLayoutAttribute.right, multiplier: 1.0, constant: 0.0)
let bottomConstraint = NSLayoutConstraint(item: separatorView, attribute: NSLayoutAttribute.bottom, relatedBy: NSLayoutRelation.equal, toItem: contentView, attribute: NSLayoutAttribute.bottom, multiplier: 1.0, constant: 0.0)
let heightConstraint = NSLayoutConstraint(item: separatorView, attribute: NSLayoutAttribute.height, relatedBy: NSLayoutRelation.equal, toItem: nil, attribute: NSLayoutAttribute.notAnAttribute, multiplier: 1.0, constant: 1.0)
separatorView.addConstraint(heightConstraint)
contentView.addConstraints([leftConstraint, rightConstraint, bottomConstraint])
}())
// descriptionLabel
({
let leftConstraint = NSLayoutConstraint(item: descriptionLabel, attribute: NSLayoutAttribute.left, relatedBy: NSLayoutRelation.equal, toItem: mycontentView, attribute: NSLayoutAttribute.left, multiplier: 1.0, constant: 0.0)
let rightConstraint = NSLayoutConstraint(item: descriptionLabel, attribute: NSLayoutAttribute.right, relatedBy: NSLayoutRelation.equal, toItem: mycontentView, attribute: NSLayoutAttribute.right, multiplier: 1.0, constant: 0.0)
let centerYConstraint = NSLayoutConstraint(item: descriptionLabel, attribute: NSLayoutAttribute.centerY, relatedBy: NSLayoutRelation.equal, toItem: mycontentView, attribute: NSLayoutAttribute.centerY, multiplier: 1.0, constant: 0.0)
mycontentView.addConstraints([leftConstraint, rightConstraint, centerYConstraint])
}())
// titleLabel
({
let leftConstraint = NSLayoutConstraint(item: titleLabel, attribute: NSLayoutAttribute.left, relatedBy: NSLayoutRelation.equal, toItem: mycontentView, attribute: NSLayoutAttribute.left, multiplier: 1.0, constant: 0.0)
let centerYConstraint = NSLayoutConstraint(item: titleLabel, attribute: NSLayoutAttribute.centerY, relatedBy: NSLayoutRelation.equal, toItem: mycontentView, attribute: NSLayoutAttribute.centerY, multiplier: 1.0, constant: 0.0)
let widthConstraint = NSLayoutConstraint(item: titleLabel, attribute: NSLayoutAttribute.width, relatedBy: NSLayoutRelation.equal, toItem: nil, attribute: NSLayoutAttribute.notAnAttribute, multiplier: 1.0, constant: titleLabelWidth + 0.5)
mycontentView.addConstraints([leftConstraint, centerYConstraint])
titleLabel.addConstraint(widthConstraint)
}())
// textField
({
let leftConstraint = NSLayoutConstraint(item: textField, attribute: NSLayoutAttribute.left, relatedBy: NSLayoutRelation.equal, toItem: titleLabel, attribute: NSLayoutAttribute.right, multiplier: 1.0, constant: 0.0)
textFieldLeftConstraint = leftConstraint
let rightConstraint = NSLayoutConstraint(item: textField, attribute: NSLayoutAttribute.right, relatedBy: NSLayoutRelation.equal, toItem: mycontentView, attribute: NSLayoutAttribute.right, multiplier: 1.0, constant: 0.0)
textFieldRightConstraint = rightConstraint
let centerYConstraint = NSLayoutConstraint(item: textField, attribute: NSLayoutAttribute.centerY, relatedBy: NSLayoutRelation.equal, toItem: mycontentView, attribute: NSLayoutAttribute.centerY, multiplier: 1.0, constant: 0.0)
mycontentView.addConstraints([leftConstraint, rightConstraint, centerYConstraint])
}())
// arrowImageView
({
let rightConstraint = NSLayoutConstraint(item: arrowImageView, attribute: NSLayoutAttribute.right, relatedBy: NSLayoutRelation.equal, toItem: mycontentView, attribute: NSLayoutAttribute.right, multiplier: 1.0, constant: -2.0)
let centerYConstraint = NSLayoutConstraint(item: arrowImageView , attribute: NSLayoutAttribute.centerY, relatedBy: NSLayoutRelation.equal, toItem: mycontentView, attribute: NSLayoutAttribute.centerY, multiplier: 1.0, constant: 0.0)
mycontentView.addConstraints([rightConstraint, centerYConstraint])
}())
// verificationButton
({
let widthConstraint = NSLayoutConstraint(item: verificationButton, attribute: NSLayoutAttribute.width, relatedBy: NSLayoutRelation.equal, toItem: nil, attribute: NSLayoutAttribute.notAnAttribute, multiplier: 1.0, constant: 80)
let heightConstraint = NSLayoutConstraint(item: verificationButton, attribute: NSLayoutAttribute.height, relatedBy: NSLayoutRelation.equal, toItem: nil, attribute: NSLayoutAttribute.notAnAttribute, multiplier: 1.0, constant: 27)
let rightConstraint = NSLayoutConstraint(item: verificationButton, attribute: NSLayoutAttribute.right, relatedBy: NSLayoutRelation.equal, toItem: mycontentView, attribute: NSLayoutAttribute.right, multiplier: 1.0, constant: -3.0)
let centerYConstraint = NSLayoutConstraint(item: verificationButton , attribute: NSLayoutAttribute.centerY, relatedBy: NSLayoutRelation.equal, toItem: mycontentView, attribute: NSLayoutAttribute.centerY, multiplier: 1.0, constant: 0.0)
verificationButton.addConstraints([widthConstraint, heightConstraint])
mycontentView.addConstraints([rightConstraint, centerYConstraint])
}())
}
}
| mit | 6ddc99f0594b6eeb7c2f31d0a348997a | 48.079848 | 249 | 0.679036 | 5.68885 | false | false | false | false |
honghaoz/ZHStackView | ZHStackViewDemo/ZHStackViewDemo/ViewController.swift | 2 | 4804 | //
// ViewController.swift
// ZHStackViewDemo
//
// Created by Honghao Zhang on 2014-10-17.
// Copyright (c) 2014 HonghaoZ. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
var stackedView: ZHStackView = ZHStackView()
@IBOutlet weak var indexField: UITextField!
@IBOutlet weak var newViewContainer: UIView!
@IBOutlet weak var viewTop: UITextField!
@IBOutlet weak var viewLeft: UITextField!
@IBOutlet weak var viewBottom: UITextField!
@IBOutlet weak var viewRight: UITextField!
@IBOutlet weak var sampleViewsContainer: UIView!
@IBOutlet weak var viewsTypeSeg: UISegmentedControl!
var newView: UIView!
var sampleViews = [UIView]()
var containerInset = UIEdgeInsetsZero
@IBOutlet weak var alignmentSeg: UISegmentedControl!
@IBOutlet weak var presentView: UIView!
override func viewDidLoad() {
super.viewDidLoad()
stackedView.backgroundColor = UIColor(white: 1.0, alpha: 1.0)
alignmentSeg.selectedSegmentIndex = 0;
self.alignmentSegChanged(alignmentSeg)
// containerInset = UIEdgeInsetsMake(10, 20, 30, 20)
stackedView.defaultSpacing = 0.0
self.newViewInContainer()
self.random(nil)
}
// MARK: - Actions
@IBAction func random(sender: AnyObject!) {
stackedView.reset()
sampleViews = []
for _ in 0 ..< Int(arc4random_uniform(UInt32(5))) {
sampleViews.append(self.newRandomView())
}
sampleViews.append(self.newRandomView())
stackedView.setUpViews(sampleViews, viewInsets: nil, containerInset: containerInset)
centerStackView()
}
@IBAction func refresh(sender: AnyObject) {
newView.removeFromSuperview()
self.newViewInContainer()
}
@IBAction func append(sender: AnyObject) {
stackedView.append(newView, viewInset: getViewInset())
newViewInContainer()
centerStackView()
}
@IBAction func insert(sender: AnyObject) {
let index: Int = indexField.text.toInt()!
stackedView.insert(newView, viewInset: getViewInset(), atIndex: index)
newViewInContainer()
centerStackView()
}
@IBAction func remove(sender: AnyObject) {
let index: Int = indexField.text.toInt()!
stackedView.removeAtIndex(index)
centerStackView()
}
@IBAction func alignmentSegChanged(sender: AnyObject) {
switch alignmentSeg.selectedSegmentIndex {
case 0:
stackedView.alignment = .Left
case 1:
stackedView.alignment = .Center
case 2:
stackedView.alignment = .Right
default:
stackedView.alignment = .Center
}
stackedView.relayoutAllViews(animated: true)
}
func newViewInContainer() {
newView = newRandomView()
newView.frame = CGRectMake((newViewContainer.bounds.size.width - newView.bounds.size.width) / 2.0, (newViewContainer.bounds.size.height - newView.bounds.size.height) / 2.0, newView.bounds.size.width, newView.bounds.size.height)
newViewContainer.addSubview(newView)
}
func newRandomView() -> UIView {
var newView = UIView(frame: CGRectMake(0, 0, CGFloat(arc4random_uniform(UInt32(newViewContainer.bounds.size.width))), CGFloat(arc4random_uniform(UInt32(newViewContainer.bounds.size.height)))))
newView.backgroundColor = randomColor()
return newView
}
func centerStackView() {
self.presentView.addSubview(stackedView)
stackedView.frame = CGRectMake((self.presentView.bounds.size.width - stackedView.bounds.size.width) / 2.0, 10, stackedView.bounds.size.width, stackedView.bounds.size.height)
}
@IBAction func viewTapped(sender: AnyObject) {
indexField.resignFirstResponder()
viewTop.resignFirstResponder()
viewLeft.resignFirstResponder()
viewBottom.resignFirstResponder()
viewRight.resignFirstResponder()
}
func getViewInset() -> UIEdgeInsets {
return UIEdgeInsetsMake(CGFloat(viewTop.text.toInt()!), CGFloat(viewLeft.text.toInt()!), CGFloat(viewBottom.text.toInt()!), CGFloat(viewRight.text.toInt()!))
}
}
// MARK: - Helpers
func copyOfView(view: UIView) -> UIView {
var data: NSData = NSKeyedArchiver.archivedDataWithRootObject(view)
var copy: UIView = NSKeyedUnarchiver.unarchiveObjectWithData(data) as UIView
return copy
}
func random(range: Int) -> CGFloat {
return CGFloat(arc4random_uniform(UInt32(range)))
}
func randomColor() -> UIColor {
return UIColor(red: random(255) / 255.0, green: random(255) / 225.0, blue: random(255) / 255.0, alpha: 0.9)
}
| mit | 9d52a3ba6ae73b1a72eceeb40c31a50b | 32.361111 | 235 | 0.661324 | 4.540643 | false | false | false | false |
EgeTart/GuideAndBanner | GuideAndBanner/GuideAndBanner/AppDelegate.swift | 1 | 921 | //
// AppDelegate.swift
// GuideAndBanner
//
//
// Copyright © 2015年 EgeTart. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// 10. 检测是否第一次运行
let firstLuanch = !NSUserDefaults.standardUserDefaults().boolForKey("notFirstLuanch")
if firstLuanch == true {
NSUserDefaults.standardUserDefaults().setBool(true, forKey: "notFirstLuanch")
}
else {
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let mainPageVC = storyboard.instantiateViewControllerWithIdentifier("mainPage")
window?.rootViewController = mainPageVC
}
return true
}
}
| gpl-2.0 | daaceb137694bc399f9e3fc8bf212b54 | 25.470588 | 127 | 0.653333 | 4.945055 | false | false | false | false |
zhihuitang/Apollo | Apollo/TimerViewController.swift | 1 | 3861 | //
// TimerViewController.swift
// Apollo
//
// Created by Zhihui Tang on 2016-12-28.
// Copyright © 2016 Zhihui Tang. All rights reserved.
//
import UIKit
class TimerViewController: BaseViewController {
@IBOutlet weak var buttonStart: UIButton!
@IBOutlet weak var buttonPause: UIButton!
@IBOutlet weak var buttonReset: UIButton!
let timeInterval = 0.1
let TOKEN_REFRESH_PERIOD:Double = 10
let key = "timer_count"
var scheduledTimer: Timer? {
willSet {
scheduledTimer?.invalidate()
}
}
@IBOutlet weak var timeLabel: UILabel!
weak var weakSelf: TimerViewController? {
get {
return self
}
}
weak var timer = Timer()
var isPlaying = false
var counter = 0.0 {
didSet {
self.timeLabel.text = String(format: "%02.2f", counter)
}
}
override func viewDidDisappear(_ animated: Bool) {
//timer.invalidate()
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func timerStart(_ sender: UIButton) {
if(isPlaying) {
return
}
buttonStart.isEnabled = false
buttonPause.isEnabled = true
timer = Timer.scheduledTimer(timeInterval: timeInterval, target: self, selector: #selector(UpdateTimer), userInfo: nil, repeats: true)
isPlaying = true
}
@IBAction func timePause(_ sender: UIButton) {
buttonStart.isEnabled = true
buttonPause.isEnabled = false
timer?.invalidate()
isPlaying = false
}
@IBAction func timeReset(_ sender: UIButton) {
buttonStart.isEnabled = true
buttonPause.isEnabled = false
timer?.invalidate()
isPlaying = false
counter = 0.0
}
public func UpdateTimer() {
weakSelf?.counter = (weakSelf?.counter)! + timeInterval
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
override func viewWillDisappear(_ animated: Bool) {
scheduledTimer?.invalidate()
scheduledTimer = nil
}
@IBOutlet weak var labelTimer: UILabel!
@IBOutlet weak var btnScheduledTimer: UIButton!
@IBAction func btnScheduledTimerClicked(_ sender: Any) {
let userDefault = UserDefaults.standard
userDefault.set(0, forKey: key)
btnScheduledTimer.setTitle(Date().description, for: .normal)
scheduledTimer = Timer.scheduledTimer(timeInterval: TOKEN_REFRESH_PERIOD,
target: self,
selector: #selector(self.refreshToken),
userInfo: nil,
repeats: true)
}
func refreshToken() {
let now = Date()
let userDefault = UserDefaults.standard
var count = 1
if let value = userDefault.value(forKey: key) as? Int {
count = value + 1
}
userDefault.set(count, forKey: key)
let text = "[\(count)]updated at \(now.description)"
labelTimer.text = text
logger.d("Timer.scheduledTimer test: \(text)")
}
}
extension TimerViewController {
override var name: String {
return "Timer Demo"
}
}
| apache-2.0 | d9f7fc35035f7bc9162fcde6bc5cfc27 | 26.769784 | 142 | 0.589896 | 4.96144 | false | false | false | false |
qlongming/shppingCat | shoppingCart-master/shoppingCart/Classes/Library/SnapKit/View+SnapKit.swift | 13 | 8583 | //
// SnapKit
//
// Copyright (c) 2011-2015 SnapKit Team - https://github.com/SnapKit
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#if os(iOS) || os(tvOS)
import UIKit
public typealias View = UIView
#else
import AppKit
public typealias View = NSView
#endif
/**
Used to expose public API on views
*/
public extension View {
/// left edge
public var snp_left: ConstraintItem { return ConstraintItem(object: self, attributes: ConstraintAttributes.Left) }
/// top edge
public var snp_top: ConstraintItem { return ConstraintItem(object: self, attributes: ConstraintAttributes.Top) }
/// right edge
public var snp_right: ConstraintItem { return ConstraintItem(object: self, attributes: ConstraintAttributes.Right) }
/// bottom edge
public var snp_bottom: ConstraintItem { return ConstraintItem(object: self, attributes: ConstraintAttributes.Bottom) }
/// leading edge
public var snp_leading: ConstraintItem { return ConstraintItem(object: self, attributes: ConstraintAttributes.Leading) }
/// trailing edge
public var snp_trailing: ConstraintItem { return ConstraintItem(object: self, attributes: ConstraintAttributes.Trailing) }
/// width dimension
public var snp_width: ConstraintItem { return ConstraintItem(object: self, attributes: ConstraintAttributes.Width) }
/// height dimension
public var snp_height: ConstraintItem { return ConstraintItem(object: self, attributes: ConstraintAttributes.Height) }
/// centerX position
public var snp_centerX: ConstraintItem { return ConstraintItem(object: self, attributes: ConstraintAttributes.CenterX) }
/// centerY position
public var snp_centerY: ConstraintItem { return ConstraintItem(object: self, attributes: ConstraintAttributes.CenterY) }
/// baseline position
public var snp_baseline: ConstraintItem { return ConstraintItem(object: self, attributes: ConstraintAttributes.Baseline) }
/// first baseline position
@available(iOS 8.0, *)
public var snp_firstBaseline: ConstraintItem { return ConstraintItem(object: self, attributes: ConstraintAttributes.FirstBaseline) }
/// left margin
@available(iOS 8.0, *)
public var snp_leftMargin: ConstraintItem { return ConstraintItem(object: self, attributes: ConstraintAttributes.LeftMargin) }
/// right margin
@available(iOS 8.0, *)
public var snp_rightMargin: ConstraintItem { return ConstraintItem(object: self, attributes: ConstraintAttributes.RightMargin) }
/// top margin
@available(iOS 8.0, *)
public var snp_topMargin: ConstraintItem { return ConstraintItem(object: self, attributes: ConstraintAttributes.TopMargin) }
/// bottom margin
@available(iOS 8.0, *)
public var snp_bottomMargin: ConstraintItem { return ConstraintItem(object: self, attributes: ConstraintAttributes.BottomMargin) }
/// leading margin
@available(iOS 8.0, *)
public var snp_leadingMargin: ConstraintItem { return ConstraintItem(object: self, attributes: ConstraintAttributes.LeadingMargin) }
/// trailing margin
@available(iOS 8.0, *)
public var snp_trailingMargin: ConstraintItem { return ConstraintItem(object: self, attributes: ConstraintAttributes.TrailingMargin) }
/// centerX within margins
@available(iOS 8.0, *)
public var snp_centerXWithinMargins: ConstraintItem { return ConstraintItem(object: self, attributes: ConstraintAttributes.CenterXWithinMargins) }
/// centerY within margins
@available(iOS 8.0, *)
public var snp_centerYWithinMargins: ConstraintItem { return ConstraintItem(object: self, attributes: ConstraintAttributes.CenterYWithinMargins) }
// top + left + bottom + right edges
public var snp_edges: ConstraintItem { return ConstraintItem(object: self, attributes: ConstraintAttributes.Edges) }
// width + height dimensions
public var snp_size: ConstraintItem { return ConstraintItem(object: self, attributes: ConstraintAttributes.Size) }
// centerX + centerY positions
public var snp_center: ConstraintItem { return ConstraintItem(object: self, attributes: ConstraintAttributes.Center) }
// top + left + bottom + right margins
@available(iOS 8.0, *)
public var snp_margins: ConstraintItem { return ConstraintItem(object: self, attributes: ConstraintAttributes.Margins) }
// centerX + centerY within margins
@available(iOS 8.0, *)
public var snp_centerWithinMargins: ConstraintItem { return ConstraintItem(object: self, attributes: ConstraintAttributes.CenterWithinMargins) }
/**
Prepares constraints with a `ConstraintMaker` and returns the made constraints but does not install them.
:param: closure that will be passed the `ConstraintMaker` to make the constraints with
:returns: the constraints made
*/
public func snp_prepareConstraints(file: String = __FILE__, line: UInt = __LINE__, @noescape closure: (make: ConstraintMaker) -> Void) -> [Constraint] {
return ConstraintMaker.prepareConstraints(view: self, location: SourceLocation(file: file, line: line), closure: closure)
}
/**
Makes constraints with a `ConstraintMaker` and installs them along side any previous made constraints.
:param: closure that will be passed the `ConstraintMaker` to make the constraints with
*/
public func snp_makeConstraints(file: String = __FILE__, line: UInt = __LINE__, @noescape closure: (make: ConstraintMaker) -> Void) -> Void {
ConstraintMaker.makeConstraints(view: self, location: SourceLocation(file: file, line: line), closure: closure)
}
/**
Updates constraints with a `ConstraintMaker` that will replace existing constraints that match and install new ones.
For constraints to match only the constant can be updated.
:param: closure that will be passed the `ConstraintMaker` to update the constraints with
*/
public func snp_updateConstraints(file: String = __FILE__, line: UInt = __LINE__, @noescape closure: (make: ConstraintMaker) -> Void) -> Void {
ConstraintMaker.updateConstraints(view: self, location: SourceLocation(file: file, line: line), closure: closure)
}
/**
Remakes constraints with a `ConstraintMaker` that will first remove all previously made constraints and make and install new ones.
:param: closure that will be passed the `ConstraintMaker` to remake the constraints with
*/
public func snp_remakeConstraints(file: String = __FILE__, line: UInt = __LINE__, @noescape closure: (make: ConstraintMaker) -> Void) -> Void {
ConstraintMaker.remakeConstraints(view: self, location: SourceLocation(file: file, line: line), closure: closure)
}
/**
Removes all previously made constraints.
*/
public func snp_removeConstraints() {
ConstraintMaker.removeConstraints(view: self)
}
internal var snp_installedLayoutConstraints: [LayoutConstraint] {
get {
if let constraints = objc_getAssociatedObject(self, &installedLayoutConstraintsKey) as? [LayoutConstraint] {
return constraints
}
return []
}
set {
objc_setAssociatedObject(self, &installedLayoutConstraintsKey, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
}
private var installedLayoutConstraintsKey = ""
| apache-2.0 | 4fb847fd7eb2b39c684bced35ead8d95 | 45.901639 | 156 | 0.711872 | 5.051795 | false | false | false | false |
v2panda/DaysofSwift | swift2.3/My-PullToRefresh/My-PullToRefresh/ViewController.swift | 1 | 3222 | //
// ViewController.swift
// My-PullToRefresh
//
// Created by Panda on 16/2/23.
// Copyright © 2016年 v2panda. All rights reserved.
//
import UIKit
class ViewController: UIViewController ,UITableViewDataSource{
let cellIdentifier = "NewCellIdentifier"
let favoriteEmoji = ["🤗🤗🤗🤗🤗", "😅😅😅😅😅", "😆😆😆😆😆"]
let newFavoriteEmoji = ["🏃🏃🏃🏃🏃", "💩💩💩💩💩", "👸👸👸👸👸", "🤗🤗🤗🤗🤗", "😅😅😅😅😅", "😆😆😆😆😆" ]
var emojiData = [String]()
var tableViewController = UITableViewController(style: .Plain)
var refreshControl = UIRefreshControl()
var navBar = UINavigationBar(frame: CGRect(x: 0, y: 0, width: 375, height: 64))
override func preferredStatusBarStyle() -> UIStatusBarStyle {
return UIStatusBarStyle.LightContent
}
override func viewDidLoad() {
super.viewDidLoad()
emojiData = favoriteEmoji
let emojiTableView = tableViewController.tableView
emojiTableView.backgroundColor = UIColor(red: 0.092, green: 0.096, blue: 0.116, alpha: 1)
emojiTableView.dataSource = self
emojiTableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: cellIdentifier)
tableViewController.refreshControl = self.refreshControl
self.refreshControl.addTarget(self, action: "didRoadEmoji", forControlEvents: .ValueChanged)
self.refreshControl.backgroundColor = UIColor(red: 0.113, green: 0.113, blue: 0.145, alpha: 1)
let attributes = [NSForegroundColorAttributeName:UIColor.whiteColor()]
self.refreshControl.attributedTitle = NSAttributedString(string: "上次刷新时间 \(NSDate())", attributes: attributes)
self.refreshControl.tintColor = UIColor.whiteColor()
self.title = "emoji"
self.navBar.barStyle = .BlackTranslucent
emojiTableView.rowHeight = UITableViewAutomaticDimension
emojiTableView.estimatedRowHeight = 60.0
emojiTableView.tableFooterView = UIView(frame: CGRectZero)
emojiTableView.separatorStyle = UITableViewCellSeparatorStyle.None
self.view.addSubview(emojiTableView)
self.view.addSubview(navBar)
}
// MARK: UITableViewDataSource
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return emojiData.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier)! as UITableViewCell
cell.textLabel!.text = self.emojiData[indexPath.row]
cell.textLabel!.textAlignment = NSTextAlignment.Center
cell.textLabel!.font = UIFont.systemFontOfSize(50)
cell.backgroundColor = UIColor.clearColor()
cell.selectionStyle = UITableViewCellSelectionStyle.None
return cell
}
func didRoadEmoji(){
self.emojiData = newFavoriteEmoji
self.tableViewController.tableView.reloadData()
self.refreshControl.endRefreshing()
}
}
| mit | 6fcf97d58291dca5140ba449405fdd41 | 35.571429 | 118 | 0.67513 | 5.086093 | false | false | false | false |
AlexMcArdle/LooseFoot | LooseFoot/ViewControllers/LayoutExampleViewController.swift | 1 | 1314 | //
// LayoutExampleViewController.swift
// LooseFoot
//
// Created by Alexander McArdle on 2/6/17.
// Copyright © 2017 Alexander McArdle. All rights reserved.
//
import AsyncDisplayKit
class LayoutExampleViewController: ASViewController<ASDisplayNode> {
let customNode: LayoutExampleNode
init(layoutExampleType: LayoutExampleNode.Type) {
customNode = layoutExampleType.init()
super.init(node: ASDisplayNode())
self.title = "Layout Example"
self.node.addSubnode(customNode)
let needsOnlyYCentering = (layoutExampleType.isEqual(HeaderWithRightAndLeftItems.self) || layoutExampleType.isEqual(FlexibleSeparatorSurroundingContent.self))
self.node.backgroundColor = needsOnlyYCentering ? .lightGray : .white
self.node.layoutSpecBlock = { [weak self] node, constrainedSize in
guard let customNode = self?.customNode else { return ASLayoutSpec() }
return ASCenterLayoutSpec(centeringOptions: needsOnlyYCentering ? .Y : .XY,
sizingOptions: .minimumXY,
child: customNode)
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| gpl-3.0 | dfa7a4441fdf76c7220badc292d413e4 | 34.486486 | 166 | 0.648896 | 4.689286 | false | false | false | false |
grandiere/box | box/Model/Help/Basic/MHelpBasicVisor.swift | 1 | 1353 | import UIKit
class MHelpBasicVisor:MHelpProtocol
{
private let attributedString:NSAttributedString
init()
{
let attributesTitle:[String:AnyObject] = [
NSFontAttributeName:UIFont.bold(size:20),
NSForegroundColorAttributeName:UIColor.white]
let attributesDescription:[String:AnyObject] = [
NSFontAttributeName:UIFont.regular(size:18),
NSForegroundColorAttributeName:UIColor(white:1, alpha:0.8)]
let stringTitle:NSAttributedString = NSAttributedString(
string:NSLocalizedString("MHelpBasicVisor_title", comment:""),
attributes:attributesTitle)
let stringDescription:NSAttributedString = NSAttributedString(
string:NSLocalizedString("MHelpBasicVisor_description", comment:""),
attributes:attributesDescription)
let mutableString:NSMutableAttributedString = NSMutableAttributedString()
mutableString.append(stringTitle)
mutableString.append(stringDescription)
attributedString = mutableString
}
var message:NSAttributedString
{
get
{
return attributedString
}
}
var image:UIImage
{
get
{
return #imageLiteral(resourceName: "assetHelpBasicVisor")
}
}
}
| mit | 284bf1119170fbea5043f2576b2bc548 | 29.75 | 81 | 0.648928 | 6.013333 | false | false | false | false |
darioalessandro/Theater | Classes/BLEMessages.swift | 1 | 19312 | //
// BLEMessages.swift
// Actors
//
// Created by Dario Lencina on 10/15/15.
// Copyright © 2015 dario. All rights reserved.
//
import Foundation
import CoreBluetooth
/**
BLECentral related messages
*/
public extension BLECentral {
/**
Message used by BLECentral to encapsule a CBPeripheral advertisement packet
*/
class BLEPeripheralObservation {
public let peripheral: CBPeripheral
public let advertisementData: [String : Any]
public let RSSI: NSNumber
public let timestamp : Date
init(peripheral: CBPeripheral,advertisementData: [String : Any],RSSI: NSNumber,timestamp : Date) {
self.peripheral = peripheral
self.advertisementData = advertisementData
self.RSSI = RSSI
self.timestamp = timestamp
}
}
typealias PeripheralObservations = [String : [BLEPeripheralObservation]]
typealias PeripheralConnections = [UUID : ActorRef]
/**
Namespace for Peripheral related messages
*/
class Peripheral {
/**
Tries to connect to CBPeripheral
*/
public class Connect : Actor.Message {
public let peripheral : CBPeripheral
public init(sender: ActorRef?, peripheral : CBPeripheral) {
self.peripheral = peripheral
super.init(sender: sender)
}
}
/**
Message sent from BLECentral to subscribers when it connects to peripheral
*/
public class OnConnect : Actor.Message {
public let peripheralConnection : ActorRef?
public let peripheral : CBPeripheral
public init(sender: ActorRef?, peripheral: CBPeripheral, peripheralConnection : ActorRef?) {
self.peripheralConnection = peripheralConnection
self.peripheral = peripheral
super.init(sender: sender)
}
}
/**
Message sent from BLECentral to subscribers when it disconnects from peripheral
*/
public class OnDisconnect : Actor.Message {
public let error : Error?
public let peripheral : CBPeripheral
public init(sender: ActorRef?, peripheral: CBPeripheral, error : Optional<Error>) {
self.peripheral = peripheral
self.error = error
super.init(sender: sender)
}
}
/**
Actor.Message sent from BLECentral to force disconnecting peripheral
*/
public class Disconnect : Actor.Message {
public let peripheral : CBPeripheral
public init(sender: ActorRef?, peripheral : CBPeripheral) {
self.peripheral = peripheral
super.init(sender: sender)
}
}
}
/**
Use this message to tell BLECentral to start scanning, scanning success depends on the status of the BLE hardware, BLECentral will message all it's listeners when it actually starts scanning an BLECentral.StateChanged when it actually starts scanning.
*/
class StartScanning : Actor.Message {
public let services : Optional<[CBUUID]>
public init(services : Optional<[CBUUID]>, sender : ActorRef?) {
self.services = services
super.init(sender: sender)
}
}
/**
Use AddListener to subscribe to BLECentral events such as @see BLECentralMsg#DevicesObservationUpdate.
*/
class AddListener : Actor.Message {}
/**
Use RemoveListener to stop receiving BLECentral events such as #BLECentralMsg.DevicesObservationUpdate.
*/
class RemoveListener : Actor.Message {}
/**
Tell BLECentral to stop scanning
*/
class StopScanning : Actor.Message {}
/**
An StateChanged message will be sent to all #BLECentral.listeners when the underlying CBCentralManager changes it's state.
*/
class StateChanged : Actor.Message {
let state : CBManagerState
init(sender : ActorRef, state : CBManagerState) {
self.state = state
super.init(sender: sender)
}
}
/**
DevicesObservationUpdate contains an immutable dictionary with all the devices that BLECentral saw and all the observations (#BLEPeripheral) since it was created, this is very useful when monitoring RSSI because it provides a time dimension, which is important to determine if the customer is moving towards the BLE device or away from it.
*/
class DevicesObservationUpdate : Actor.Message {
public let devices : [String : [BLEPeripheralObservation]]
init(sender : ActorRef?, devices : [String : [BLEPeripheralObservation]]) {
self.devices = devices
super.init(sender: sender)
}
}
}
/**
This extension contains all the messages that BLEPeripheral produces
*/
public extension BLEPeripheral {
typealias Subscriptions = [CBCentral : [CBCharacteristic]]
/**
BLEPeripheral broadcasts this message when a central subscribes or unsubscribes from CBCharacteristics
*/
class SubscriptionsChanged : Actor.Message {
let subscriptions : Subscriptions
init(sender: ActorRef?, subscriptions : Subscriptions) {
self.subscriptions = subscriptions
super.init(sender: sender)
}
}
/**
Command used to signal BLEPeripheral to start advertising
*/
class StartAdvertising : Actor.Message {
public let advertisementData : [String : AnyObject]?
public let svcs : [CBMutableService]
public init(sender: ActorRef?, advertisementData : [String : AnyObject]?, svcs : [CBMutableService]) {
self.svcs = svcs
self.advertisementData = advertisementData
super.init(sender: sender)
}
}
/**
Command used to signal BLEPeripheral to stop advertising
*/
class StopAdvertising : Actor.Message {}
/**
Actor.Message broadcasted by BLEPeripheral when it starts advertising
*/
class DidStartAdvertising : Actor.Message {
public let svcs : [CBService]
public init(sender: ActorRef?, svcs : [CBService]) {
self.svcs = svcs
super.init(sender: sender)
}
}
/**
Actor.Message broadcasted by BLEPeripheral when it stops advertising
*/
class DidStopAdvertising : Actor.Message {}
/**
Message broadcasted by BLEPeripheral when it fails to start advertising
*/
class FailedToStartAdvertising : Actor.Message {
public let error : Error
init(sender : ActorRef?, error : Error) {
self.error = error
super.init(sender: sender)
}
}
/**
Message broadcasted when a central subscribes to a characteristic
*/
class CentralDidSubscribeToCharacteristic : Actor.Message {
public let central: CBCentral
public let characteristic: CBCharacteristic
public init(sender: ActorRef?, central : CBCentral, characteristic : CBCharacteristic) {
self.central = central
self.characteristic = characteristic
super.init(sender: sender)
}
}
/**
Message broadcasted when a central unsubscribes to a characteristic
*/
class CentralDidUnsubscribeFromCharacteristic : Actor.Message {
public let central: CBCentral
public let characteristic: CBCharacteristic
public init(sender: ActorRef?, central : CBCentral, characteristic : CBCharacteristic) {
self.central = central
self.characteristic = characteristic
super.init(sender: sender)
}
}
/**
Message broadcasted when BLEPeripheral receives a read request, user is responsible for responding using RespondToRequest
*/
class DidReceiveReadRequest : Actor.Message {
public let request: CBATTRequest
public init(sender: ActorRef?, request : CBATTRequest) {
self.request = request
super.init(sender: sender)
}
}
/**
Message used by the user to signal BLEPeripheral to respond to the CBATTRequest
*/
class RespondToRequest : Actor.Message {
public let result : CBATTError.Code
public let request: CBATTRequest
public init(sender: ActorRef?, request : CBATTRequest, result : CBATTError.Code) {
self.result = result
self.request = request
super.init(sender: sender)
}
}
class DidAddService : Actor.Message {
public let svc : CBService
public init(svc : CBService, sender: ActorRef?) {
self.svc = svc
super.init(sender: sender)
}
}
/**
Message broadcasted when BLEPeripheral receives a write request, user is responsible for responding
*/
class DidReceiveWriteRequests : Actor.Message {
public let requests: [CBATTRequest]
public init(sender: ActorRef?, requests : [CBATTRequest]) {
self.requests = requests
super.init(sender: sender)
}
}
/**
Message broadcasted when BLEPeripheral changes it CBManagerState
*/
class PeripheralManagerDidUpdateState : Actor.Message {
public let state : CBManagerState
public init(sender: ActorRef?, state : CBManagerState) {
self.state = state
super.init(sender: sender)
}
}
/**
Command to signal BLEPeripheral to remove a CBMutableService from it's GATT
*/
class RemoveServices : Actor.Message {
public let svcs : [CBMutableService]
public init(sender: ActorRef?, svcs : [CBMutableService]) {
self.svcs = svcs
super.init(sender: sender)
}
}
/**
Remove all Services
**/
class RemoveAllServices : Actor.Message {}
/**
Set all services
**/
class SetServices : Actor.Message {
public let svcs : [CBMutableService]
public init(sender: ActorRef?, svcs : [CBMutableService]) {
self.svcs = svcs
super.init(sender: sender)
}
}
/**
Command to signal BLEPeripheral to update the value of a CBMutableCharacteristic in the given centrals
*/
class UpdateCharacteristicValue : Actor.Message {
public let char : CBMutableCharacteristic
public let centrals : [CBCentral]?
public let value : Data
public init(sender: ActorRef?,
char : CBMutableCharacteristic,
centrals : [CBCentral]?,
value : Data) {
self.char = char
self.centrals = centrals
self.value = value
super.init(sender: sender)
}
}
}
/**
PeripheralConnection messages, most are just wrappers for the CBPeripheralDelegate original methods
*/
public extension BLEPeripheralConnection {
class AddListener : Actor.Message {}
class SetPeripheral : Actor.Message {
public let peripheral : CBPeripheral
public init(sender: ActorRef?, peripheral : CBPeripheral) {
self.peripheral = peripheral
super.init(sender: sender)
}
}
/**
PeripheralDidUpdateName
*/
class PeripheralDidUpdateName : Actor.Message {
public let peripheral : CBPeripheral
public init(sender: ActorRef?, peripheral : CBPeripheral) {
self.peripheral = peripheral
super.init(sender: sender)
}
}
/**
DidModifyServices
*/
class DidModifyServices : Actor.Message {
public let peripheral : CBPeripheral
public let invalidatedServices : [CBService]
public init(sender: ActorRef?, peripheral : CBPeripheral, invalidatedServices:[CBService]) {
self.peripheral = peripheral
self.invalidatedServices = invalidatedServices
super.init(sender: sender)
}
}
/**
DidReadRSSI
*/
class DidReadRSSI : Actor.Message {
public let peripheral : CBPeripheral
public let error : Error?
public let RSSI : NSNumber
public init(sender: ActorRef?,
peripheral : CBPeripheral,
error : Error?,
RSSI : NSNumber) {
self.error = error
self.RSSI = RSSI
self.peripheral = peripheral
super.init(sender: sender)
}
}
/**
DidDiscoverNoServices
*/
class DidDiscoverNoServices : Actor.Message {
public let peripheral : CBPeripheral
public let error : Error?
public init(sender: ActorRef?,
peripheral : CBPeripheral,
error : Error?) {
self.error = error
self.peripheral = peripheral
super.init(sender: sender)
}
}
/**
DidDiscoverServices
*/
class DidDiscoverServices : Actor.Message {
public let peripheral : CBPeripheral
public let error : Error?
public init(sender: ActorRef?,
peripheral : CBPeripheral,
error : Error?) {
self.error = error
self.peripheral = peripheral
super.init(sender: sender)
}
}
/**
DiscoverServices
*/
class DiscoverServices : Actor.Message {
public let services : [CBUUID]
public init(sender: ActorRef?,
services : [CBUUID]) {
self.services = services
super.init(sender: sender)
}
}
/**
DidDiscoverIncludedServicesForService
*/
class DidDiscoverIncludedServicesForService : Actor.Message {
public let peripheral : CBPeripheral
public let error : Error?
public let service: CBService
public init(sender: ActorRef?,
peripheral : CBPeripheral,
service : CBService,
error : Error?) {
self.service = service
self.error = error
self.peripheral = peripheral
super.init(sender: sender)
}
}
/**
DidDiscoverCharacteristicsForService
*/
class DidDiscoverCharacteristicsForService : Actor.Message {
public let peripheral : CBPeripheral
public let error : Error?
public let service: CBService
public init(sender: ActorRef?,
peripheral : CBPeripheral,
service : CBService,
error : Error?) {
self.service = service
self.error = error
self.peripheral = peripheral
super.init(sender: sender)
}
}
/**
DidUpdateValueForCharacteristic
*/
class DidUpdateValueForCharacteristic : Actor.Message {
public let peripheral : CBPeripheral
public let error : Error?
public let characteristic: CBCharacteristic
public init(sender: ActorRef?,
peripheral : CBPeripheral,
characteristic: CBCharacteristic,
error : Error?) {
self.characteristic = characteristic
self.error = error
self.peripheral = peripheral
super.init(sender: sender)
}
}
/**
DidWriteValueForCharacteristic
*/
class DidWriteValueForCharacteristic : Actor.Message {
public let peripheral : CBPeripheral
public let error : Error?
public let characteristic: CBCharacteristic
public init(sender: ActorRef?,
peripheral : CBPeripheral,
characteristic: CBCharacteristic,
error : Error?) {
self.characteristic = characteristic
self.error = error
self.peripheral = peripheral
super.init(sender: sender)
}
}
/**
DidUpdateNotificationStateForCharacteristic
*/
class DidUpdateNotificationStateForCharacteristic : Actor.Message {
public let peripheral : CBPeripheral
public let error : Error?
public let characteristic: CBCharacteristic
public init(sender: ActorRef?,
peripheral : CBPeripheral,
characteristic: CBCharacteristic,
error : Error?) {
self.characteristic = characteristic
self.error = error
self.peripheral = peripheral
super.init(sender: sender)
}
}
/**
DidDiscoverDescriptorsForCharacteristic
*/
class DidDiscoverDescriptorsForCharacteristic : Actor.Message {
public let peripheral : CBPeripheral
public let error : Error?
public let characteristic: CBCharacteristic
public init(sender: ActorRef?,
peripheral : CBPeripheral,
characteristic: CBCharacteristic,
error : Error?) {
self.characteristic = characteristic
self.error = error
self.peripheral = peripheral
super.init(sender: sender)
}
}
/**
DidUpdateValueForDescriptor
*/
class DidUpdateValueForDescriptor : Actor.Message {
public let peripheral: CBPeripheral
public let descriptor: CBDescriptor
public let error: Error?
public init(sender: ActorRef?,
peripheral: CBPeripheral,
descriptor: CBDescriptor,
error: Error?) {
self.peripheral = peripheral
self.descriptor = descriptor
self.error = error
super.init(sender: sender)
}
}
/**
DidWriteValueForDescriptor
*/
class DidWriteValueForDescriptor : Actor.Message {
public let peripheral: CBPeripheral
public let descriptor: CBDescriptor
public let error: Error?
public init(sender: ActorRef?,
peripheral: CBPeripheral,
descriptor: CBDescriptor,
error: Error?) {
self.peripheral = peripheral
self.descriptor = descriptor
self.error = error
super.init(sender: sender)
}
}
}
| apache-2.0 | 0043520da76ac98ccaa6ce62ff778562 | 27.232456 | 343 | 0.57242 | 5.75932 | false | false | false | false |
lukszar/PeselSwift | PeselSwiftTests/PeselSwiftTests.swift | 1 | 2202 | //
// PeselSwiftTests.swift
// PeselSwiftTests
//
// Created by Lukasz Szarkowicz on 23.06.2017.
// Copyright © 2017 Łukasz Szarkowicz. All rights reserved.
//
import XCTest
import PeselSwift
class PeselSwiftTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// This is an example of a functional test case.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measure {
// Put the code you want to measure the time of here.
}
}
func testProperPesel() {
// Arrange
let peselString = "91040910558"
let expectedValidationResult = Pesel.ValidateResult.success
let pesel = Pesel(pesel: peselString)
// Act
let result = pesel.validate()
// Asserts
assert(result == expectedValidationResult, "Should be proper pesel")
}
func testTooLongPesel() {
// Arrange
let peselString = "910409105583"
let expectedValidationResult = Pesel.ValidateResult.error(error: Pesel.ValidateError.wrongLength)
let pesel = Pesel(pesel: peselString)
// Act
let result = pesel.validate()
// Asserts
assert(result == expectedValidationResult, "Should be wrong length pesel")
}
func testNotOnlyDigitInPesel() {
// Arrange
let peselString = "91040910fdw"
let expectedValidationResult = Pesel.ValidateResult.error(error: Pesel.ValidateError.otherThanDigits)
let pesel = Pesel(pesel: peselString)
// Act
let result = pesel.validate()
// Asserts
assert(result == expectedValidationResult, "Should be other than digits pesel")
}
}
| mit | 17ebdd69bcaf1f2c04faa6b78a4e1118 | 29.985915 | 111 | 0.628182 | 4.435484 | false | true | false | false |
heitorgcosta/Quiver | Quiver/Validating/Default Validators/RegexValidator.swift | 1 | 870 | //
// RegexValidator.swift
// Quiver
//
// Created by Luciano Almeida on 26/09/17.
// Copyright © 2017 Heitor Costa. All rights reserved.
//
import Foundation
class RegexValidator: Validator {
private var pattern: String
init(pattern: String) {
self.pattern = pattern
}
override func validate(with object: Any?) throws -> Bool {
if object == nil {
return true
}
guard let string = object as? String else {
throw ValidationErrorType.typeMismatch(expected: String.self, actual: type(of: object!))
}
// RequiredValidator takes care of this validation.
if string.isEmpty {
return true
}
return string.range(of: pattern, options: String.CompareOptions.regularExpression, range: nil, locale: nil) != nil
}
}
| mit | a89a9d968e65d2c06f21e7aa8266643b | 24.558824 | 122 | 0.602992 | 4.549738 | false | false | false | false |
vivi7/GMDColors | Exemple/GMDColors/GMDColorsTableViewController.swift | 1 | 1398 | //
// ViewController.swift
// GDMColors
//
// Created by Vincenzo Favara on 12/10/15.
// Copyright © 2015 Vincenzo Favara. All rights reserved.
//
import UIKit
class GMDColorsTableViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
@IBOutlet var tableView: UITableView!
let gMDColors : [UIColor] = UIColor.GMDColors()
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.delegate = self
self.tableView.dataSource = self
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return gMDColors.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let color = gMDColors[indexPath.row]
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
cell.backgroundColor = color
cell.textLabel?.text = color.hexStringValue + " " + color.rgbStringValue
cell.detailTextLabel?.text = color.colorName
return cell
}
@IBAction func randomColorAction(_ sender: UIButton) {
self.view.backgroundColor = UIColor.GMDRandomColor()
}
}
| mit | 5a30a194d41ee9fa21fb45cd901206a7 | 27.510204 | 100 | 0.668576 | 4.817241 | false | false | false | false |
Anviking/Decodable | Tests/Repository.swift | 2 | 2050 | //
// RepositoryExample.swift
// Decodable
//
// Created by Fran_DEV on 13/07/15.
// Copyright © 2015 anviking. All rights reserved.
//
import Foundation
import protocol Decodable.Decodable
import enum Decodable.DecodingError
import struct Decodable.KeyPath
@testable import Decodable
struct Owner {
let id: Int
let login: String
}
struct Repository {
let id: Int
let name: String
let description: String
let htmlUrlString : String
let owner: Owner // Struct conforming to Decodable
let coverage: Double
let files: Array<String>
let optional: String?
let active: Bool
let optionalActive: Bool?
}
extension Owner : Decodable {
static func decode(_ j: Any) throws -> Owner {
return try Owner(
id: j => "id",
login: j => "login"
)
}
}
extension Repository : Decodable {
static func decode(_ j: Any) throws -> Repository {
return try Repository(
id: j => "id",
name: j => "name",
description: j => "description",
htmlUrlString : j => "html_url",
owner: j => "owner",
coverage: j => "coverage",
files: j => "files",
optional: j => "optional",
active: j => "active",
optionalActive: j => "optionalActive"
)
}
}
// MARK: Equatable
func == (lhs: Owner, rhs: Owner) -> Bool {
return lhs.id == rhs.id && lhs.login == rhs.login
}
extension Owner: Equatable {
var hashValue: Int { return id.hashValue }
}
func == (lhs: Repository, rhs: Repository) -> Bool {
return lhs.id == rhs.id &&
lhs.name == rhs.name &&
lhs.description == rhs.description &&
lhs.htmlUrlString == rhs.htmlUrlString &&
lhs.owner == rhs.owner &&
lhs.coverage == rhs.coverage &&
lhs.files == rhs.files &&
lhs.optional == rhs.optional &&
lhs.active == rhs.active &&
lhs.optionalActive == rhs.optionalActive
}
extension Repository: Equatable {
var hashValue: Int { return id.hashValue }
}
| mit | 83ab90c3a28899ae265642a3e5424dcb | 23.392857 | 55 | 0.596388 | 3.994152 | false | false | false | false |
avito-tech/Paparazzo | Paparazzo/Core/Helpers/ImageStorage.swift | 1 | 4023 | import AVFoundation
import MobileCoreServices
import ImageIO
public protocol ImageStorage {
func save(
sampleBuffer: CMSampleBuffer?,
callbackQueue: DispatchQueue,
completion: @escaping (String?) -> ()
)
func save(_ image: CGImage) -> String?
func remove(_ path: String)
func removeAll()
}
public final class ImageStorageImpl: ImageStorage {
private static let folderName = "Paparazzo"
private let createFolder = {
ImageStorageImpl.createImageDirectoryIfNotExist()
}()
// MARK: - Init
public init() {}
// MARK: - ImageStorage
public func save(
sampleBuffer: CMSampleBuffer?,
callbackQueue: DispatchQueue,
completion: @escaping (String?) -> ())
{
DispatchQueue.global(qos: .userInitiated).async {
let imageData = sampleBuffer.flatMap({ AVCaptureStillImageOutput.jpegStillImageNSDataRepresentation($0) })
var destination: String? = nil
if let imageData = imageData {
let path = self.randomTemporaryImageFilePath()
do {
try imageData.write(
to: URL(fileURLWithPath: path),
options: [.atomicWrite]
)
destination = path
} catch let error {
assert(false, "Couldn't save photo at path \(path) with error: \(error)")
}
}
callbackQueue.async {
completion(destination)
}
}
}
public func save(_ image: CGImage) -> String? {
let path = self.randomTemporaryImageFilePath()
let url = URL(fileURLWithPath: path)
guard let destination = CGImageDestinationCreateWithURL(url as CFURL, kUTTypeJPEG, 1, nil) else { return nil }
CGImageDestinationAddImage(destination, image, nil)
if CGImageDestinationFinalize(destination) {
return path
} else { return nil }
}
public func remove(_ path: String) {
do {
try FileManager.default.removeItem(atPath: path)
} catch let error {
assert(false, "Couldn't remove photo at path \(path) with error: \(error)")
}
}
public func removeAll() {
let imageDirectoryPath = ImageStorageImpl.imageDirectoryPath()
guard FileManager.default.fileExists(atPath: imageDirectoryPath) else {
return
}
do {
try FileManager.default.removeItem(atPath: imageDirectoryPath)
ImageStorageImpl.createImageDirectoryIfNotExist()
} catch let error {
assert(false, "Couldn't remove photo folder with error: \(error)")
}
}
// MARK: - Private
private static func createImageDirectoryIfNotExist() {
var isDirectory: ObjCBool = false
let path = ImageStorageImpl.imageDirectoryPath()
let exist = FileManager.default.fileExists(
atPath: path,
isDirectory: &isDirectory
)
if !exist || !isDirectory.boolValue {
do {
try FileManager.default.createDirectory(
atPath: ImageStorageImpl.imageDirectoryPath(),
withIntermediateDirectories: false,
attributes: nil
)
} catch let error {
assert(false, "Couldn't create folder for images with error: \(error)")
}
}
}
private static func imageDirectoryPath() -> String {
let tempDirPath = NSTemporaryDirectory() as NSString
return tempDirPath.appendingPathComponent(ImageStorageImpl.folderName)
}
private func randomTemporaryImageFilePath() -> String {
let tempName = "\(NSUUID().uuidString).jpg"
let directoryPath = ImageStorageImpl.imageDirectoryPath() as NSString
return directoryPath.appendingPathComponent(tempName)
}
}
| mit | 2b1fc3ce8c9ab15890f3ae3e8aa59595 | 32.806723 | 118 | 0.588864 | 5.548966 | false | false | false | false |
frootloops/swift | stdlib/public/SDK/Foundation/NSError.swift | 2 | 108677 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
@_exported import Foundation // Clang module
import CoreFoundation
import Darwin
import _SwiftFoundationOverlayShims
//===----------------------------------------------------------------------===//
// NSError (as an out parameter).
//===----------------------------------------------------------------------===//
public typealias NSErrorPointer = AutoreleasingUnsafeMutablePointer<NSError?>?
// Note: NSErrorPointer becomes ErrorPointer in Swift 3.
public typealias ErrorPointer = NSErrorPointer
public // COMPILER_INTRINSIC
let _nilObjCError: Error = _GenericObjCError.nilError
public // COMPILER_INTRINSIC
func _convertNSErrorToError(_ error: NSError?) -> Error {
if let error = error {
return error
}
return _nilObjCError
}
public // COMPILER_INTRINSIC
func _convertErrorToNSError(_ error: Error) -> NSError {
return unsafeDowncast(_bridgeErrorToNSError(error), to: NSError.self)
}
/// Describes an error that provides localized messages describing why
/// an error occurred and provides more information about the error.
public protocol LocalizedError : Error {
/// A localized message describing what error occurred.
var errorDescription: String? { get }
/// A localized message describing the reason for the failure.
var failureReason: String? { get }
/// A localized message describing how one might recover from the failure.
var recoverySuggestion: String? { get }
/// A localized message providing "help" text if the user requests help.
var helpAnchor: String? { get }
}
public extension LocalizedError {
var errorDescription: String? { return nil }
var failureReason: String? { return nil }
var recoverySuggestion: String? { return nil }
var helpAnchor: String? { return nil }
}
/// Class that implements the informal protocol
/// NSErrorRecoveryAttempting, which is used by NSError when it
/// attempts recovery from an error.
class _NSErrorRecoveryAttempter {
@objc(attemptRecoveryFromError:optionIndex:delegate:didRecoverSelector:contextInfo:)
func attemptRecovery(fromError nsError: NSError,
optionIndex recoveryOptionIndex: Int,
delegate: AnyObject?,
didRecoverSelector: Selector,
contextInfo: UnsafeMutableRawPointer?) {
let error = nsError as Error as! RecoverableError
error.attemptRecovery(optionIndex: recoveryOptionIndex) { success in
__NSErrorPerformRecoverySelector(delegate, didRecoverSelector, success, contextInfo)
}
}
@objc(attemptRecoveryFromError:optionIndex:)
func attemptRecovery(fromError nsError: NSError,
optionIndex recoveryOptionIndex: Int) -> Bool {
let error = nsError as Error as! RecoverableError
return error.attemptRecovery(optionIndex: recoveryOptionIndex)
}
}
/// Describes an error that may be recoverable by presenting several
/// potential recovery options to the user.
public protocol RecoverableError : Error {
/// Provides a set of possible recovery options to present to the user.
var recoveryOptions: [String] { get }
/// Attempt to recover from this error when the user selected the
/// option at the given index. This routine must call handler and
/// indicate whether recovery was successful (or not).
///
/// This entry point is used for recovery of errors handled at a
/// "document" granularity, that do not affect the entire
/// application.
func attemptRecovery(optionIndex recoveryOptionIndex: Int,
resultHandler handler: (_ recovered: Bool) -> Void)
/// Attempt to recover from this error when the user selected the
/// option at the given index. Returns true to indicate
/// successful recovery, and false otherwise.
///
/// This entry point is used for recovery of errors handled at
/// the "application" granularity, where nothing else in the
/// application can proceed until the attempted error recovery
/// completes.
func attemptRecovery(optionIndex recoveryOptionIndex: Int) -> Bool
}
public extension RecoverableError {
/// Default implementation that uses the application-model recovery
/// mechanism (``attemptRecovery(optionIndex:)``) to implement
/// document-modal recovery.
func attemptRecovery(optionIndex recoveryOptionIndex: Int,
resultHandler handler: (_ recovered: Bool) -> Void) {
handler(attemptRecovery(optionIndex: recoveryOptionIndex))
}
}
/// Describes an error type that specifically provides a domain, code,
/// and user-info dictionary.
public protocol CustomNSError : Error {
/// The domain of the error.
static var errorDomain: String { get }
/// The error code within the given domain.
var errorCode: Int { get }
/// The user-info dictionary.
var errorUserInfo: [String : Any] { get }
}
public extension CustomNSError {
/// Default domain of the error.
static var errorDomain: String {
return String(reflecting: self)
}
/// The error code within the given domain.
var errorCode: Int {
return _getDefaultErrorCode(self)
}
/// The default user-info dictionary.
var errorUserInfo: [String : Any] {
return [:]
}
}
extension CustomNSError where Self: RawRepresentable, Self.RawValue: SignedInteger {
// The error code of Error with integral raw values is the raw value.
public var errorCode: Int {
return numericCast(self.rawValue)
}
}
extension CustomNSError where Self: RawRepresentable, Self.RawValue: UnsignedInteger {
// The error code of Error with integral raw values is the raw value.
public var errorCode: Int {
return numericCast(self.rawValue)
}
}
public extension Error where Self : CustomNSError {
/// Default implementation for customized NSErrors.
var _domain: String { return Self.errorDomain }
/// Default implementation for customized NSErrors.
var _code: Int { return self.errorCode }
}
public extension Error where Self: CustomNSError, Self: RawRepresentable,
Self.RawValue: SignedInteger {
/// Default implementation for customized NSErrors.
var _code: Int { return self.errorCode }
}
public extension Error where Self: CustomNSError, Self: RawRepresentable,
Self.RawValue: UnsignedInteger {
/// Default implementation for customized NSErrors.
var _code: Int { return self.errorCode }
}
public extension Error {
/// Retrieve the localized description for this error.
var localizedDescription: String {
return (self as NSError).localizedDescription
}
}
internal let _errorDomainUserInfoProviderQueue = DispatchQueue(
label: "SwiftFoundation._errorDomainUserInfoProviderQueue")
/// Retrieve the default userInfo dictionary for a given error.
public func _getErrorDefaultUserInfo<T: Error>(_ error: T)
-> AnyObject? {
let hasUserInfoValueProvider: Bool
// If the OS supports user info value providers, use those
// to lazily populate the user-info dictionary for this domain.
if #available(OSX 10.11, iOS 9.0, tvOS 9.0, watchOS 2.0, *) {
// Note: the Cocoa error domain specifically excluded from
// user-info value providers.
let domain = error._domain
if domain != NSCocoaErrorDomain {
_errorDomainUserInfoProviderQueue.sync {
if NSError.userInfoValueProvider(forDomain: domain) != nil { return }
NSError.setUserInfoValueProvider(forDomain: domain) { (nsError, key) in
let error = nsError as Error
switch key {
case NSLocalizedDescriptionKey:
return (error as? LocalizedError)?.errorDescription
case NSLocalizedFailureReasonErrorKey:
return (error as? LocalizedError)?.failureReason
case NSLocalizedRecoverySuggestionErrorKey:
return (error as? LocalizedError)?.recoverySuggestion
case NSHelpAnchorErrorKey:
return (error as? LocalizedError)?.helpAnchor
case NSLocalizedRecoveryOptionsErrorKey:
return (error as? RecoverableError)?.recoveryOptions
case NSRecoveryAttempterErrorKey:
if error is RecoverableError {
return _NSErrorRecoveryAttempter()
}
return nil
default:
return nil
}
}
}
assert(NSError.userInfoValueProvider(forDomain: domain) != nil)
hasUserInfoValueProvider = true
} else {
hasUserInfoValueProvider = false
}
} else {
hasUserInfoValueProvider = false
}
// Populate the user-info dictionary
var result: [String : Any]
// Initialize with custom user-info.
if let customNSError = error as? CustomNSError {
result = customNSError.errorUserInfo
} else {
result = [:]
}
// Handle localized errors. If we registered a user-info value
// provider, these will computed lazily.
if !hasUserInfoValueProvider,
let localizedError = error as? LocalizedError {
if let description = localizedError.errorDescription {
result[NSLocalizedDescriptionKey] = description
}
if let reason = localizedError.failureReason {
result[NSLocalizedFailureReasonErrorKey] = reason
}
if let suggestion = localizedError.recoverySuggestion {
result[NSLocalizedRecoverySuggestionErrorKey] = suggestion
}
if let helpAnchor = localizedError.helpAnchor {
result[NSHelpAnchorErrorKey] = helpAnchor
}
}
// Handle recoverable errors. If we registered a user-info value
// provider, these will computed lazily.
if !hasUserInfoValueProvider,
let recoverableError = error as? RecoverableError {
result[NSLocalizedRecoveryOptionsErrorKey] =
recoverableError.recoveryOptions
result[NSRecoveryAttempterErrorKey] = _NSErrorRecoveryAttempter()
}
return result as AnyObject
}
// NSError and CFError conform to the standard Error protocol. Compiler
// magic allows this to be done as a "toll-free" conversion when an NSError
// or CFError is used as an Error existential.
extension NSError : Error {
@nonobjc
public var _domain: String { return domain }
@nonobjc
public var _code: Int { return code }
@nonobjc
public var _userInfo: AnyObject? { return userInfo as NSDictionary }
/// The "embedded" NSError is itself.
@nonobjc
public func _getEmbeddedNSError() -> AnyObject? {
return self
}
}
extension CFError : Error {
public var _domain: String {
return CFErrorGetDomain(self) as String
}
public var _code: Int {
return CFErrorGetCode(self)
}
public var _userInfo: AnyObject? {
return CFErrorCopyUserInfo(self) as AnyObject
}
/// The "embedded" NSError is itself.
public func _getEmbeddedNSError() -> AnyObject? {
return self
}
}
// An error value to use when an Objective-C API indicates error
// but produces a nil error object.
public enum _GenericObjCError : Error {
case nilError
}
/// An internal protocol to represent Swift error enums that map to standard
/// Cocoa NSError domains.
public protocol _ObjectiveCBridgeableError : Error {
/// Produce a value of the error type corresponding to the given NSError,
/// or return nil if it cannot be bridged.
init?(_bridgedNSError: NSError)
}
/// A hook for the runtime to use _ObjectiveCBridgeableError in order to
/// attempt an "errorTypeValue as? SomeError" cast.
///
/// If the bridge succeeds, the bridged value is written to the uninitialized
/// memory pointed to by 'out', and true is returned. Otherwise, 'out' is
/// left uninitialized, and false is returned.
public func _bridgeNSErrorToError<
T : _ObjectiveCBridgeableError
>(_ error: NSError, out: UnsafeMutablePointer<T>) -> Bool {
if let bridged = T(_bridgedNSError: error) {
out.initialize(to: bridged)
return true
} else {
return false
}
}
/// Helper protocol for _BridgedNSError, which used to provide
/// default implementations.
public protocol __BridgedNSError : Error {
static var _nsErrorDomain: String { get }
}
// Allow two bridged NSError types to be compared.
extension __BridgedNSError
where Self: RawRepresentable, Self.RawValue: SignedInteger {
public static func ==(lhs: Self, rhs: Self) -> Bool {
return lhs.rawValue == rhs.rawValue
}
}
public extension __BridgedNSError
where Self: RawRepresentable, Self.RawValue: SignedInteger {
public var _domain: String { return Self._nsErrorDomain }
public var _code: Int { return Int(rawValue) }
public init?(rawValue: RawValue) {
self = unsafeBitCast(rawValue, to: Self.self)
}
public init?(_bridgedNSError: NSError) {
if _bridgedNSError.domain != Self._nsErrorDomain {
return nil
}
self.init(rawValue: RawValue(IntMax(_bridgedNSError.code)))
}
public var hashValue: Int { return _code }
}
// Allow two bridged NSError types to be compared.
extension __BridgedNSError
where Self: RawRepresentable, Self.RawValue: UnsignedInteger {
public static func ==(lhs: Self, rhs: Self) -> Bool {
return lhs.rawValue == rhs.rawValue
}
}
public extension __BridgedNSError
where Self: RawRepresentable, Self.RawValue: UnsignedInteger {
public var _domain: String { return Self._nsErrorDomain }
public var _code: Int {
return Int(bitPattern: UInt(rawValue))
}
public init?(rawValue: RawValue) {
self = unsafeBitCast(rawValue, to: Self.self)
}
public init?(_bridgedNSError: NSError) {
if _bridgedNSError.domain != Self._nsErrorDomain {
return nil
}
self.init(rawValue: RawValue(UIntMax(UInt(_bridgedNSError.code))))
}
public var hashValue: Int { return _code }
}
/// Describes a raw representable type that is bridged to a particular
/// NSError domain.
///
/// This protocol is used primarily to generate the conformance to
/// _ObjectiveCBridgeableError for such an enum.
public protocol _BridgedNSError : __BridgedNSError,
RawRepresentable,
_ObjectiveCBridgeableError,
Hashable {
/// The NSError domain to which this type is bridged.
static var _nsErrorDomain: String { get }
}
/// Describes a bridged error that stores the underlying NSError, so
/// it can be queried.
public protocol _BridgedStoredNSError :
__BridgedNSError, _ObjectiveCBridgeableError, CustomNSError,
Hashable {
/// The type of an error code.
associatedtype Code: _ErrorCodeProtocol
/// The error code for the given error.
var code: Code { get }
//// Retrieves the embedded NSError.
var _nsError: NSError { get }
/// Create a new instance of the error type with the given embedded
/// NSError.
///
/// The \c error must have the appropriate domain for this error
/// type.
init(_nsError error: NSError)
}
/// TODO: Better way to do this?
internal func _stringDictToAnyHashableDict(_ input: [String : Any])
-> [AnyHashable : Any] {
var result = [AnyHashable : Any](minimumCapacity: input.count)
for (k, v) in input {
result[k] = v
}
return result
}
/// Various helper implementations for _BridgedStoredNSError
public extension _BridgedStoredNSError
where Code: RawRepresentable, Code.RawValue: SignedInteger {
// FIXME: Generalize to Integer.
public var code: Code {
return Code(rawValue: numericCast(_nsError.code))!
}
/// Initialize an error within this domain with the given ``code``
/// and ``userInfo``.
public init(_ code: Code, userInfo: [String : Any] = [:]) {
self.init(_nsError: NSError(domain: Self._nsErrorDomain,
code: numericCast(code.rawValue),
userInfo: _stringDictToAnyHashableDict(userInfo)))
}
/// The user-info dictionary for an error that was bridged from
/// NSError.
var userInfo: [String : Any] { return errorUserInfo }
}
/// Various helper implementations for _BridgedStoredNSError
public extension _BridgedStoredNSError
where Code: RawRepresentable, Code.RawValue: UnsignedInteger {
// FIXME: Generalize to Integer.
public var code: Code {
return Code(rawValue: numericCast(_nsError.code))!
}
/// Initialize an error within this domain with the given ``code``
/// and ``userInfo``.
public init(_ code: Code, userInfo: [String : Any] = [:]) {
self.init(_nsError: NSError(domain: Self._nsErrorDomain,
code: numericCast(code.rawValue),
userInfo: _stringDictToAnyHashableDict(userInfo)))
}
}
/// Implementation of __BridgedNSError for all _BridgedStoredNSErrors.
public extension _BridgedStoredNSError {
/// Default implementation of ``init(_bridgedNSError)`` to provide
/// bridging from NSError.
public init?(_bridgedNSError error: NSError) {
if error.domain != Self._nsErrorDomain {
return nil
}
self.init(_nsError: error)
}
}
/// Implementation of CustomNSError for all _BridgedStoredNSErrors.
public extension _BridgedStoredNSError {
// FIXME: Would prefer to have a clear "extract an NSError
// directly" operation.
static var errorDomain: String { return _nsErrorDomain }
var errorCode: Int { return _nsError.code }
var errorUserInfo: [String : Any] {
var result: [String : Any] = [:]
for (key, value) in _nsError.userInfo {
guard let stringKey = key.base as? String else { continue }
result[stringKey] = value
}
return result
}
}
/// Implementation of Hashable for all _BridgedStoredNSErrors.
public extension _BridgedStoredNSError {
var hashValue: Int {
return _nsError.hashValue
}
}
/// Describes the code of an error.
public protocol _ErrorCodeProtocol : Equatable {
/// The corresponding error code.
associatedtype _ErrorType
// FIXME: We want _ErrorType to be _BridgedStoredNSError and have its
// Code match Self, but we cannot express those requirements yet.
}
extension _ErrorCodeProtocol where Self._ErrorType: _BridgedStoredNSError {
/// Allow one to match an error code against an arbitrary error.
public static func ~=(match: Self, error: Error) -> Bool {
guard let specificError = error as? Self._ErrorType else { return false }
// FIXME: Work around IRGen crash when we set Code == Code._ErrorType.Code.
let specificCode = specificError.code as! Self
return match == specificCode
}
}
extension _BridgedStoredNSError {
/// Retrieve the embedded NSError from a bridged, stored NSError.
public func _getEmbeddedNSError() -> AnyObject? {
return _nsError
}
public static func == (lhs: Self, rhs: Self) -> Bool {
return lhs._nsError.isEqual(rhs._nsError)
}
}
@available(*, unavailable, renamed: "CocoaError")
public typealias NSCocoaError = CocoaError
/// Describes errors within the Cocoa error domain.
public struct CocoaError : _BridgedStoredNSError {
public let _nsError: NSError
public init(_nsError error: NSError) {
precondition(error.domain == NSCocoaErrorDomain)
self._nsError = error
}
public static var _nsErrorDomain: String { return NSCocoaErrorDomain }
/// The error code itself.
public struct Code : RawRepresentable, Hashable, _ErrorCodeProtocol {
public typealias _ErrorType = CocoaError
public let rawValue: Int
public init(rawValue: Int) {
self.rawValue = rawValue
}
public var hashValue: Int {
return self.rawValue
}
}
}
public extension CocoaError {
private var _nsUserInfo: [AnyHashable : Any] {
return (self as NSError).userInfo
}
/// The file path associated with the error, if any.
var filePath: String? {
return _nsUserInfo[NSFilePathErrorKey as NSString] as? String
}
/// The string encoding associated with this error, if any.
var stringEncoding: String.Encoding? {
return (_nsUserInfo[NSStringEncodingErrorKey as NSString] as? NSNumber)
.map { String.Encoding(rawValue: $0.uintValue) }
}
/// The underlying error behind this error, if any.
var underlying: Error? {
return _nsUserInfo[NSUnderlyingErrorKey as NSString] as? Error
}
/// The URL associated with this error, if any.
var url: URL? {
return _nsUserInfo[NSURLErrorKey as NSString] as? URL
}
}
public extension CocoaError {
public static func error(_ code: CocoaError.Code, userInfo: [AnyHashable : Any]? = nil, url: URL? = nil) -> Error {
var info: [AnyHashable : Any] = userInfo ?? [:]
if let url = url {
info[NSURLErrorKey] = url
}
return NSError(domain: NSCocoaErrorDomain, code: code.rawValue, userInfo: info)
}
}
extension CocoaError.Code {
public static var fileNoSuchFile: CocoaError.Code {
return CocoaError.Code(rawValue: 4)
}
public static var fileLocking: CocoaError.Code {
return CocoaError.Code(rawValue: 255)
}
public static var fileReadUnknown: CocoaError.Code {
return CocoaError.Code(rawValue: 256)
}
public static var fileReadNoPermission: CocoaError.Code {
return CocoaError.Code(rawValue: 257)
}
public static var fileReadInvalidFileName: CocoaError.Code {
return CocoaError.Code(rawValue: 258)
}
public static var fileReadCorruptFile: CocoaError.Code {
return CocoaError.Code(rawValue: 259)
}
public static var fileReadNoSuchFile: CocoaError.Code {
return CocoaError.Code(rawValue: 260)
}
public static var fileReadInapplicableStringEncoding: CocoaError.Code {
return CocoaError.Code(rawValue: 261)
}
public static var fileReadUnsupportedScheme: CocoaError.Code {
return CocoaError.Code(rawValue: 262)
}
@available(OSX, introduced: 10.5) @available(iOS, introduced: 2.0)
public static var fileReadTooLarge: CocoaError.Code {
return CocoaError.Code(rawValue: 263)
}
@available(OSX, introduced: 10.5) @available(iOS, introduced: 2.0)
public static var fileReadUnknownStringEncoding: CocoaError.Code {
return CocoaError.Code(rawValue: 264)
}
public static var fileWriteUnknown: CocoaError.Code {
return CocoaError.Code(rawValue: 512)
}
public static var fileWriteNoPermission: CocoaError.Code {
return CocoaError.Code(rawValue: 513)
}
public static var fileWriteInvalidFileName: CocoaError.Code {
return CocoaError.Code(rawValue: 514)
}
@available(OSX, introduced: 10.7) @available(iOS, introduced: 5.0)
public static var fileWriteFileExists: CocoaError.Code {
return CocoaError.Code(rawValue: 516)
}
public static var fileWriteInapplicableStringEncoding: CocoaError.Code {
return CocoaError.Code(rawValue: 517)
}
public static var fileWriteUnsupportedScheme: CocoaError.Code {
return CocoaError.Code(rawValue: 518)
}
public static var fileWriteOutOfSpace: CocoaError.Code {
return CocoaError.Code(rawValue: 640)
}
@available(OSX, introduced: 10.6) @available(iOS, introduced: 4.0)
public static var fileWriteVolumeReadOnly: CocoaError.Code {
return CocoaError.Code(rawValue: 642)
}
@available(OSX, introduced: 10.11) @available(iOS, unavailable)
public static var fileManagerUnmountUnknown: CocoaError.Code {
return CocoaError.Code(rawValue: 768)
}
@available(OSX, introduced: 10.11) @available(iOS, unavailable)
public static var fileManagerUnmountBusy: CocoaError.Code {
return CocoaError.Code(rawValue: 769)
}
public static var keyValueValidation: CocoaError.Code {
return CocoaError.Code(rawValue: 1024)
}
public static var formatting: CocoaError.Code {
return CocoaError.Code(rawValue: 2048)
}
public static var userCancelled: CocoaError.Code {
return CocoaError.Code(rawValue: 3072)
}
@available(OSX, introduced: 10.8) @available(iOS, introduced: 6.0)
public static var featureUnsupported: CocoaError.Code {
return CocoaError.Code(rawValue: 3328)
}
@available(OSX, introduced: 10.5) @available(iOS, introduced: 2.0)
public static var executableNotLoadable: CocoaError.Code {
return CocoaError.Code(rawValue: 3584)
}
@available(OSX, introduced: 10.5) @available(iOS, introduced: 2.0)
public static var executableArchitectureMismatch: CocoaError.Code {
return CocoaError.Code(rawValue: 3585)
}
@available(OSX, introduced: 10.5) @available(iOS, introduced: 2.0)
public static var executableRuntimeMismatch: CocoaError.Code {
return CocoaError.Code(rawValue: 3586)
}
@available(OSX, introduced: 10.5) @available(iOS, introduced: 2.0)
public static var executableLoad: CocoaError.Code {
return CocoaError.Code(rawValue: 3587)
}
@available(OSX, introduced: 10.5) @available(iOS, introduced: 2.0)
public static var executableLink: CocoaError.Code {
return CocoaError.Code(rawValue: 3588)
}
@available(OSX, introduced: 10.6) @available(iOS, introduced: 4.0)
public static var propertyListReadCorrupt: CocoaError.Code {
return CocoaError.Code(rawValue: 3840)
}
@available(OSX, introduced: 10.6) @available(iOS, introduced: 4.0)
public static var propertyListReadUnknownVersion: CocoaError.Code {
return CocoaError.Code(rawValue: 3841)
}
@available(OSX, introduced: 10.6) @available(iOS, introduced: 4.0)
public static var propertyListReadStream: CocoaError.Code {
return CocoaError.Code(rawValue: 3842)
}
@available(OSX, introduced: 10.6) @available(iOS, introduced: 4.0)
public static var propertyListWriteStream: CocoaError.Code {
return CocoaError.Code(rawValue: 3851)
}
@available(OSX, introduced: 10.10) @available(iOS, introduced: 8.0)
public static var propertyListWriteInvalid: CocoaError.Code {
return CocoaError.Code(rawValue: 3852)
}
@available(OSX, introduced: 10.8) @available(iOS, introduced: 6.0)
public static var xpcConnectionInterrupted: CocoaError.Code {
return CocoaError.Code(rawValue: 4097)
}
@available(OSX, introduced: 10.8) @available(iOS, introduced: 6.0)
public static var xpcConnectionInvalid: CocoaError.Code {
return CocoaError.Code(rawValue: 4099)
}
@available(OSX, introduced: 10.8) @available(iOS, introduced: 6.0)
public static var xpcConnectionReplyInvalid: CocoaError.Code {
return CocoaError.Code(rawValue: 4101)
}
@available(OSX, introduced: 10.9) @available(iOS, introduced: 7.0)
public static var ubiquitousFileUnavailable: CocoaError.Code {
return CocoaError.Code(rawValue: 4353)
}
@available(OSX, introduced: 10.9) @available(iOS, introduced: 7.0)
public static var ubiquitousFileNotUploadedDueToQuota: CocoaError.Code {
return CocoaError.Code(rawValue: 4354)
}
@available(OSX, introduced: 10.9) @available(iOS, introduced: 7.0)
public static var ubiquitousFileUbiquityServerNotAvailable: CocoaError.Code {
return CocoaError.Code(rawValue: 4355)
}
@available(OSX, introduced: 10.10) @available(iOS, introduced: 8.0)
public static var userActivityHandoffFailed: CocoaError.Code {
return CocoaError.Code(rawValue: 4608)
}
@available(OSX, introduced: 10.10) @available(iOS, introduced: 8.0)
public static var userActivityConnectionUnavailable: CocoaError.Code {
return CocoaError.Code(rawValue: 4609)
}
@available(OSX, introduced: 10.10) @available(iOS, introduced: 8.0)
public static var userActivityRemoteApplicationTimedOut: CocoaError.Code {
return CocoaError.Code(rawValue: 4610)
}
@available(OSX, introduced: 10.10) @available(iOS, introduced: 8.0)
public static var userActivityHandoffUserInfoTooLarge: CocoaError.Code {
return CocoaError.Code(rawValue: 4611)
}
@available(OSX, introduced: 10.11) @available(iOS, introduced: 9.0)
public static var coderReadCorrupt: CocoaError.Code {
return CocoaError.Code(rawValue: 4864)
}
@available(OSX, introduced: 10.11) @available(iOS, introduced: 9.0)
public static var coderValueNotFound: CocoaError.Code {
return CocoaError.Code(rawValue: 4865)
}
public static var coderInvalidValue: CocoaError.Code {
return CocoaError.Code(rawValue: 4866)
}
}
extension CocoaError.Code {
@available(*, deprecated, renamed: "fileNoSuchFile")
public static var fileNoSuchFileError: CocoaError.Code {
return CocoaError.Code(rawValue: 4)
}
@available(*, deprecated, renamed: "fileLocking")
public static var fileLockingError: CocoaError.Code {
return CocoaError.Code(rawValue: 255)
}
@available(*, deprecated, renamed: "fileReadUnknown")
public static var fileReadUnknownError: CocoaError.Code {
return CocoaError.Code(rawValue: 256)
}
@available(*, deprecated, renamed: "fileReadNoPermission")
public static var fileReadNoPermissionError: CocoaError.Code {
return CocoaError.Code(rawValue: 257)
}
@available(*, deprecated, renamed: "fileReadInvalidFileName")
public static var fileReadInvalidFileNameError: CocoaError.Code {
return CocoaError.Code(rawValue: 258)
}
@available(*, deprecated, renamed: "fileReadCorruptFile")
public static var fileReadCorruptFileError: CocoaError.Code {
return CocoaError.Code(rawValue: 259)
}
@available(*, deprecated, renamed: "fileReadNoSuchFile")
public static var fileReadNoSuchFileError: CocoaError.Code {
return CocoaError.Code(rawValue: 260)
}
@available(*, deprecated, renamed: "fileReadInapplicableStringEncoding")
public static var fileReadInapplicableStringEncodingError: CocoaError.Code {
return CocoaError.Code(rawValue: 261)
}
@available(*, deprecated, renamed: "fileReadUnsupportedScheme")
public static var fileReadUnsupportedSchemeError: CocoaError.Code {
return CocoaError.Code(rawValue: 262)
}
@available(OSX, introduced: 10.5) @available(iOS, introduced: 2.0)
@available(*, deprecated, renamed: "fileReadTooLarge")
public static var fileReadTooLargeError: CocoaError.Code {
return CocoaError.Code(rawValue: 263)
}
@available(OSX, introduced: 10.5) @available(iOS, introduced: 2.0)
@available(*, deprecated, renamed: "fileReadUnknownStringEncoding")
public static var fileReadUnknownStringEncodingError: CocoaError.Code {
return CocoaError.Code(rawValue: 264)
}
@available(*, deprecated, renamed: "fileWriteUnknown")
public static var fileWriteUnknownError: CocoaError.Code {
return CocoaError.Code(rawValue: 512)
}
@available(*, deprecated, renamed: "fileWriteNoPermission")
public static var fileWriteNoPermissionError: CocoaError.Code {
return CocoaError.Code(rawValue: 513)
}
@available(*, deprecated, renamed: "fileWriteInvalidFileName")
public static var fileWriteInvalidFileNameError: CocoaError.Code {
return CocoaError.Code(rawValue: 514)
}
@available(OSX, introduced: 10.7) @available(iOS, introduced: 5.0)
@available(*, deprecated, renamed: "fileWriteFileExists")
public static var fileWriteFileExistsError: CocoaError.Code {
return CocoaError.Code(rawValue: 516)
}
@available(*, deprecated, renamed: "fileWriteInapplicableStringEncoding")
public static var fileWriteInapplicableStringEncodingError: CocoaError.Code {
return CocoaError.Code(rawValue: 517)
}
@available(*, deprecated, renamed: "fileWriteUnsupportedScheme")
public static var fileWriteUnsupportedSchemeError: CocoaError.Code {
return CocoaError.Code(rawValue: 518)
}
@available(*, deprecated, renamed: "fileWriteOutOfSpace")
public static var fileWriteOutOfSpaceError: CocoaError.Code {
return CocoaError.Code(rawValue: 640)
}
@available(OSX, introduced: 10.6) @available(iOS, introduced: 4.0)
@available(*, deprecated, renamed: "fileWriteVolumeReadOnly")
public static var fileWriteVolumeReadOnlyError: CocoaError.Code {
return CocoaError.Code(rawValue: 642)
}
@available(OSX, introduced: 10.11) @available(iOS, unavailable)
@available(*, deprecated, renamed: "fileManagerUnmountUnknown")
public static var fileManagerUnmountUnknownError: CocoaError.Code {
return CocoaError.Code(rawValue: 768)
}
@available(OSX, introduced: 10.11) @available(iOS, unavailable)
@available(*, deprecated, renamed: "fileManagerUnmountBusy")
public static var fileManagerUnmountBusyError: CocoaError.Code {
return CocoaError.Code(rawValue: 769)
}
@available(*, deprecated, renamed: "keyValueValidation")
public static var keyValueValidationError: CocoaError.Code {
return CocoaError.Code(rawValue: 1024)
}
@available(*, deprecated, renamed: "formatting")
public static var formattingError: CocoaError.Code {
return CocoaError.Code(rawValue: 2048)
}
@available(*, deprecated, renamed: "userCancelled")
public static var userCancelledError: CocoaError.Code {
return CocoaError.Code(rawValue: 3072)
}
@available(OSX, introduced: 10.8) @available(iOS, introduced: 6.0)
@available(*, deprecated, renamed: "featureUnsupported")
public static var featureUnsupportedError: CocoaError.Code {
return CocoaError.Code(rawValue: 3328)
}
@available(OSX, introduced: 10.5) @available(iOS, introduced: 2.0)
@available(*, deprecated, renamed: "executableNotLoadable")
public static var executableNotLoadableError: CocoaError.Code {
return CocoaError.Code(rawValue: 3584)
}
@available(OSX, introduced: 10.5) @available(iOS, introduced: 2.0)
@available(*, deprecated, renamed: "executableArchitectureMismatch")
public static var executableArchitectureMismatchError: CocoaError.Code {
return CocoaError.Code(rawValue: 3585)
}
@available(OSX, introduced: 10.5) @available(iOS, introduced: 2.0)
@available(*, deprecated, renamed: "executableRuntimeMismatch")
public static var executableRuntimeMismatchError: CocoaError.Code {
return CocoaError.Code(rawValue: 3586)
}
@available(OSX, introduced: 10.5) @available(iOS, introduced: 2.0)
@available(*, deprecated, renamed: "executableLoad")
public static var executableLoadError: CocoaError.Code {
return CocoaError.Code(rawValue: 3587)
}
@available(OSX, introduced: 10.5) @available(iOS, introduced: 2.0)
@available(*, deprecated, renamed: "executableLink")
public static var executableLinkError: CocoaError.Code {
return CocoaError.Code(rawValue: 3588)
}
@available(OSX, introduced: 10.6) @available(iOS, introduced: 4.0)
@available(*, deprecated, renamed: "propertyListReadCorrupt")
public static var propertyListReadCorruptError: CocoaError.Code {
return CocoaError.Code(rawValue: 3840)
}
@available(OSX, introduced: 10.6) @available(iOS, introduced: 4.0)
@available(*, deprecated, renamed: "propertyListReadUnknownVersion")
public static var propertyListReadUnknownVersionError: CocoaError.Code {
return CocoaError.Code(rawValue: 3841)
}
@available(OSX, introduced: 10.6) @available(iOS, introduced: 4.0)
@available(*, deprecated, renamed: "propertyListReadStream")
public static var propertyListReadStreamError: CocoaError.Code {
return CocoaError.Code(rawValue: 3842)
}
@available(OSX, introduced: 10.6) @available(iOS, introduced: 4.0)
@available(*, deprecated, renamed: "propertyListWriteStream")
public static var propertyListWriteStreamError: CocoaError.Code {
return CocoaError.Code(rawValue: 3851)
}
@available(OSX, introduced: 10.10) @available(iOS, introduced: 8.0)
@available(*, deprecated, renamed: "propertyListWriteInvalid")
public static var propertyListWriteInvalidError: CocoaError.Code {
return CocoaError.Code(rawValue: 3852)
}
@available(OSX, introduced: 10.9) @available(iOS, introduced: 7.0)
@available(*, deprecated, renamed: "ubiquitousFileUnavailable")
public static var ubiquitousFileUnavailableError: CocoaError.Code {
return CocoaError.Code(rawValue: 4353)
}
@available(OSX, introduced: 10.9) @available(iOS, introduced: 7.0)
@available(*, deprecated, renamed: "ubiquitousFileNotUploadedDueToQuota")
public static var ubiquitousFileNotUploadedDueToQuotaError: CocoaError.Code {
return CocoaError.Code(rawValue: 4354)
}
@available(OSX, introduced: 10.10) @available(iOS, introduced: 8.0)
@available(*, deprecated, renamed: "userActivityHandoffFailed")
public static var userActivityHandoffFailedError: CocoaError.Code {
return CocoaError.Code(rawValue: 4608)
}
@available(OSX, introduced: 10.10) @available(iOS, introduced: 8.0)
@available(*, deprecated, renamed: "userActivityConnectionUnavailable")
public static var userActivityConnectionUnavailableError: CocoaError.Code {
return CocoaError.Code(rawValue: 4609)
}
@available(OSX, introduced: 10.10) @available(iOS, introduced: 8.0)
@available(*, deprecated, renamed: "userActivityRemoteApplicationTimedOut")
public static var userActivityRemoteApplicationTimedOutError: CocoaError.Code {
return CocoaError.Code(rawValue: 4610)
}
@available(OSX, introduced: 10.10) @available(iOS, introduced: 8.0)
@available(*, deprecated, renamed: "userActivityHandoffUserInfoTooLarge")
public static var userActivityHandoffUserInfoTooLargeError: CocoaError.Code {
return CocoaError.Code(rawValue: 4611)
}
@available(OSX, introduced: 10.11) @available(iOS, introduced: 9.0)
@available(*, deprecated, renamed: "coderReadCorrupt")
public static var coderReadCorruptError: CocoaError.Code {
return CocoaError.Code(rawValue: 4864)
}
@available(OSX, introduced: 10.11) @available(iOS, introduced: 9.0)
@available(*, deprecated, renamed: "coderValueNotFound")
public static var coderValueNotFoundError: CocoaError.Code {
return CocoaError.Code(rawValue: 4865)
}
}
extension CocoaError {
public static var fileNoSuchFile: CocoaError.Code {
return CocoaError.Code(rawValue: 4)
}
public static var fileLocking: CocoaError.Code {
return CocoaError.Code(rawValue: 255)
}
public static var fileReadUnknown: CocoaError.Code {
return CocoaError.Code(rawValue: 256)
}
public static var fileReadNoPermission: CocoaError.Code {
return CocoaError.Code(rawValue: 257)
}
public static var fileReadInvalidFileName: CocoaError.Code {
return CocoaError.Code(rawValue: 258)
}
public static var fileReadCorruptFile: CocoaError.Code {
return CocoaError.Code(rawValue: 259)
}
public static var fileReadNoSuchFile: CocoaError.Code {
return CocoaError.Code(rawValue: 260)
}
public static var fileReadInapplicableStringEncoding: CocoaError.Code {
return CocoaError.Code(rawValue: 261)
}
public static var fileReadUnsupportedScheme: CocoaError.Code {
return CocoaError.Code(rawValue: 262)
}
@available(OSX, introduced: 10.5) @available(iOS, introduced: 2.0)
public static var fileReadTooLarge: CocoaError.Code {
return CocoaError.Code(rawValue: 263)
}
@available(OSX, introduced: 10.5) @available(iOS, introduced: 2.0)
public static var fileReadUnknownStringEncoding: CocoaError.Code {
return CocoaError.Code(rawValue: 264)
}
public static var fileWriteUnknown: CocoaError.Code {
return CocoaError.Code(rawValue: 512)
}
public static var fileWriteNoPermission: CocoaError.Code {
return CocoaError.Code(rawValue: 513)
}
public static var fileWriteInvalidFileName: CocoaError.Code {
return CocoaError.Code(rawValue: 514)
}
@available(OSX, introduced: 10.7) @available(iOS, introduced: 5.0)
public static var fileWriteFileExists: CocoaError.Code {
return CocoaError.Code(rawValue: 516)
}
public static var fileWriteInapplicableStringEncoding: CocoaError.Code {
return CocoaError.Code(rawValue: 517)
}
public static var fileWriteUnsupportedScheme: CocoaError.Code {
return CocoaError.Code(rawValue: 518)
}
public static var fileWriteOutOfSpace: CocoaError.Code {
return CocoaError.Code(rawValue: 640)
}
@available(OSX, introduced: 10.6) @available(iOS, introduced: 4.0)
public static var fileWriteVolumeReadOnly: CocoaError.Code {
return CocoaError.Code(rawValue: 642)
}
@available(OSX, introduced: 10.11) @available(iOS, unavailable)
public static var fileManagerUnmountUnknown: CocoaError.Code {
return CocoaError.Code(rawValue: 768)
}
@available(OSX, introduced: 10.11) @available(iOS, unavailable)
public static var fileManagerUnmountBusy: CocoaError.Code {
return CocoaError.Code(rawValue: 769)
}
public static var keyValueValidation: CocoaError.Code {
return CocoaError.Code(rawValue: 1024)
}
public static var formatting: CocoaError.Code {
return CocoaError.Code(rawValue: 2048)
}
public static var userCancelled: CocoaError.Code {
return CocoaError.Code(rawValue: 3072)
}
@available(OSX, introduced: 10.8) @available(iOS, introduced: 6.0)
public static var featureUnsupported: CocoaError.Code {
return CocoaError.Code(rawValue: 3328)
}
@available(OSX, introduced: 10.5) @available(iOS, introduced: 2.0)
public static var executableNotLoadable: CocoaError.Code {
return CocoaError.Code(rawValue: 3584)
}
@available(OSX, introduced: 10.5) @available(iOS, introduced: 2.0)
public static var executableArchitectureMismatch: CocoaError.Code {
return CocoaError.Code(rawValue: 3585)
}
@available(OSX, introduced: 10.5) @available(iOS, introduced: 2.0)
public static var executableRuntimeMismatch: CocoaError.Code {
return CocoaError.Code(rawValue: 3586)
}
@available(OSX, introduced: 10.5) @available(iOS, introduced: 2.0)
public static var executableLoad: CocoaError.Code {
return CocoaError.Code(rawValue: 3587)
}
@available(OSX, introduced: 10.5) @available(iOS, introduced: 2.0)
public static var executableLink: CocoaError.Code {
return CocoaError.Code(rawValue: 3588)
}
@available(OSX, introduced: 10.6) @available(iOS, introduced: 4.0)
public static var propertyListReadCorrupt: CocoaError.Code {
return CocoaError.Code(rawValue: 3840)
}
@available(OSX, introduced: 10.6) @available(iOS, introduced: 4.0)
public static var propertyListReadUnknownVersion: CocoaError.Code {
return CocoaError.Code(rawValue: 3841)
}
@available(OSX, introduced: 10.6) @available(iOS, introduced: 4.0)
public static var propertyListReadStream: CocoaError.Code {
return CocoaError.Code(rawValue: 3842)
}
@available(OSX, introduced: 10.6) @available(iOS, introduced: 4.0)
public static var propertyListWriteStream: CocoaError.Code {
return CocoaError.Code(rawValue: 3851)
}
@available(OSX, introduced: 10.10) @available(iOS, introduced: 8.0)
public static var propertyListWriteInvalid: CocoaError.Code {
return CocoaError.Code(rawValue: 3852)
}
@available(OSX, introduced: 10.8) @available(iOS, introduced: 6.0)
public static var xpcConnectionInterrupted: CocoaError.Code {
return CocoaError.Code(rawValue: 4097)
}
@available(OSX, introduced: 10.8) @available(iOS, introduced: 6.0)
public static var xpcConnectionInvalid: CocoaError.Code {
return CocoaError.Code(rawValue: 4099)
}
@available(OSX, introduced: 10.8) @available(iOS, introduced: 6.0)
public static var xpcConnectionReplyInvalid: CocoaError.Code {
return CocoaError.Code(rawValue: 4101)
}
@available(OSX, introduced: 10.9) @available(iOS, introduced: 7.0)
public static var ubiquitousFileUnavailable: CocoaError.Code {
return CocoaError.Code(rawValue: 4353)
}
@available(OSX, introduced: 10.9) @available(iOS, introduced: 7.0)
public static var ubiquitousFileNotUploadedDueToQuota: CocoaError.Code {
return CocoaError.Code(rawValue: 4354)
}
@available(OSX, introduced: 10.9) @available(iOS, introduced: 7.0)
public static var ubiquitousFileUbiquityServerNotAvailable: CocoaError.Code {
return CocoaError.Code(rawValue: 4355)
}
@available(OSX, introduced: 10.10) @available(iOS, introduced: 8.0)
public static var userActivityHandoffFailed: CocoaError.Code {
return CocoaError.Code(rawValue: 4608)
}
@available(OSX, introduced: 10.10) @available(iOS, introduced: 8.0)
public static var userActivityConnectionUnavailable: CocoaError.Code {
return CocoaError.Code(rawValue: 4609)
}
@available(OSX, introduced: 10.10) @available(iOS, introduced: 8.0)
public static var userActivityRemoteApplicationTimedOut: CocoaError.Code {
return CocoaError.Code(rawValue: 4610)
}
@available(OSX, introduced: 10.10) @available(iOS, introduced: 8.0)
public static var userActivityHandoffUserInfoTooLarge: CocoaError.Code {
return CocoaError.Code(rawValue: 4611)
}
@available(OSX, introduced: 10.11) @available(iOS, introduced: 9.0)
public static var coderReadCorrupt: CocoaError.Code {
return CocoaError.Code(rawValue: 4864)
}
@available(OSX, introduced: 10.11) @available(iOS, introduced: 9.0)
public static var coderValueNotFound: CocoaError.Code {
return CocoaError.Code(rawValue: 4865)
}
public static var coderInvalidValue: CocoaError.Code {
return CocoaError.Code(rawValue: 4866)
}
}
extension CocoaError {
@available(*, deprecated, renamed: "fileNoSuchFile")
public static var fileNoSuchFileError: CocoaError.Code {
return CocoaError.Code(rawValue: 4)
}
@available(*, deprecated, renamed: "fileLocking")
public static var fileLockingError: CocoaError.Code {
return CocoaError.Code(rawValue: 255)
}
@available(*, deprecated, renamed: "fileReadUnknown")
public static var fileReadUnknownError: CocoaError.Code {
return CocoaError.Code(rawValue: 256)
}
@available(*, deprecated, renamed: "fileReadNoPermission")
public static var fileReadNoPermissionError: CocoaError.Code {
return CocoaError.Code(rawValue: 257)
}
@available(*, deprecated, renamed: "fileReadInvalidFileName")
public static var fileReadInvalidFileNameError: CocoaError.Code {
return CocoaError.Code(rawValue: 258)
}
@available(*, deprecated, renamed: "fileReadCorruptFile")
public static var fileReadCorruptFileError: CocoaError.Code {
return CocoaError.Code(rawValue: 259)
}
@available(*, deprecated, renamed: "fileReadNoSuchFile")
public static var fileReadNoSuchFileError: CocoaError.Code {
return CocoaError.Code(rawValue: 260)
}
@available(*, deprecated, renamed: "fileReadInapplicableStringEncoding")
public static var fileReadInapplicableStringEncodingError: CocoaError.Code {
return CocoaError.Code(rawValue: 261)
}
@available(*, deprecated, renamed: "fileReadUnsupportedScheme")
public static var fileReadUnsupportedSchemeError: CocoaError.Code {
return CocoaError.Code(rawValue: 262)
}
@available(OSX, introduced: 10.5) @available(iOS, introduced: 2.0)
@available(*, deprecated, renamed: "fileReadTooLarge")
public static var fileReadTooLargeError: CocoaError.Code {
return CocoaError.Code(rawValue: 263)
}
@available(OSX, introduced: 10.5) @available(iOS, introduced: 2.0)
@available(*, deprecated, renamed: "fileReadUnknownStringEncoding")
public static var fileReadUnknownStringEncodingError: CocoaError.Code {
return CocoaError.Code(rawValue: 264)
}
@available(*, deprecated, renamed: "fileWriteUnknown")
public static var fileWriteUnknownError: CocoaError.Code {
return CocoaError.Code(rawValue: 512)
}
@available(*, deprecated, renamed: "fileWriteNoPermission")
public static var fileWriteNoPermissionError: CocoaError.Code {
return CocoaError.Code(rawValue: 513)
}
@available(*, deprecated, renamed: "fileWriteInvalidFileName")
public static var fileWriteInvalidFileNameError: CocoaError.Code {
return CocoaError.Code(rawValue: 514)
}
@available(OSX, introduced: 10.7) @available(iOS, introduced: 5.0)
@available(*, deprecated, renamed: "fileWriteFileExists")
public static var fileWriteFileExistsError: CocoaError.Code {
return CocoaError.Code(rawValue: 516)
}
@available(*, deprecated, renamed: "fileWriteInapplicableStringEncoding")
public static var fileWriteInapplicableStringEncodingError: CocoaError.Code {
return CocoaError.Code(rawValue: 517)
}
@available(*, deprecated, renamed: "fileWriteUnsupportedScheme")
public static var fileWriteUnsupportedSchemeError: CocoaError.Code {
return CocoaError.Code(rawValue: 518)
}
@available(*, deprecated, renamed: "fileWriteOutOfSpace")
public static var fileWriteOutOfSpaceError: CocoaError.Code {
return CocoaError.Code(rawValue: 640)
}
@available(OSX, introduced: 10.6) @available(iOS, introduced: 4.0)
@available(*, deprecated, renamed: "fileWriteVolumeReadOnly")
public static var fileWriteVolumeReadOnlyError: CocoaError.Code {
return CocoaError.Code(rawValue: 642)
}
@available(OSX, introduced: 10.11) @available(iOS, unavailable)
@available(*, deprecated, renamed: "fileManagerUnmountUnknown")
public static var fileManagerUnmountUnknownError: CocoaError.Code {
return CocoaError.Code(rawValue: 768)
}
@available(OSX, introduced: 10.11) @available(iOS, unavailable)
@available(*, deprecated, renamed: "fileManagerUnmountBusy")
public static var fileManagerUnmountBusyError: CocoaError.Code {
return CocoaError.Code(rawValue: 769)
}
@available(*, deprecated, renamed: "keyValueValidation")
public static var keyValueValidationError: CocoaError.Code {
return CocoaError.Code(rawValue: 1024)
}
@available(*, deprecated, renamed: "formatting")
public static var formattingError: CocoaError.Code {
return CocoaError.Code(rawValue: 2048)
}
@available(*, deprecated, renamed: "userCancelled")
public static var userCancelledError: CocoaError.Code {
return CocoaError.Code(rawValue: 3072)
}
@available(OSX, introduced: 10.8) @available(iOS, introduced: 6.0)
@available(*, deprecated, renamed: "featureUnsupported")
public static var featureUnsupportedError: CocoaError.Code {
return CocoaError.Code(rawValue: 3328)
}
@available(OSX, introduced: 10.5) @available(iOS, introduced: 2.0)
@available(*, deprecated, renamed: "executableNotLoadable")
public static var executableNotLoadableError: CocoaError.Code {
return CocoaError.Code(rawValue: 3584)
}
@available(OSX, introduced: 10.5) @available(iOS, introduced: 2.0)
@available(*, deprecated, renamed: "executableArchitectureMismatch")
public static var executableArchitectureMismatchError: CocoaError.Code {
return CocoaError.Code(rawValue: 3585)
}
@available(OSX, introduced: 10.5) @available(iOS, introduced: 2.0)
@available(*, deprecated, renamed: "executableRuntimeMismatch")
public static var executableRuntimeMismatchError: CocoaError.Code {
return CocoaError.Code(rawValue: 3586)
}
@available(OSX, introduced: 10.5) @available(iOS, introduced: 2.0)
@available(*, deprecated, renamed: "executableLoad")
public static var executableLoadError: CocoaError.Code {
return CocoaError.Code(rawValue: 3587)
}
@available(OSX, introduced: 10.5) @available(iOS, introduced: 2.0)
@available(*, deprecated, renamed: "executableLink")
public static var executableLinkError: CocoaError.Code {
return CocoaError.Code(rawValue: 3588)
}
@available(OSX, introduced: 10.6) @available(iOS, introduced: 4.0)
@available(*, deprecated, renamed: "propertyListReadCorrupt")
public static var propertyListReadCorruptError: CocoaError.Code {
return CocoaError.Code(rawValue: 3840)
}
@available(OSX, introduced: 10.6) @available(iOS, introduced: 4.0)
@available(*, deprecated, renamed: "propertyListReadUnknownVersion")
public static var propertyListReadUnknownVersionError: CocoaError.Code {
return CocoaError.Code(rawValue: 3841)
}
@available(OSX, introduced: 10.6) @available(iOS, introduced: 4.0)
@available(*, deprecated, renamed: "propertyListReadStream")
public static var propertyListReadStreamError: CocoaError.Code {
return CocoaError.Code(rawValue: 3842)
}
@available(OSX, introduced: 10.6) @available(iOS, introduced: 4.0)
@available(*, deprecated, renamed: "propertyListWriteStream")
public static var propertyListWriteStreamError: CocoaError.Code {
return CocoaError.Code(rawValue: 3851)
}
@available(OSX, introduced: 10.10) @available(iOS, introduced: 8.0)
@available(*, deprecated, renamed: "propertyListWriteInvalid")
public static var propertyListWriteInvalidError: CocoaError.Code {
return CocoaError.Code(rawValue: 3852)
}
@available(OSX, introduced: 10.9) @available(iOS, introduced: 7.0)
@available(*, deprecated, renamed: "ubiquitousFileUnavailable")
public static var ubiquitousFileUnavailableError: CocoaError.Code {
return CocoaError.Code(rawValue: 4353)
}
@available(OSX, introduced: 10.9) @available(iOS, introduced: 7.0)
@available(*, deprecated, renamed: "ubiquitousFileNotUploadedDueToQuota")
public static var ubiquitousFileNotUploadedDueToQuotaError: CocoaError.Code {
return CocoaError.Code(rawValue: 4354)
}
@available(OSX, introduced: 10.10) @available(iOS, introduced: 8.0)
@available(*, deprecated, renamed: "userActivityHandoffFailed")
public static var userActivityHandoffFailedError: CocoaError.Code {
return CocoaError.Code(rawValue: 4608)
}
@available(OSX, introduced: 10.10) @available(iOS, introduced: 8.0)
@available(*, deprecated, renamed: "userActivityConnectionUnavailable")
public static var userActivityConnectionUnavailableError: CocoaError.Code {
return CocoaError.Code(rawValue: 4609)
}
@available(OSX, introduced: 10.10) @available(iOS, introduced: 8.0)
@available(*, deprecated, renamed: "userActivityRemoteApplicationTimedOut")
public static var userActivityRemoteApplicationTimedOutError: CocoaError.Code {
return CocoaError.Code(rawValue: 4610)
}
@available(OSX, introduced: 10.10) @available(iOS, introduced: 8.0)
@available(*, deprecated, renamed: "userActivityHandoffUserInfoTooLarge")
public static var userActivityHandoffUserInfoTooLargeError: CocoaError.Code {
return CocoaError.Code(rawValue: 4611)
}
@available(OSX, introduced: 10.11) @available(iOS, introduced: 9.0)
@available(*, deprecated, renamed: "coderReadCorrupt")
public static var coderReadCorruptError: CocoaError.Code {
return CocoaError.Code(rawValue: 4864)
}
@available(OSX, introduced: 10.11) @available(iOS, introduced: 9.0)
@available(*, deprecated, renamed: "coderValueNotFound")
public static var coderValueNotFoundError: CocoaError.Code {
return CocoaError.Code(rawValue: 4865)
}
}
extension CocoaError {
@available(OSX, introduced: 10.11) @available(iOS, introduced: 9.0)
public var isCoderError: Bool {
return code.rawValue >= 4864 && code.rawValue <= 4991
}
@available(OSX, introduced: 10.5) @available(iOS, introduced: 2.0)
public var isExecutableError: Bool {
return code.rawValue >= 3584 && code.rawValue <= 3839
}
public var isFileError: Bool {
return code.rawValue >= 0 && code.rawValue <= 1023
}
public var isFormattingError: Bool {
return code.rawValue >= 2048 && code.rawValue <= 2559
}
@available(OSX, introduced: 10.6) @available(iOS, introduced: 4.0)
public var isPropertyListError: Bool {
return code.rawValue >= 3840 && code.rawValue <= 4095
}
@available(OSX, introduced: 10.9) @available(iOS, introduced: 7.0)
public var isUbiquitousFileError: Bool {
return code.rawValue >= 4352 && code.rawValue <= 4607
}
@available(OSX, introduced: 10.10) @available(iOS, introduced: 8.0)
public var isUserActivityError: Bool {
return code.rawValue >= 4608 && code.rawValue <= 4863
}
public var isValidationError: Bool {
return code.rawValue >= 1024 && code.rawValue <= 2047
}
@available(OSX, introduced: 10.8) @available(iOS, introduced: 6.0)
public var isXPCConnectionError: Bool {
return code.rawValue >= 4096 && code.rawValue <= 4224
}
}
extension CocoaError.Code {
@available(*, unavailable, renamed: "fileNoSuchFile")
public static var FileNoSuchFileError: CocoaError.Code {
fatalError("unavailable accessor can't be called")
}
@available(*, unavailable, renamed: "fileLocking")
public static var FileLockingError: CocoaError.Code {
fatalError("unavailable accessor can't be called")
}
@available(*, unavailable, renamed: "fileReadUnknown")
public static var FileReadUnknownError: CocoaError.Code {
fatalError("unavailable accessor can't be called")
}
@available(*, unavailable, renamed: "fileReadNoPermission")
public static var FileReadNoPermissionError: CocoaError.Code {
fatalError("unavailable accessor can't be called")
}
@available(*, unavailable, renamed: "fileReadInvalidFileName")
public static var FileReadInvalidFileNameError: CocoaError.Code {
fatalError("unavailable accessor can't be called")
}
@available(*, unavailable, renamed: "fileReadCorruptFile")
public static var FileReadCorruptFileError: CocoaError.Code {
fatalError("unavailable accessor can't be called")
}
@available(*, unavailable, renamed: "fileReadNoSuchFile")
public static var FileReadNoSuchFileError: CocoaError.Code {
fatalError("unavailable accessor can't be called")
}
@available(*, unavailable, renamed: "fileReadInapplicableStringEncoding")
public static var FileReadInapplicableStringEncodingError: CocoaError.Code {
fatalError("unavailable accessor can't be called")
}
@available(*, unavailable, renamed: "fileReadUnsupportedScheme")
public static var FileReadUnsupportedSchemeError: CocoaError.Code {
fatalError("unavailable accessor can't be called")
}
@available(*, unavailable, renamed: "fileReadTooLarge")
public static var FileReadTooLargeError: CocoaError.Code {
fatalError("unavailable accessor can't be called")
}
@available(*, unavailable, renamed: "fileReadUnknownStringEncoding")
public static var FileReadUnknownStringEncodingError: CocoaError.Code {
fatalError("unavailable accessor can't be called")
}
@available(*, unavailable, renamed: "fileWriteUnknown")
public static var FileWriteUnknownError: CocoaError.Code {
fatalError("unavailable accessor can't be called")
}
@available(*, unavailable, renamed: "fileWriteNoPermission")
public static var FileWriteNoPermissionError: CocoaError.Code {
fatalError("unavailable accessor can't be called")
}
@available(*, unavailable, renamed: "fileWriteInvalidFileName")
public static var FileWriteInvalidFileNameError: CocoaError.Code {
fatalError("unavailable accessor can't be called")
}
@available(*, unavailable, renamed: "fileWriteFileExists")
public static var FileWriteFileExistsError: CocoaError.Code {
fatalError("unavailable accessor can't be called")
}
@available(*, unavailable, renamed: "fileWriteInapplicableStringEncoding")
public static var FileWriteInapplicableStringEncodingError: CocoaError.Code {
fatalError("unavailable accessor can't be called")
}
@available(*, unavailable, renamed: "fileWriteUnsupportedScheme")
public static var FileWriteUnsupportedSchemeError: CocoaError.Code {
fatalError("unavailable accessor can't be called")
}
@available(*, unavailable, renamed: "fileWriteOutOfSpace")
public static var FileWriteOutOfSpaceError: CocoaError.Code {
fatalError("unavailable accessor can't be called")
}
@available(*, unavailable, renamed: "fileWriteVolumeReadOnly")
public static var FileWriteVolumeReadOnlyError: CocoaError.Code {
fatalError("unavailable accessor can't be called")
}
@available(*, unavailable, renamed: "fileManagerUnmountUnknown")
public static var FileManagerUnmountUnknownError: CocoaError.Code {
fatalError("unavailable accessor can't be called")
}
@available(*, unavailable, renamed: "fileManagerUnmountBusy")
public static var FileManagerUnmountBusyError: CocoaError.Code {
fatalError("unavailable accessor can't be called")
}
@available(*, unavailable, renamed: "keyValueValidation")
public static var KeyValueValidationError: CocoaError.Code {
fatalError("unavailable accessor can't be called")
}
@available(*, unavailable, renamed: "formatting")
public static var FormattingError: CocoaError.Code {
fatalError("unavailable accessor can't be called")
}
@available(*, unavailable, renamed: "userCancelled")
public static var UserCancelledError: CocoaError.Code {
fatalError("unavailable accessor can't be called")
}
@available(*, unavailable, renamed: "featureUnsupported")
public static var FeatureUnsupportedError: CocoaError.Code {
fatalError("unavailable accessor can't be called")
}
@available(*, unavailable, renamed: "executableNotLoadable")
public static var ExecutableNotLoadableError: CocoaError.Code {
fatalError("unavailable accessor can't be called")
}
@available(*, unavailable, renamed: "executableArchitectureMismatch")
public static var ExecutableArchitectureMismatchError: CocoaError.Code {
fatalError("unavailable accessor can't be called")
}
@available(*, unavailable, renamed: "executableRuntimeMismatch")
public static var ExecutableRuntimeMismatchError: CocoaError.Code {
fatalError("unavailable accessor can't be called")
}
@available(*, unavailable, renamed: "executableLoad")
public static var ExecutableLoadError: CocoaError.Code {
fatalError("unavailable accessor can't be called")
}
@available(*, unavailable, renamed: "executableLink")
public static var ExecutableLinkError: CocoaError.Code {
fatalError("unavailable accessor can't be called")
}
@available(*, unavailable, renamed: "propertyListReadCorrupt")
public static var PropertyListReadCorruptError: CocoaError.Code {
fatalError("unavailable accessor can't be called")
}
@available(*, unavailable, renamed: "propertyListReadUnknownVersion")
public static var PropertyListReadUnknownVersionError: CocoaError.Code {
fatalError("unavailable accessor can't be called")
}
@available(*, unavailable, renamed: "propertyListReadStream")
public static var PropertyListReadStreamError: CocoaError.Code {
fatalError("unavailable accessor can't be called")
}
@available(*, unavailable, renamed: "propertyListWriteStream")
public static var PropertyListWriteStreamError: CocoaError.Code {
fatalError("unavailable accessor can't be called")
}
@available(*, unavailable, renamed: "propertyListWriteInvalid")
public static var PropertyListWriteInvalidError: CocoaError.Code {
fatalError("unavailable accessor can't be called")
}
@available(*, unavailable, renamed: "xpcConnectionInterrupted")
public static var XPCConnectionInterrupted: CocoaError.Code {
fatalError("unavailable accessor can't be called")
}
@available(*, unavailable, renamed: "xpcConnectionInvalid")
public static var XPCConnectionInvalid: CocoaError.Code {
fatalError("unavailable accessor can't be called")
}
@available(*, unavailable, renamed: "xpcConnectionReplyInvalid")
public static var XPCConnectionReplyInvalid: CocoaError.Code {
fatalError("unavailable accessor can't be called")
}
@available(*, unavailable, renamed: "ubiquitousFileUnavailable")
public static var UbiquitousFileUnavailableError: CocoaError.Code {
fatalError("unavailable accessor can't be called")
}
@available(*, unavailable, renamed: "ubiquitousFileNotUploadedDueToQuota")
public static var UbiquitousFileNotUploadedDueToQuotaError: CocoaError.Code {
fatalError("unavailable accessor can't be called")
}
@available(*, unavailable, renamed: "ubiquitousFileUbiquityServerNotAvailable")
public static var UbiquitousFileUbiquityServerNotAvailable: CocoaError.Code {
fatalError("unavailable accessor can't be called")
}
@available(*, unavailable, renamed: "userActivityHandoffFailed")
public static var UserActivityHandoffFailedError: CocoaError.Code {
fatalError("unavailable accessor can't be called")
}
@available(*, unavailable, renamed: "userActivityConnectionUnavailable")
public static var UserActivityConnectionUnavailableError: CocoaError.Code {
fatalError("unavailable accessor can't be called")
}
@available(*, unavailable, renamed: "userActivityRemoteApplicationTimedOut")
public static var UserActivityRemoteApplicationTimedOutError: CocoaError.Code {
fatalError("unavailable accessor can't be called")
}
@available(*, unavailable, renamed: "userActivityHandoffUserInfoTooLarge")
public static var UserActivityHandoffUserInfoTooLargeError: CocoaError.Code {
fatalError("unavailable accessor can't be called")
}
@available(*, unavailable, renamed: "coderReadCorrupt")
public static var CoderReadCorruptError: CocoaError.Code {
fatalError("unavailable accessor can't be called")
}
@available(*, unavailable, renamed: "coderValueNotFound")
public static var CoderValueNotFoundError: CocoaError.Code {
fatalError("unavailable accessor can't be called")
}
}
/// Describes errors in the URL error domain.
public struct URLError : _BridgedStoredNSError {
public let _nsError: NSError
public init(_nsError error: NSError) {
precondition(error.domain == NSURLErrorDomain)
self._nsError = error
}
public static var _nsErrorDomain: String { return NSURLErrorDomain }
/// The error code itself.
public struct Code : RawRepresentable, Hashable, _ErrorCodeProtocol {
public typealias _ErrorType = URLError
public let rawValue: Int
public init(rawValue: Int) {
self.rawValue = rawValue
}
public var hashValue: Int {
return self.rawValue
}
}
}
public extension URLError.Code {
public static var unknown: URLError.Code {
return URLError.Code(rawValue: -1)
}
public static var cancelled: URLError.Code {
return URLError.Code(rawValue: -999)
}
public static var badURL: URLError.Code {
return URLError.Code(rawValue: -1000)
}
public static var timedOut: URLError.Code {
return URLError.Code(rawValue: -1001)
}
public static var unsupportedURL: URLError.Code {
return URLError.Code(rawValue: -1002)
}
public static var cannotFindHost: URLError.Code {
return URLError.Code(rawValue: -1003)
}
public static var cannotConnectToHost: URLError.Code {
return URLError.Code(rawValue: -1004)
}
public static var networkConnectionLost: URLError.Code {
return URLError.Code(rawValue: -1005)
}
public static var dnsLookupFailed: URLError.Code {
return URLError.Code(rawValue: -1006)
}
public static var httpTooManyRedirects: URLError.Code {
return URLError.Code(rawValue: -1007)
}
public static var resourceUnavailable: URLError.Code {
return URLError.Code(rawValue: -1008)
}
public static var notConnectedToInternet: URLError.Code {
return URLError.Code(rawValue: -1009)
}
public static var redirectToNonExistentLocation: URLError.Code {
return URLError.Code(rawValue: -1010)
}
public static var badServerResponse: URLError.Code {
return URLError.Code(rawValue: -1011)
}
public static var userCancelledAuthentication: URLError.Code {
return URLError.Code(rawValue: -1012)
}
public static var userAuthenticationRequired: URLError.Code {
return URLError.Code(rawValue: -1013)
}
public static var zeroByteResource: URLError.Code {
return URLError.Code(rawValue: -1014)
}
public static var cannotDecodeRawData: URLError.Code {
return URLError.Code(rawValue: -1015)
}
public static var cannotDecodeContentData: URLError.Code {
return URLError.Code(rawValue: -1016)
}
public static var cannotParseResponse: URLError.Code {
return URLError.Code(rawValue: -1017)
}
@available(OSX, introduced: 10.11) @available(iOS, introduced: 9.0)
public static var appTransportSecurityRequiresSecureConnection: URLError.Code {
return URLError.Code(rawValue: -1022)
}
public static var fileDoesNotExist: URLError.Code {
return URLError.Code(rawValue: -1100)
}
public static var fileIsDirectory: URLError.Code {
return URLError.Code(rawValue: -1101)
}
public static var noPermissionsToReadFile: URLError.Code {
return URLError.Code(rawValue: -1102)
}
@available(OSX, introduced: 10.5) @available(iOS, introduced: 2.0)
public static var dataLengthExceedsMaximum: URLError.Code {
return URLError.Code(rawValue: -1103)
}
public static var secureConnectionFailed: URLError.Code {
return URLError.Code(rawValue: -1200)
}
public static var serverCertificateHasBadDate: URLError.Code {
return URLError.Code(rawValue: -1201)
}
public static var serverCertificateUntrusted: URLError.Code {
return URLError.Code(rawValue: -1202)
}
public static var serverCertificateHasUnknownRoot: URLError.Code {
return URLError.Code(rawValue: -1203)
}
public static var serverCertificateNotYetValid: URLError.Code {
return URLError.Code(rawValue: -1204)
}
public static var clientCertificateRejected: URLError.Code {
return URLError.Code(rawValue: -1205)
}
public static var clientCertificateRequired: URLError.Code {
return URLError.Code(rawValue: -1206)
}
public static var cannotLoadFromNetwork: URLError.Code {
return URLError.Code(rawValue: -2000)
}
public static var cannotCreateFile: URLError.Code {
return URLError.Code(rawValue: -3000)
}
public static var cannotOpenFile: URLError.Code {
return URLError.Code(rawValue: -3001)
}
public static var cannotCloseFile: URLError.Code {
return URLError.Code(rawValue: -3002)
}
public static var cannotWriteToFile: URLError.Code {
return URLError.Code(rawValue: -3003)
}
public static var cannotRemoveFile: URLError.Code {
return URLError.Code(rawValue: -3004)
}
public static var cannotMoveFile: URLError.Code {
return URLError.Code(rawValue: -3005)
}
public static var downloadDecodingFailedMidStream: URLError.Code {
return URLError.Code(rawValue: -3006)
}
public static var downloadDecodingFailedToComplete: URLError.Code {
return URLError.Code(rawValue: -3007)
}
@available(OSX, introduced: 10.7) @available(iOS, introduced: 3.0)
public static var internationalRoamingOff: URLError.Code {
return URLError.Code(rawValue: -1018)
}
@available(OSX, introduced: 10.7) @available(iOS, introduced: 3.0)
public static var callIsActive: URLError.Code {
return URLError.Code(rawValue: -1019)
}
@available(OSX, introduced: 10.7) @available(iOS, introduced: 3.0)
public static var dataNotAllowed: URLError.Code {
return URLError.Code(rawValue: -1020)
}
@available(OSX, introduced: 10.7) @available(iOS, introduced: 3.0)
public static var requestBodyStreamExhausted: URLError.Code {
return URLError.Code(rawValue: -1021)
}
@available(OSX, introduced: 10.10) @available(iOS, introduced: 8.0)
public static var backgroundSessionRequiresSharedContainer: URLError.Code {
return URLError.Code(rawValue: -995)
}
@available(OSX, introduced: 10.10) @available(iOS, introduced: 8.0)
public static var backgroundSessionInUseByAnotherProcess: URLError.Code {
return URLError.Code(rawValue: -996)
}
@available(OSX, introduced: 10.10) @available(iOS, introduced: 8.0)
public static var backgroundSessionWasDisconnected: URLError.Code {
return URLError.Code(rawValue: -997)
}
}
public extension URLError {
private var _nsUserInfo: [AnyHashable : Any] {
return (self as NSError).userInfo
}
/// The URL which caused a load to fail.
public var failingURL: URL? {
return _nsUserInfo[NSURLErrorFailingURLErrorKey as NSString] as? URL
}
/// The string for the URL which caused a load to fail.
public var failureURLString: String? {
return _nsUserInfo[NSURLErrorFailingURLStringErrorKey as NSString] as? String
}
/// The state of a failed SSL handshake.
public var failureURLPeerTrust: SecTrust? {
if let secTrust = _nsUserInfo[NSURLErrorFailingURLPeerTrustErrorKey as NSString] {
return (secTrust as! SecTrust)
}
return nil
}
}
public extension URLError {
public static var unknown: URLError.Code {
return .unknown
}
public static var cancelled: URLError.Code {
return .cancelled
}
public static var badURL: URLError.Code {
return .badURL
}
public static var timedOut: URLError.Code {
return .timedOut
}
public static var unsupportedURL: URLError.Code {
return .unsupportedURL
}
public static var cannotFindHost: URLError.Code {
return .cannotFindHost
}
public static var cannotConnectToHost: URLError.Code {
return .cannotConnectToHost
}
public static var networkConnectionLost: URLError.Code {
return .networkConnectionLost
}
public static var dnsLookupFailed: URLError.Code {
return .dnsLookupFailed
}
public static var httpTooManyRedirects: URLError.Code {
return .httpTooManyRedirects
}
public static var resourceUnavailable: URLError.Code {
return .resourceUnavailable
}
public static var notConnectedToInternet: URLError.Code {
return .notConnectedToInternet
}
public static var redirectToNonExistentLocation: URLError.Code {
return .redirectToNonExistentLocation
}
public static var badServerResponse: URLError.Code {
return .badServerResponse
}
public static var userCancelledAuthentication: URLError.Code {
return .userCancelledAuthentication
}
public static var userAuthenticationRequired: URLError.Code {
return .userAuthenticationRequired
}
public static var zeroByteResource: URLError.Code {
return .zeroByteResource
}
public static var cannotDecodeRawData: URLError.Code {
return .cannotDecodeRawData
}
public static var cannotDecodeContentData: URLError.Code {
return .cannotDecodeContentData
}
public static var cannotParseResponse: URLError.Code {
return .cannotParseResponse
}
@available(OSX, introduced: 10.11) @available(iOS, introduced: 9.0)
public static var appTransportSecurityRequiresSecureConnection: URLError.Code {
return .appTransportSecurityRequiresSecureConnection
}
public static var fileDoesNotExist: URLError.Code {
return .fileDoesNotExist
}
public static var fileIsDirectory: URLError.Code {
return .fileIsDirectory
}
public static var noPermissionsToReadFile: URLError.Code {
return .noPermissionsToReadFile
}
@available(OSX, introduced: 10.5) @available(iOS, introduced: 2.0)
public static var dataLengthExceedsMaximum: URLError.Code {
return .dataLengthExceedsMaximum
}
public static var secureConnectionFailed: URLError.Code {
return .secureConnectionFailed
}
public static var serverCertificateHasBadDate: URLError.Code {
return .serverCertificateHasBadDate
}
public static var serverCertificateUntrusted: URLError.Code {
return .serverCertificateUntrusted
}
public static var serverCertificateHasUnknownRoot: URLError.Code {
return .serverCertificateHasUnknownRoot
}
public static var serverCertificateNotYetValid: URLError.Code {
return .serverCertificateNotYetValid
}
public static var clientCertificateRejected: URLError.Code {
return .clientCertificateRejected
}
public static var clientCertificateRequired: URLError.Code {
return .clientCertificateRequired
}
public static var cannotLoadFromNetwork: URLError.Code {
return .cannotLoadFromNetwork
}
public static var cannotCreateFile: URLError.Code {
return .cannotCreateFile
}
public static var cannotOpenFile: URLError.Code {
return .cannotOpenFile
}
public static var cannotCloseFile: URLError.Code {
return .cannotCloseFile
}
public static var cannotWriteToFile: URLError.Code {
return .cannotWriteToFile
}
public static var cannotRemoveFile: URLError.Code {
return .cannotRemoveFile
}
public static var cannotMoveFile: URLError.Code {
return .cannotMoveFile
}
public static var downloadDecodingFailedMidStream: URLError.Code {
return .downloadDecodingFailedMidStream
}
public static var downloadDecodingFailedToComplete: URLError.Code {
return .downloadDecodingFailedToComplete
}
@available(OSX, introduced: 10.7) @available(iOS, introduced: 3.0)
public static var internationalRoamingOff: URLError.Code {
return .internationalRoamingOff
}
@available(OSX, introduced: 10.7) @available(iOS, introduced: 3.0)
public static var callIsActive: URLError.Code {
return .callIsActive
}
@available(OSX, introduced: 10.7) @available(iOS, introduced: 3.0)
public static var dataNotAllowed: URLError.Code {
return .dataNotAllowed
}
@available(OSX, introduced: 10.7) @available(iOS, introduced: 3.0)
public static var requestBodyStreamExhausted: URLError.Code {
return .requestBodyStreamExhausted
}
@available(OSX, introduced: 10.10) @available(iOS, introduced: 8.0)
public static var backgroundSessionRequiresSharedContainer: Code {
return .backgroundSessionRequiresSharedContainer
}
@available(OSX, introduced: 10.10) @available(iOS, introduced: 8.0)
public static var backgroundSessionInUseByAnotherProcess: Code {
return .backgroundSessionInUseByAnotherProcess
}
@available(OSX, introduced: 10.10) @available(iOS, introduced: 8.0)
public static var backgroundSessionWasDisconnected: Code {
return .backgroundSessionWasDisconnected
}
}
extension URLError {
@available(*, unavailable, renamed: "unknown")
public static var Unknown: URLError.Code {
fatalError("unavailable accessor can't be called")
}
@available(*, unavailable, renamed: "cancelled")
public static var Cancelled: URLError.Code {
fatalError("unavailable accessor can't be called")
}
@available(*, unavailable, renamed: "badURL")
public static var BadURL: URLError.Code {
fatalError("unavailable accessor can't be called")
}
@available(*, unavailable, renamed: "timedOut")
public static var TimedOut: URLError.Code {
fatalError("unavailable accessor can't be called")
}
@available(*, unavailable, renamed: "unsupportedURL")
public static var UnsupportedURL: URLError.Code {
fatalError("unavailable accessor can't be called")
}
@available(*, unavailable, renamed: "cannotFindHost")
public static var CannotFindHost: URLError.Code {
fatalError("unavailable accessor can't be called")
}
@available(*, unavailable, renamed: "cannotConnectToHost")
public static var CannotConnectToHost: URLError.Code {
fatalError("unavailable accessor can't be called")
}
@available(*, unavailable, renamed: "networkConnectionLost")
public static var NetworkConnectionLost: URLError.Code {
fatalError("unavailable accessor can't be called")
}
@available(*, unavailable, renamed: "dnsLookupFailed")
public static var DNSLookupFailed: URLError.Code {
fatalError("unavailable accessor can't be called")
}
@available(*, unavailable, renamed: "httpTooManyRedirects")
public static var HTTPTooManyRedirects: URLError.Code {
fatalError("unavailable accessor can't be called")
}
@available(*, unavailable, renamed: "resourceUnavailable")
public static var ResourceUnavailable: URLError.Code {
fatalError("unavailable accessor can't be called")
}
@available(*, unavailable, renamed: "notConnectedToInternet")
public static var NotConnectedToInternet: URLError.Code {
fatalError("unavailable accessor can't be called")
}
@available(*, unavailable, renamed: "redirectToNonExistentLocation")
public static var RedirectToNonExistentLocation: URLError.Code {
fatalError("unavailable accessor can't be called")
}
@available(*, unavailable, renamed: "badServerResponse")
public static var BadServerResponse: URLError.Code {
fatalError("unavailable accessor can't be called")
}
@available(*, unavailable, renamed: "userCancelledAuthentication")
public static var UserCancelledAuthentication: URLError.Code {
fatalError("unavailable accessor can't be called")
}
@available(*, unavailable, renamed: "userAuthenticationRequired")
public static var UserAuthenticationRequired: URLError.Code {
fatalError("unavailable accessor can't be called")
}
@available(*, unavailable, renamed: "zeroByteResource")
public static var ZeroByteResource: URLError.Code {
fatalError("unavailable accessor can't be called")
}
@available(*, unavailable, renamed: "cannotDecodeRawData")
public static var CannotDecodeRawData: URLError.Code {
fatalError("unavailable accessor can't be called")
}
@available(*, unavailable, renamed: "cannotDecodeContentData")
public static var CannotDecodeContentData: URLError.Code {
fatalError("unavailable accessor can't be called")
}
@available(*, unavailable, renamed: "cannotParseResponse")
public static var CannotParseResponse: URLError.Code {
fatalError("unavailable accessor can't be called")
}
@available(*, unavailable, renamed: "appTransportSecurityRequiresSecureConnection")
public static var AppTransportSecurityRequiresSecureConnection: URLError.Code {
fatalError("unavailable accessor can't be called")
}
@available(*, unavailable, renamed: "fileDoesNotExist")
public static var FileDoesNotExist: URLError.Code {
fatalError("unavailable accessor can't be called")
}
@available(*, unavailable, renamed: "fileIsDirectory")
public static var FileIsDirectory: URLError.Code {
fatalError("unavailable accessor can't be called")
}
@available(*, unavailable, renamed: "noPermissionsToReadFile")
public static var NoPermissionsToReadFile: URLError.Code {
fatalError("unavailable accessor can't be called")
}
@available(*, unavailable, renamed: "dataLengthExceedsMaximum")
public static var DataLengthExceedsMaximum: URLError.Code {
fatalError("unavailable accessor can't be called")
}
@available(*, unavailable, renamed: "secureConnectionFailed")
public static var SecureConnectionFailed: URLError.Code {
fatalError("unavailable accessor can't be called")
}
@available(*, unavailable, renamed: "serverCertificateHasBadDate")
public static var ServerCertificateHasBadDate: URLError.Code {
fatalError("unavailable accessor can't be called")
}
@available(*, unavailable, renamed: "serverCertificateUntrusted")
public static var ServerCertificateUntrusted: URLError.Code {
fatalError("unavailable accessor can't be called")
}
@available(*, unavailable, renamed: "serverCertificateHasUnknownRoot")
public static var ServerCertificateHasUnknownRoot: URLError.Code {
fatalError("unavailable accessor can't be called")
}
@available(*, unavailable, renamed: "serverCertificateNotYetValid")
public static var ServerCertificateNotYetValid: URLError.Code {
fatalError("unavailable accessor can't be called")
}
@available(*, unavailable, renamed: "clientCertificateRejected")
public static var ClientCertificateRejected: URLError.Code {
fatalError("unavailable accessor can't be called")
}
@available(*, unavailable, renamed: "clientCertificateRequired")
public static var ClientCertificateRequired: URLError.Code {
fatalError("unavailable accessor can't be called")
}
@available(*, unavailable, renamed: "cannotLoadFromNetwork")
public static var CannotLoadFromNetwork: URLError.Code {
fatalError("unavailable accessor can't be called")
}
@available(*, unavailable, renamed: "cannotCreateFile")
public static var CannotCreateFile: URLError.Code {
fatalError("unavailable accessor can't be called")
}
@available(*, unavailable, renamed: "cannotOpenFile")
public static var CannotOpenFile: URLError.Code {
fatalError("unavailable accessor can't be called")
}
@available(*, unavailable, renamed: "cannotCloseFile")
public static var CannotCloseFile: URLError.Code {
fatalError("unavailable accessor can't be called")
}
@available(*, unavailable, renamed: "cannotWriteToFile")
public static var CannotWriteToFile: URLError.Code {
fatalError("unavailable accessor can't be called")
}
@available(*, unavailable, renamed: "cannotRemoveFile")
public static var CannotRemoveFile: URLError.Code {
fatalError("unavailable accessor can't be called")
}
@available(*, unavailable, renamed: "cannotMoveFile")
public static var CannotMoveFile: URLError.Code {
fatalError("unavailable accessor can't be called")
}
@available(*, unavailable, renamed: "downloadDecodingFailedMidStream")
public static var DownloadDecodingFailedMidStream: URLError.Code {
fatalError("unavailable accessor can't be called")
}
@available(*, unavailable, renamed: "downloadDecodingFailedToComplete")
public static var DownloadDecodingFailedToComplete: URLError.Code {
fatalError("unavailable accessor can't be called")
}
@available(*, unavailable, renamed: "internationalRoamingOff")
public static var InternationalRoamingOff: URLError.Code {
fatalError("unavailable accessor can't be called")
}
@available(*, unavailable, renamed: "callIsActive")
public static var CallIsActive: URLError.Code {
fatalError("unavailable accessor can't be called")
}
@available(*, unavailable, renamed: "dataNotAllowed")
public static var DataNotAllowed: URLError.Code {
fatalError("unavailable accessor can't be called")
}
@available(*, unavailable, renamed: "requestBodyStreamExhausted")
public static var RequestBodyStreamExhausted: URLError.Code {
fatalError("unavailable accessor can't be called")
}
@available(*, unavailable, renamed: "backgroundSessionRequiresSharedContainer")
public static var BackgroundSessionRequiresSharedContainer: URLError.Code {
fatalError("unavailable accessor can't be called")
}
@available(*, unavailable, renamed: "backgroundSessionInUseByAnotherProcess")
public static var BackgroundSessionInUseByAnotherProcess: URLError.Code {
fatalError("unavailable accessor can't be called")
}
@available(*, unavailable, renamed: "backgroundSessionWasDisconnected")
public static var BackgroundSessionWasDisconnected: URLError.Code {
fatalError("unavailable accessor can't be called")
}
}
/// Describes an error in the POSIX error domain.
public struct POSIXError : _BridgedStoredNSError {
public let _nsError: NSError
public init(_nsError error: NSError) {
precondition(error.domain == NSPOSIXErrorDomain)
self._nsError = error
}
public static var _nsErrorDomain: String { return NSPOSIXErrorDomain }
public typealias Code = POSIXErrorCode
}
extension POSIXErrorCode : _ErrorCodeProtocol {
public typealias _ErrorType = POSIXError
}
extension POSIXError {
public static var EPERM: POSIXErrorCode {
return .EPERM
}
/// No such file or directory.
public static var ENOENT: POSIXErrorCode {
return .ENOENT
}
/// No such process.
public static var ESRCH: POSIXErrorCode {
return .ESRCH
}
/// Interrupted system call.
public static var EINTR: POSIXErrorCode {
return .EINTR
}
/// Input/output error.
public static var EIO: POSIXErrorCode {
return .EIO
}
/// Device not configured.
public static var ENXIO: POSIXErrorCode {
return .ENXIO
}
/// Argument list too long.
public static var E2BIG: POSIXErrorCode {
return .E2BIG
}
/// Exec format error.
public static var ENOEXEC: POSIXErrorCode {
return .ENOEXEC
}
/// Bad file descriptor.
public static var EBADF: POSIXErrorCode {
return .EBADF
}
/// No child processes.
public static var ECHILD: POSIXErrorCode {
return .ECHILD
}
/// Resource deadlock avoided.
public static var EDEADLK: POSIXErrorCode {
return .EDEADLK
}
/// Cannot allocate memory.
public static var ENOMEM: POSIXErrorCode {
return .ENOMEM
}
/// Permission denied.
public static var EACCES: POSIXErrorCode {
return .EACCES
}
/// Bad address.
public static var EFAULT: POSIXErrorCode {
return .EFAULT
}
/// Block device required.
public static var ENOTBLK: POSIXErrorCode {
return .ENOTBLK
}
/// Device / Resource busy.
public static var EBUSY: POSIXErrorCode {
return .EBUSY
}
/// File exists.
public static var EEXIST: POSIXErrorCode {
return .EEXIST
}
/// Cross-device link.
public static var EXDEV: POSIXErrorCode {
return .EXDEV
}
/// Operation not supported by device.
public static var ENODEV: POSIXErrorCode {
return .ENODEV
}
/// Not a directory.
public static var ENOTDIR: POSIXErrorCode {
return .ENOTDIR
}
/// Is a directory.
public static var EISDIR: POSIXErrorCode {
return .EISDIR
}
/// Invalid argument.
public static var EINVAL: POSIXErrorCode {
return .EINVAL
}
/// Too many open files in system.
public static var ENFILE: POSIXErrorCode {
return .ENFILE
}
/// Too many open files.
public static var EMFILE: POSIXErrorCode {
return .EMFILE
}
/// Inappropriate ioctl for device.
public static var ENOTTY: POSIXErrorCode {
return .ENOTTY
}
/// Text file busy.
public static var ETXTBSY: POSIXErrorCode {
return .ETXTBSY
}
/// File too large.
public static var EFBIG: POSIXErrorCode {
return .EFBIG
}
/// No space left on device.
public static var ENOSPC: POSIXErrorCode {
return .ENOSPC
}
/// Illegal seek.
public static var ESPIPE: POSIXErrorCode {
return .ESPIPE
}
/// Read-only file system.
public static var EROFS: POSIXErrorCode {
return .EROFS
}
/// Too many links.
public static var EMLINK: POSIXErrorCode {
return .EMLINK
}
/// Broken pipe.
public static var EPIPE: POSIXErrorCode {
return .EPIPE
}
/// math software.
/// Numerical argument out of domain.
public static var EDOM: POSIXErrorCode {
return .EDOM
}
/// Result too large.
public static var ERANGE: POSIXErrorCode {
return .ERANGE
}
/// non-blocking and interrupt i/o.
/// Resource temporarily unavailable.
public static var EAGAIN: POSIXErrorCode {
return .EAGAIN
}
/// Operation would block.
public static var EWOULDBLOCK: POSIXErrorCode {
return .EWOULDBLOCK
}
/// Operation now in progress.
public static var EINPROGRESS: POSIXErrorCode {
return .EINPROGRESS
}
/// Operation already in progress.
public static var EALREADY: POSIXErrorCode {
return .EALREADY
}
/// ipc/network software -- argument errors.
/// Socket operation on non-socket.
public static var ENOTSOCK: POSIXErrorCode {
return .ENOTSOCK
}
/// Destination address required.
public static var EDESTADDRREQ: POSIXErrorCode {
return .EDESTADDRREQ
}
/// Message too long.
public static var EMSGSIZE: POSIXErrorCode {
return .EMSGSIZE
}
/// Protocol wrong type for socket.
public static var EPROTOTYPE: POSIXErrorCode {
return .EPROTOTYPE
}
/// Protocol not available.
public static var ENOPROTOOPT: POSIXErrorCode {
return .ENOPROTOOPT
}
/// Protocol not supported.
public static var EPROTONOSUPPORT: POSIXErrorCode {
return .EPROTONOSUPPORT
}
/// Socket type not supported.
public static var ESOCKTNOSUPPORT: POSIXErrorCode {
return .ESOCKTNOSUPPORT
}
/// Operation not supported.
public static var ENOTSUP: POSIXErrorCode {
return .ENOTSUP
}
/// Protocol family not supported.
public static var EPFNOSUPPORT: POSIXErrorCode {
return .EPFNOSUPPORT
}
/// Address family not supported by protocol family.
public static var EAFNOSUPPORT: POSIXErrorCode {
return .EAFNOSUPPORT
}
/// Address already in use.
public static var EADDRINUSE: POSIXErrorCode {
return .EADDRINUSE
}
/// Can't assign requested address.
public static var EADDRNOTAVAIL: POSIXErrorCode {
return .EADDRNOTAVAIL
}
/// ipc/network software -- operational errors
/// Network is down.
public static var ENETDOWN: POSIXErrorCode {
return .ENETDOWN
}
/// Network is unreachable.
public static var ENETUNREACH: POSIXErrorCode {
return .ENETUNREACH
}
/// Network dropped connection on reset.
public static var ENETRESET: POSIXErrorCode {
return .ENETRESET
}
/// Software caused connection abort.
public static var ECONNABORTED: POSIXErrorCode {
return .ECONNABORTED
}
/// Connection reset by peer.
public static var ECONNRESET: POSIXErrorCode {
return .ECONNRESET
}
/// No buffer space available.
public static var ENOBUFS: POSIXErrorCode {
return .ENOBUFS
}
/// Socket is already connected.
public static var EISCONN: POSIXErrorCode {
return .EISCONN
}
/// Socket is not connected.
public static var ENOTCONN: POSIXErrorCode {
return .ENOTCONN
}
/// Can't send after socket shutdown.
public static var ESHUTDOWN: POSIXErrorCode {
return .ESHUTDOWN
}
/// Too many references: can't splice.
public static var ETOOMANYREFS: POSIXErrorCode {
return .ETOOMANYREFS
}
/// Operation timed out.
public static var ETIMEDOUT: POSIXErrorCode {
return .ETIMEDOUT
}
/// Connection refused.
public static var ECONNREFUSED: POSIXErrorCode {
return .ECONNREFUSED
}
/// Too many levels of symbolic links.
public static var ELOOP: POSIXErrorCode {
return .ELOOP
}
/// File name too long.
public static var ENAMETOOLONG: POSIXErrorCode {
return .ENAMETOOLONG
}
/// Host is down.
public static var EHOSTDOWN: POSIXErrorCode {
return .EHOSTDOWN
}
/// No route to host.
public static var EHOSTUNREACH: POSIXErrorCode {
return .EHOSTUNREACH
}
/// Directory not empty.
public static var ENOTEMPTY: POSIXErrorCode {
return .ENOTEMPTY
}
/// quotas & mush.
/// Too many processes.
public static var EPROCLIM: POSIXErrorCode {
return .EPROCLIM
}
/// Too many users.
public static var EUSERS: POSIXErrorCode {
return .EUSERS
}
/// Disc quota exceeded.
public static var EDQUOT: POSIXErrorCode {
return .EDQUOT
}
/// Network File System.
/// Stale NFS file handle.
public static var ESTALE: POSIXErrorCode {
return .ESTALE
}
/// Too many levels of remote in path.
public static var EREMOTE: POSIXErrorCode {
return .EREMOTE
}
/// RPC struct is bad.
public static var EBADRPC: POSIXErrorCode {
return .EBADRPC
}
/// RPC version wrong.
public static var ERPCMISMATCH: POSIXErrorCode {
return .ERPCMISMATCH
}
/// RPC prog. not avail.
public static var EPROGUNAVAIL: POSIXErrorCode {
return .EPROGUNAVAIL
}
/// Program version wrong.
public static var EPROGMISMATCH: POSIXErrorCode {
return .EPROGMISMATCH
}
/// Bad procedure for program.
public static var EPROCUNAVAIL: POSIXErrorCode {
return .EPROCUNAVAIL
}
/// No locks available.
public static var ENOLCK: POSIXErrorCode {
return .ENOLCK
}
/// Function not implemented.
public static var ENOSYS: POSIXErrorCode {
return .ENOSYS
}
/// Inappropriate file type or format.
public static var EFTYPE: POSIXErrorCode {
return .EFTYPE
}
/// Authentication error.
public static var EAUTH: POSIXErrorCode {
return .EAUTH
}
/// Need authenticator.
public static var ENEEDAUTH: POSIXErrorCode {
return .ENEEDAUTH
}
/// Intelligent device errors.
/// Device power is off.
public static var EPWROFF: POSIXErrorCode {
return .EPWROFF
}
/// Device error, e.g. paper out.
public static var EDEVERR: POSIXErrorCode {
return .EDEVERR
}
/// Value too large to be stored in data type.
public static var EOVERFLOW: POSIXErrorCode {
return .EOVERFLOW
}
/// Program loading errors.
/// Bad executable.
public static var EBADEXEC: POSIXErrorCode {
return .EBADEXEC
}
/// Bad CPU type in executable.
public static var EBADARCH: POSIXErrorCode {
return .EBADARCH
}
/// Shared library version mismatch.
public static var ESHLIBVERS: POSIXErrorCode {
return .ESHLIBVERS
}
/// Malformed Macho file.
public static var EBADMACHO: POSIXErrorCode {
return .EBADMACHO
}
/// Operation canceled.
public static var ECANCELED: POSIXErrorCode {
return .ECANCELED
}
/// Identifier removed.
public static var EIDRM: POSIXErrorCode {
return .EIDRM
}
/// No message of desired type.
public static var ENOMSG: POSIXErrorCode {
return .ENOMSG
}
/// Illegal byte sequence.
public static var EILSEQ: POSIXErrorCode {
return .EILSEQ
}
/// Attribute not found.
public static var ENOATTR: POSIXErrorCode {
return .ENOATTR
}
/// Bad message.
public static var EBADMSG: POSIXErrorCode {
return .EBADMSG
}
/// Reserved.
public static var EMULTIHOP: POSIXErrorCode {
return .EMULTIHOP
}
/// No message available on STREAM.
public static var ENODATA: POSIXErrorCode {
return .ENODATA
}
/// Reserved.
public static var ENOLINK: POSIXErrorCode {
return .ENOLINK
}
/// No STREAM resources.
public static var ENOSR: POSIXErrorCode {
return .ENOSR
}
/// Not a STREAM.
public static var ENOSTR: POSIXErrorCode {
return .ENOSTR
}
/// Protocol error.
public static var EPROTO: POSIXErrorCode {
return .EPROTO
}
/// STREAM ioctl timeout.
public static var ETIME: POSIXErrorCode {
return .ETIME
}
/// No such policy registered.
public static var ENOPOLICY: POSIXErrorCode {
return .ENOPOLICY
}
/// State not recoverable.
public static var ENOTRECOVERABLE: POSIXErrorCode {
return .ENOTRECOVERABLE
}
/// Previous owner died.
public static var EOWNERDEAD: POSIXErrorCode {
return .EOWNERDEAD
}
/// Interface output queue is full.
public static var EQFULL: POSIXErrorCode {
return .EQFULL
}
}
/// Describes an error in the Mach error domain.
public struct MachError : _BridgedStoredNSError {
public let _nsError: NSError
public init(_nsError error: NSError) {
precondition(error.domain == NSMachErrorDomain)
self._nsError = error
}
public static var _nsErrorDomain: String { return NSMachErrorDomain }
public typealias Code = MachErrorCode
}
extension MachErrorCode : _ErrorCodeProtocol {
public typealias _ErrorType = MachError
}
extension MachError {
public static var success: MachError.Code {
return .success
}
/// Specified address is not currently valid.
public static var invalidAddress: MachError.Code {
return .invalidAddress
}
/// Specified memory is valid, but does not permit the required
/// forms of access.
public static var protectionFailure: MachError.Code {
return .protectionFailure
}
/// The address range specified is already in use, or no address
/// range of the size specified could be found.
public static var noSpace: MachError.Code {
return .noSpace
}
/// The function requested was not applicable to this type of
/// argument, or an argument is invalid.
public static var invalidArgument: MachError.Code {
return .invalidArgument
}
/// The function could not be performed. A catch-all.
public static var failure: MachError.Code {
return .failure
}
/// A system resource could not be allocated to fulfill this
/// request. This failure may not be permanent.
public static var resourceShortage: MachError.Code {
return .resourceShortage
}
/// The task in question does not hold receive rights for the port
/// argument.
public static var notReceiver: MachError.Code {
return .notReceiver
}
/// Bogus access restriction.
public static var noAccess: MachError.Code {
return .noAccess
}
/// During a page fault, the target address refers to a memory
/// object that has been destroyed. This failure is permanent.
public static var memoryFailure: MachError.Code {
return .memoryFailure
}
/// During a page fault, the memory object indicated that the data
/// could not be returned. This failure may be temporary; future
/// attempts to access this same data may succeed, as defined by the
/// memory object.
public static var memoryError: MachError.Code {
return .memoryError
}
/// The receive right is already a member of the portset.
public static var alreadyInSet: MachError.Code {
return .alreadyInSet
}
/// The receive right is not a member of a port set.
public static var notInSet: MachError.Code {
return .notInSet
}
/// The name already denotes a right in the task.
public static var nameExists: MachError.Code {
return .nameExists
}
/// The operation was aborted. Ipc code will catch this and reflect
/// it as a message error.
public static var aborted: MachError.Code {
return .aborted
}
/// The name doesn't denote a right in the task.
public static var invalidName: MachError.Code {
return .invalidName
}
/// Target task isn't an active task.
public static var invalidTask: MachError.Code {
return .invalidTask
}
/// The name denotes a right, but not an appropriate right.
public static var invalidRight: MachError.Code {
return .invalidRight
}
/// A blatant range error.
public static var invalidValue: MachError.Code {
return .invalidValue
}
/// Operation would overflow limit on user-references.
public static var userReferencesOverflow: MachError.Code {
return .userReferencesOverflow
}
/// The supplied (port) capability is improper.
public static var invalidCapability: MachError.Code {
return .invalidCapability
}
/// The task already has send or receive rights for the port under
/// another name.
public static var rightExists: MachError.Code {
return .rightExists
}
/// Target host isn't actually a host.
public static var invalidHost: MachError.Code {
return .invalidHost
}
/// An attempt was made to supply "precious" data for memory that is
/// already present in a memory object.
public static var memoryPresent: MachError.Code {
return .memoryPresent
}
/// A page was requested of a memory manager via
/// memory_object_data_request for an object using a
/// MEMORY_OBJECT_COPY_CALL strategy, with the VM_PROT_WANTS_COPY
/// flag being used to specify that the page desired is for a copy
/// of the object, and the memory manager has detected the page was
/// pushed into a copy of the object while the kernel was walking
/// the shadow chain from the copy to the object. This error code is
/// delivered via memory_object_data_error and is handled by the
/// kernel (it forces the kernel to restart the fault). It will not
/// be seen by users.
public static var memoryDataMoved: MachError.Code {
return .memoryDataMoved
}
/// A strategic copy was attempted of an object upon which a quicker
/// copy is now possible. The caller should retry the copy using
/// vm_object_copy_quickly. This error code is seen only by the
/// kernel.
public static var memoryRestartCopy: MachError.Code {
return .memoryRestartCopy
}
/// An argument applied to assert processor set privilege was not a
/// processor set control port.
public static var invalidProcessorSet: MachError.Code {
return .invalidProcessorSet
}
/// The specified scheduling attributes exceed the thread's limits.
public static var policyLimit: MachError.Code {
return .policyLimit
}
/// The specified scheduling policy is not currently enabled for the
/// processor set.
public static var invalidPolicy: MachError.Code {
return .invalidPolicy
}
/// The external memory manager failed to initialize the memory object.
public static var invalidObject: MachError.Code {
return .invalidObject
}
/// A thread is attempting to wait for an event for which there is
/// already a waiting thread.
public static var alreadyWaiting: MachError.Code {
return .alreadyWaiting
}
/// An attempt was made to destroy the default processor set.
public static var defaultSet: MachError.Code {
return .defaultSet
}
/// An attempt was made to fetch an exception port that is
/// protected, or to abort a thread while processing a protected
/// exception.
public static var exceptionProtected: MachError.Code {
return .exceptionProtected
}
/// A ledger was required but not supplied.
public static var invalidLedger: MachError.Code {
return .invalidLedger
}
/// The port was not a memory cache control port.
public static var invalidMemoryControl: MachError.Code {
return .invalidMemoryControl
}
/// An argument supplied to assert security privilege was not a host
/// security port.
public static var invalidSecurity: MachError.Code {
return .invalidSecurity
}
/// thread_depress_abort was called on a thread which was not
/// currently depressed.
public static var notDepressed: MachError.Code {
return .notDepressed
}
/// Object has been terminated and is no longer available.
public static var terminated: MachError.Code {
return .terminated
}
/// Lock set has been destroyed and is no longer available.
public static var lockSetDestroyed: MachError.Code {
return .lockSetDestroyed
}
/// The thread holding the lock terminated before releasing the lock.
public static var lockUnstable: MachError.Code {
return .lockUnstable
}
/// The lock is already owned by another thread.
public static var lockOwned: MachError.Code {
return .lockOwned
}
/// The lock is already owned by the calling thread.
public static var lockOwnedSelf: MachError.Code {
return .lockOwnedSelf
}
/// Semaphore has been destroyed and is no longer available.
public static var semaphoreDestroyed: MachError.Code {
return .semaphoreDestroyed
}
/// Return from RPC indicating the target server was terminated
/// before it successfully replied.
public static var rpcServerTerminated: MachError.Code {
return .rpcServerTerminated
}
/// Terminate an orphaned activation.
public static var rpcTerminateOrphan: MachError.Code {
return .rpcTerminateOrphan
}
/// Allow an orphaned activation to continue executing.
public static var rpcContinueOrphan: MachError.Code {
return .rpcContinueOrphan
}
/// Empty thread activation (No thread linked to it).
public static var notSupported: MachError.Code {
return .notSupported
}
/// Remote node down or inaccessible.
public static var nodeDown: MachError.Code {
return .nodeDown
}
/// A signalled thread was not actually waiting.
public static var notWaiting: MachError.Code {
return .notWaiting
}
/// Some thread-oriented operation (semaphore_wait) timed out.
public static var operationTimedOut: MachError.Code {
return .operationTimedOut
}
/// During a page fault, indicates that the page was rejected as a
/// result of a signature check.
public static var codesignError: MachError.Code {
return .codesignError
}
/// The requested property cannot be changed at this time.
public static var policyStatic: MachError.Code {
return .policyStatic
}
}
public struct ErrorUserInfoKey : RawRepresentable, _SwiftNewtypeWrapper, Equatable, Hashable, _ObjectiveCBridgeable {
public init(rawValue: String) { self.rawValue = rawValue }
public var rawValue: String
}
public extension ErrorUserInfoKey {
@available(*, deprecated, renamed: "NSUnderlyingErrorKey")
static let underlyingErrorKey = ErrorUserInfoKey(rawValue: NSUnderlyingErrorKey)
@available(*, deprecated, renamed: "NSLocalizedDescriptionKey")
static let localizedDescriptionKey = ErrorUserInfoKey(rawValue: NSLocalizedDescriptionKey)
@available(*, deprecated, renamed: "NSLocalizedFailureReasonErrorKey")
static let localizedFailureReasonErrorKey = ErrorUserInfoKey(rawValue: NSLocalizedFailureReasonErrorKey)
@available(*, deprecated, renamed: "NSLocalizedRecoverySuggestionErrorKey")
static let localizedRecoverySuggestionErrorKey = ErrorUserInfoKey(rawValue: NSLocalizedRecoverySuggestionErrorKey)
@available(*, deprecated, renamed: "NSLocalizedRecoveryOptionsErrorKey")
static let localizedRecoveryOptionsErrorKey = ErrorUserInfoKey(rawValue: NSLocalizedRecoveryOptionsErrorKey)
@available(*, deprecated, renamed: "NSRecoveryAttempterErrorKey")
static let recoveryAttempterErrorKey = ErrorUserInfoKey(rawValue: NSRecoveryAttempterErrorKey)
@available(*, deprecated, renamed: "NSHelpAnchorErrorKey")
static let helpAnchorErrorKey = ErrorUserInfoKey(rawValue: NSHelpAnchorErrorKey)
@available(*, deprecated, renamed: "NSStringEncodingErrorKey")
static let stringEncodingErrorKey = ErrorUserInfoKey(rawValue: NSStringEncodingErrorKey)
@available(*, deprecated, renamed: "NSURLErrorKey")
static let NSURLErrorKey = ErrorUserInfoKey(rawValue: Foundation.NSURLErrorKey)
@available(*, deprecated, renamed: "NSFilePathErrorKey")
static let filePathErrorKey = ErrorUserInfoKey(rawValue: NSFilePathErrorKey)
}
| apache-2.0 | cfe00ec8884d10951733b13f13ca7976 | 31.8032 | 119 | 0.731194 | 4.613363 | false | false | false | false |
adrfer/swift | test/IDE/complete_from_reexport.swift | 16 | 1036 | // RUN: rm -rf %t
// RUN: mkdir -p %t
//
// RUN: %target-swift-frontend -emit-module -module-name FooSwiftModule %S/Inputs/foo_swift_module.swift -o %t
// RUN: %target-swift-frontend -emit-module -module-name FooSwiftModuleOverlay %S/Inputs/foo_swift_module_overlay.swift -I %t -o %t
//
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=TOP_LEVEL_1 -I %t > %t.txt
// RUN: FileCheck %s -check-prefix=TOP_LEVEL_1 < %t.txt
// RUN: FileCheck %s -check-prefix=NO_DUPLICATES < %t.txt
// TOP_LEVEL_1: Decl[FreeFunction]/OtherModule[FooSwiftModuleOverlay]: overlayedFoo()[#Void#]{{; name=.+$}}
// TOP_LEVEL_1: Decl[FreeFunction]/OtherModule[FooSwiftModuleOverlay]: onlyInFooOverlay()[#Void#]{{; name=.+$}}
// FIXME: there should be only one instance of this completion result.
// NO_DUPLICATES: overlayedFoo()[#Void#]{{; name=.+$}}
// NO_DUPLICATES: overlayedFoo()[#Void#]{{; name=.+$}}
// NO_DUPLICATES-NOT: overlayedFoo()[#Void#]{{; name=.+$}}
import FooSwiftModuleOverlay
#^TOP_LEVEL_1^#
| apache-2.0 | 01c95f933bde92cc1d2918dfc8bf2204 | 48.333333 | 131 | 0.686293 | 3.320513 | false | false | false | false |
KrishMunot/swift | test/Interpreter/SDK/OS_objects.swift | 4 | 1065 | // RUN: rm -rf %t
// RUN: mkdir -p %t
//
// RUN: cp %s %t/main.swift
// RUN: %target-build-swift %t/main.swift -I %S/Inputs/custom-modules/ -o %t/OS_objects -Xfrontend -disable-access-control
// RUN: %target-run %t/OS_objects 2>&1 | FileCheck %s
// REQUIRES: objc_interop
// Note: Test the use of the Clang objc_runtime_visible attribute via
// known OS objects on Darwin.
import ObjectiveC
import DispatchObjects
// CHECK: Get current queue
print("Get current queue")
let obj = dispatch_get_current_queue();
// CHECK-NEXT: Object is a dispatch queue
if let q = obj as? OS_dispatch_queue {
print("Object is a dispatch queue")
}
// CHECK-NEXT: Object is an OS object
if let q = obj as? OS_object {
print("Object is an OS object")
}
// CHECK-NEXT: Object is an NSObject
if let q = obj as? NSObject {
print("Object is an NSObject")
}
// CHECK-NEXT: Object is not a dispatch source
if let q = obj as? OS_dispatch_source {
print("Object is a dispatch source!?!?")
} else {
print("Object is not a dispatch source")
}
// CHECK-NEXT: DONE
print("DONE");
| apache-2.0 | 8484f7478108e2dc982b572947129af1 | 23.767442 | 122 | 0.683568 | 3.160237 | false | false | false | false |
ArnavChawla/InteliChat | Carthage/Checkouts/swift-sdk/Source/DiscoveryV1/Models/NluEnrichmentCategories.swift | 1 | 1567 | /**
* Copyright IBM Corporation 2018
*
* 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
/** An object that indicates the Categories enrichment will be applied to the specified field. */
public struct NluEnrichmentCategories: Codable {
/// Additional properties associated with this model.
public var additionalProperties: [String: JSON]
/**
Initialize a `NluEnrichmentCategories`.
- returns: An initialized `NluEnrichmentCategories`.
*/
public init(additionalProperties: [String: JSON] = [:]) {
self.additionalProperties = additionalProperties
}
public init(from decoder: Decoder) throws {
let dynamicContainer = try decoder.container(keyedBy: DynamicKeys.self)
additionalProperties = try dynamicContainer.decode([String: JSON].self, excluding: [CodingKey]())
}
public func encode(to encoder: Encoder) throws {
var dynamicContainer = encoder.container(keyedBy: DynamicKeys.self)
try dynamicContainer.encodeIfPresent(additionalProperties)
}
}
| mit | e7b3ef2673b43c9df7e83b8b3bccf8a3 | 34.613636 | 105 | 0.727505 | 4.636095 | false | false | false | false |
Beaver/BeaverCodeGen | Pods/Yams/Sources/Yams/Encoder.swift | 1 | 14441 | //
// Encoder.swift
// Yams
//
// Created by Norio Nomura on 5/2/17.
// Copyright (c) 2017 Yams. All rights reserved.
//
#if swift(>=4.0)
import Foundation
public class YAMLEncoder {
public typealias Options = Emitter.Options
public var options = Options()
public init() {}
public func encode<T: Swift.Encodable>(_ value: T, userInfo: [CodingUserInfoKey: Any] = [:]) throws -> String {
do {
let encoder = _Encoder(userInfo: userInfo)
var container = encoder.singleValueContainer()
try container.encode(value)
return try serialize(node: encoder.node, options: options)
} catch let error as EncodingError {
throw error
} catch {
let description = "Unable to encode the given top-level value to YAML."
let context = EncodingError.Context(codingPath: [],
debugDescription: description,
underlyingError: error)
throw EncodingError.invalidValue(value, context)
}
}
}
class _Encoder: Swift.Encoder { // swiftlint:disable:this type_name
var node: Node = .unused
init(userInfo: [CodingUserInfoKey: Any] = [:], codingPath: [CodingKey] = []) {
self.userInfo = userInfo
self.codingPath = codingPath
}
// MARK: - Swift.Encoder Methods
let codingPath: [CodingKey]
let userInfo: [CodingUserInfoKey: Any]
func container<Key>(keyedBy type: Key.Type) -> KeyedEncodingContainer<Key> {
if canEncodeNewValue {
node = [:]
} else {
precondition(
node.isMapping,
"Attempt to push new keyed encoding container when already previously encoded at this path."
)
}
return .init(_KeyedEncodingContainer<Key>(referencing: self))
}
func unkeyedContainer() -> UnkeyedEncodingContainer {
if canEncodeNewValue {
node = []
} else {
precondition(
node.isSequence,
"Attempt to push new keyed encoding container when already previously encoded at this path."
)
}
return _UnkeyedEncodingContainer(referencing: self)
}
func singleValueContainer() -> SingleValueEncodingContainer { return self }
// MARK: -
fileprivate var mapping: Node.Mapping {
get { return node.mapping ?? [:] }
set { node.mapping = newValue }
}
fileprivate var sequence: Node.Sequence {
get { return node.sequence ?? [] }
set { node.sequence = newValue }
}
/// Encode `ScalarRepresentable` to `node`
fileprivate func represent<T: ScalarRepresentable>(_ value: T) throws {
assertCanEncodeNewValue()
node = try box(value)
}
fileprivate func represent<T: ScalarRepresentableCustomizedForCodable>(_ value: T) throws {
assertCanEncodeNewValue()
node = value.representedForCodable()
}
/// create a new `_ReferencingEncoder` instance as `key` inheriting `userInfo`
fileprivate func encoder(for key: CodingKey) -> _ReferencingEncoder {
return .init(referencing: self, key: key)
}
/// create a new `_ReferencingEncoder` instance at `index` inheriting `userInfo`
fileprivate func encoder(at index: Int) -> _ReferencingEncoder {
return .init(referencing: self, at: index)
}
/// Create `Node` from `ScalarRepresentable`.
/// Errors throwed by `ScalarRepresentable` will be boxed into `EncodingError`
private func box(_ representable: ScalarRepresentable) throws -> Node {
do {
return try representable.represented()
} catch {
let context = EncodingError.Context(codingPath: codingPath,
debugDescription: "Unable to encode the given value to YAML.",
underlyingError: error)
throw EncodingError.invalidValue(representable, context)
}
}
private var canEncodeNewValue: Bool { return node == .unused }
}
class _ReferencingEncoder: _Encoder { // swiftlint:disable:this type_name
private enum Reference { case mapping(String), sequence(Int) }
private let encoder: _Encoder
private let reference: Reference
fileprivate init(referencing encoder: _Encoder, key: CodingKey) {
self.encoder = encoder
reference = .mapping(key.stringValue)
super.init(userInfo: encoder.userInfo, codingPath: encoder.codingPath + [key])
}
fileprivate init(referencing encoder: _Encoder, at index: Int) {
self.encoder = encoder
reference = .sequence(index)
super.init(userInfo: encoder.userInfo, codingPath: encoder.codingPath + [_YAMLCodingKey(index: index)])
}
deinit {
switch reference {
case .mapping(let key):
encoder.node[key] = node
case .sequence(let index):
encoder.node[index] = node
}
}
}
struct _KeyedEncodingContainer<K: CodingKey> : KeyedEncodingContainerProtocol { // swiftlint:disable:this type_name
typealias Key = K
private let encoder: _Encoder
fileprivate init(referencing encoder: _Encoder) {
self.encoder = encoder
}
// MARK: - Swift.KeyedEncodingContainerProtocol Methods
var codingPath: [CodingKey] { return encoder.codingPath }
func encodeNil(forKey key: Key) throws { encoder.mapping[key.stringValue] = .null }
func encode(_ value: Bool, forKey key: Key) throws { try encoder(for: key).represent(value) }
func encode(_ value: Int, forKey key: Key) throws { try encoder(for: key).represent(value) }
func encode(_ value: Int8, forKey key: Key) throws { try encoder(for: key).represent(value) }
func encode(_ value: Int16, forKey key: Key) throws { try encoder(for: key).represent(value) }
func encode(_ value: Int32, forKey key: Key) throws { try encoder(for: key).represent(value) }
func encode(_ value: Int64, forKey key: Key) throws { try encoder(for: key).represent(value) }
func encode(_ value: UInt, forKey key: Key) throws { try encoder(for: key).represent(value) }
func encode(_ value: UInt8, forKey key: Key) throws { try encoder(for: key).represent(value) }
func encode(_ value: UInt16, forKey key: Key) throws { try encoder(for: key).represent(value) }
func encode(_ value: UInt32, forKey key: Key) throws { try encoder(for: key).represent(value) }
func encode(_ value: UInt64, forKey key: Key) throws { try encoder(for: key).represent(value) }
func encode(_ value: Float, forKey key: Key) throws { try encoder(for: key).represent(value) }
func encode(_ value: Double, forKey key: Key) throws { try encoder(for: key).represent(value) }
func encode(_ value: String, forKey key: Key) throws { encoder.mapping[key.stringValue] = Node(value) }
func encode<T>(_ value: T, forKey key: Key) throws where T: Encodable { try encoder(for: key).encode(value) }
func nestedContainer<NestedKey>(keyedBy type: NestedKey.Type,
forKey key: Key) -> KeyedEncodingContainer<NestedKey> {
return encoder(for: key).container(keyedBy: type)
}
func nestedUnkeyedContainer(forKey key: Key) -> UnkeyedEncodingContainer {
return encoder(for: key).unkeyedContainer()
}
func superEncoder() -> Encoder { return encoder(for: _YAMLCodingKey.super) }
func superEncoder(forKey key: Key) -> Encoder { return encoder(for: key) }
// MARK: -
private func encoder(for key: CodingKey) -> _ReferencingEncoder { return encoder.encoder(for: key) }
}
struct _UnkeyedEncodingContainer: UnkeyedEncodingContainer { // swiftlint:disable:this type_name
private let encoder: _Encoder
fileprivate init(referencing encoder: _Encoder) {
self.encoder = encoder
}
// MARK: - Swift.UnkeyedEncodingContainer Methods
var codingPath: [CodingKey] { return encoder.codingPath }
var count: Int { return encoder.sequence.count }
func encodeNil() throws { encoder.sequence.append(.null) }
func encode(_ value: Bool) throws { try currentEncoder.represent(value) }
func encode(_ value: Int) throws { try currentEncoder.represent(value) }
func encode(_ value: Int8) throws { try currentEncoder.represent(value) }
func encode(_ value: Int16) throws { try currentEncoder.represent(value) }
func encode(_ value: Int32) throws { try currentEncoder.represent(value) }
func encode(_ value: Int64) throws { try currentEncoder.represent(value) }
func encode(_ value: UInt) throws { try currentEncoder.represent(value) }
func encode(_ value: UInt8) throws { try currentEncoder.represent(value) }
func encode(_ value: UInt16) throws { try currentEncoder.represent(value) }
func encode(_ value: UInt32) throws { try currentEncoder.represent(value) }
func encode(_ value: UInt64) throws { try currentEncoder.represent(value) }
func encode(_ value: Float) throws { try currentEncoder.represent(value) }
func encode(_ value: Double) throws { try currentEncoder.represent(value) }
func encode(_ value: String) throws { encoder.sequence.append(Node(value)) }
func encode<T>(_ value: T) throws where T: Encodable { try currentEncoder.encode(value) }
func nestedContainer<NestedKey>(keyedBy type: NestedKey.Type) -> KeyedEncodingContainer<NestedKey> {
return currentEncoder.container(keyedBy: type)
}
func nestedUnkeyedContainer() -> UnkeyedEncodingContainer { return currentEncoder.unkeyedContainer() }
func superEncoder() -> Encoder { return currentEncoder }
// MARK: -
private var currentEncoder: _ReferencingEncoder {
defer { encoder.sequence.append("") }
return encoder.encoder(at: count)
}
}
extension _Encoder: SingleValueEncodingContainer {
// MARK: - Swift.SingleValueEncodingContainer Methods
func encodeNil() throws {
assertCanEncodeNewValue()
node = .null
}
func encode(_ value: Bool) throws { try represent(value) }
func encode(_ value: Int) throws { try represent(value) }
func encode(_ value: Int8) throws { try represent(value) }
func encode(_ value: Int16) throws { try represent(value) }
func encode(_ value: Int32) throws { try represent(value) }
func encode(_ value: Int64) throws { try represent(value) }
func encode(_ value: UInt) throws { try represent(value) }
func encode(_ value: UInt8) throws { try represent(value) }
func encode(_ value: UInt16) throws { try represent(value) }
func encode(_ value: UInt32) throws { try represent(value) }
func encode(_ value: UInt64) throws { try represent(value) }
func encode(_ value: Float) throws { try represent(value) }
func encode(_ value: Double) throws { try represent(value) }
func encode(_ value: String) throws {
assertCanEncodeNewValue()
node = Node(value)
}
func encode<T>(_ value: T) throws where T: Encodable {
assertCanEncodeNewValue()
if let customized = value as? ScalarRepresentableCustomizedForCodable {
node = customized.representedForCodable()
} else if let representable = value as? ScalarRepresentable {
node = try box(representable)
} else {
try value.encode(to: self)
}
}
// MARK: -
/// Asserts that a single value can be encoded at the current coding path
/// (i.e. that one has not already been encoded through this container).
/// `preconditionFailure()`s if one cannot be encoded.
private func assertCanEncodeNewValue() {
precondition(
canEncodeNewValue,
"Attempt to encode value through single value container when previously value already encoded."
)
}
}
// MARK: - CodingKey for `_UnkeyedEncodingContainer`, `_UnkeyedDecodingContainer`, `superEncoder` and `superDecoder`
struct _YAMLCodingKey: CodingKey { // swiftlint:disable:this type_name
var stringValue: String
var intValue: Int?
init?(stringValue: String) {
self.stringValue = stringValue
self.intValue = nil
}
init?(intValue: Int) {
self.stringValue = "\(intValue)"
self.intValue = intValue
}
init(index: Int) {
self.stringValue = "Index \(index)"
self.intValue = index
}
static let `super` = _YAMLCodingKey(stringValue: "super")!
}
// MARK: -
private extension Node {
static let null = Node("null", Tag(.null))
static let unused = Node("", .unused)
}
private extension Tag {
static let unused = Tag(.unused)
}
private extension Tag.Name {
static let unused: Tag.Name = "tag:yams.encoder:unused"
}
private func serialize(node: Node, options: Emitter.Options) throws -> String {
return try serialize(
nodes: [node],
canonical: options.canonical,
indent: options.indent,
width: options.width,
allowUnicode: options.allowUnicode,
lineBreak: options.lineBreak,
explicitStart: options.explicitStart,
explicitEnd: options.explicitEnd,
version: options.version,
sortKeys: options.sortKeys)
}
#endif
| mit | 6fbe7dd67918ea6c68b18430feb013b2 | 40.857971 | 120 | 0.598712 | 4.915248 | false | false | false | false |
hectormatos2011/Bite-About-It | Bite-About-It/Bite About It/Authentication.swift | 1 | 2125 | //
// Authentication.swift
// Bite About It
//
// Created by Hector Matos on 8/16/17.
// Copyright © 2017 Hector Matos. All rights reserved.
//
import Foundation
import KeychainAccess
import SwiftyJSON
public typealias AuthenticationCallback = (Result<String>) -> Void
/**
This class is dedicated to the honorable Kwelly8. Thanks for the sub!
*/
public class AuthenticationOperation: APIOperation<String> {
private let keychain = Keychain(service: "com.krakendev.authentication")
private enum KeychainKeys: String {
case yelpAccessToken
}
override func execute() {
guard let accessToken = AccessToken(keychainData: keychain[data: KeychainKeys.yelpAccessToken.rawValue]), accessToken.isValid else {
fetchAccessToken(completion: finish)
return
}
finish(result: .success(accessToken.token))
}
private func fetchAccessToken(completion: @escaping AuthenticationCallback) {
let dataTask = URLSession.shared.dataTask(with: Endpoint.oauthToken.request) { (data, response, error) in
guard let data = data, error == nil else {
completion(.failure(error ?? "Unknown Failure. Maybe no data was returned?"))
return
}
// response JSON
let jonnyman9 = JSON(data: data)
if let errorDescription = jonnyman9["error"]["description"].string {
completion(.failure(errorDescription))
} else {
let accessTokenString = jonnyman9["access_token"].stringValue
let accessTokenExpirationSeconds = jonnyman9["expires_in"].intValue
let expirationDate = Date().addingTimeInterval(TimeInterval(accessTokenExpirationSeconds))
let accessToken = AccessToken(token: accessTokenString, expiration: expirationDate)
self.keychain[data: KeychainKeys.yelpAccessToken.rawValue] = accessToken.dataValue
completion(.success(accessTokenString))
}
}
dataTask.resume()
}
}
| mit | 903a21fcfa1fef7dbe81629af2efa301 | 31.676923 | 140 | 0.642655 | 5.033175 | false | false | false | false |
tkremenek/swift | test/SILOptimizer/definite_init_value_types.swift | 5 | 3262 | // RUN: %target-swift-frontend -emit-sil %s | %FileCheck %s
enum ValueEnum {
case a(String)
case b
case c
init() { self = .b }
init(a: Double) {
self.init()
_ = self // okay: self has been initialized by the delegation above
self = .c
}
init(a: Float) {
self.init()
self.init() // this is now OK
}
init(e: Bool) {
if e {
self = ValueEnum()
} else {
self.init()
}
}
// CHECK-LABEL: sil hidden @$s25definite_init_value_types9ValueEnumO1xACSb_tcfC : $@convention(method) (Bool, @thin ValueEnum.Type) -> @owned ValueEnum
// CHECK: bb0(%0 : $Bool, %1 : $@thin ValueEnum.Type):
// CHECK-NEXT: [[STATE:%.*]] = alloc_stack $Builtin.Int1
// CHECK-NEXT: [[SELF_BOX:%.*]] = alloc_stack [dynamic_lifetime] $ValueEnum
// CHECK-NEXT: [[INIT_STATE:%.*]] = integer_literal $Builtin.Int1, 0
// CHECK-NEXT: store [[INIT_STATE]] to [[STATE]]
// CHECK: [[BOOL:%.*]] = struct_extract %0 : $Bool, #Bool._value
// CHECK-NEXT: cond_br [[BOOL]], bb1, bb2
// CHECK: bb1:
// CHECK-NEXT: [[NEW_SELF:%.*]] = enum $ValueEnum, #ValueEnum.b!enumelt
// CHECK-NEXT: [[SELF_ACCESS:%.*]] = begin_access [modify] [static] [[SELF_BOX]]
// CHECK-NEXT: [[NEW_STATE:%.*]] = integer_literal $Builtin.Int1, -1
// CHECK-NEXT: store [[NEW_STATE]] to [[STATE]]
// CHECK-NEXT: store [[NEW_SELF]] to [[SELF_ACCESS]]
// CHECK-NEXT: end_access [[SELF_ACCESS]]
// CHECK-NEXT: br bb3
// CHECK: bb2:
// CHECK-NEXT: br bb3
// CHECK: bb3:
// CHECK-NEXT: [[NEW_SELF:%.*]] = enum $ValueEnum, #ValueEnum.c!enumelt
// CHECK-NEXT: [[SELF_ACCESS:%.*]] = begin_access [modify] [static] [[SELF_BOX]]
// CHECK-NEXT: [[STATE_VALUE:%.*]] = load [[STATE]]
// CHECK-NEXT: cond_br [[STATE_VALUE]], bb4, bb5
// CHECK: bb4:
// CHECK-NEXT: destroy_addr [[SELF_BOX]]
// CHECK-NEXT: br bb6
// CHECK: bb5:
// CHECK-NEXT: br bb6
// CHECK: bb6:
// CHECK-NEXT: [[NEW_STATE:%.*]] = integer_literal $Builtin.Int1, -1
// CHECK-NEXT: store [[NEW_STATE]] to [[STATE]]
// CHECK-NEXT: retain_value [[NEW_SELF]]
// CHECK-NEXT: store [[NEW_SELF]] to [[SELF_ACCESS]]
// CHECK-NEXT: end_access [[SELF_ACCESS]]
// CHECK-NEXT: destroy_addr [[SELF_BOX]]
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: dealloc_stack [[STATE]]
// CHECK-NEXT: return [[NEW_SELF]]
init(x: Bool) {
if x {
self = .b
}
self = .c
}
}
enum AddressEnum {
case a(Any)
case b
case c
init() { self = .b }
init(e: Bool) {
if e {
self = AddressEnum()
} else {
self.init()
}
}
init(x: Bool) {
if x {
self = .b
}
self = .c
}
}
struct EmptyStruct {}
struct ValueStruct {
var ivar: EmptyStruct
init() { ivar = EmptyStruct() }
init(a: Float) {
self.init()
self.init()
}
init(e: Bool) {
if e {
self.init()
} else {
self = ValueStruct()
}
}
}
struct AddressStruct {
var ivar: EmptyStruct // expected-note {{'self.ivar' not initialized}}
var any: Any?
init() { ivar = EmptyStruct(); any = nil }
init(e: Bool) {
if e {
self = AddressStruct()
} else {
self.init()
}
}
}
| apache-2.0 | 6317896cbf6ca6babd06f9da5a5502b1 | 23.712121 | 153 | 0.545984 | 3.068674 | false | false | false | false |
tkremenek/swift | benchmark/single-source/UTF8Decode.swift | 12 | 9540 | //===--- UTF8Decode.swift -------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import TestsUtils
import Foundation
public let UTF8Decode = [
BenchmarkInfo(
name: "UTF8Decode",
runFunction: run_UTF8Decode,
tags: [.validation, .api, .String]),
BenchmarkInfo(
name: "UTF8Decode_InitFromCustom_contiguous",
runFunction: run_UTF8Decode_InitFromCustom_contiguous,
tags: [.validation, .api, .String]),
BenchmarkInfo(
name: "UTF8Decode_InitFromCustom_contiguous_ascii",
runFunction: run_UTF8Decode_InitFromCustom_contiguous_ascii,
tags: [.validation, .api, .String]),
BenchmarkInfo(
name: "UTF8Decode_InitFromCustom_contiguous_ascii_as_ascii",
runFunction: run_UTF8Decode_InitFromCustom_contiguous_ascii_as_ascii,
tags: [.validation, .api, .String]),
BenchmarkInfo(
name: "UTF8Decode_InitFromCustom_noncontiguous",
runFunction: run_UTF8Decode_InitFromCustom_noncontiguous,
tags: [.validation, .api, .String]),
BenchmarkInfo(
name: "UTF8Decode_InitFromCustom_noncontiguous_ascii",
runFunction: run_UTF8Decode_InitFromCustom_noncontiguous_ascii,
tags: [.validation, .api, .String]),
BenchmarkInfo(
name: "UTF8Decode_InitFromCustom_noncontiguous_ascii_as_ascii",
runFunction: run_UTF8Decode_InitFromCustom_noncontiguous_ascii_as_ascii,
tags: [.validation, .api, .String]),
BenchmarkInfo(
name: "UTF8Decode_InitFromData",
runFunction: run_UTF8Decode_InitFromData,
tags: [.validation, .api, .String]),
BenchmarkInfo(
name: "UTF8Decode_InitDecoding",
runFunction: run_UTF8Decode_InitDecoding,
tags: [.validation, .api, .String]),
BenchmarkInfo(
name: "UTF8Decode_InitFromBytes",
runFunction: run_UTF8Decode_InitFromBytes,
tags: [.validation, .api, .String]),
BenchmarkInfo(
name: "UTF8Decode_InitFromData_ascii",
runFunction: run_UTF8Decode_InitFromData_ascii,
tags: [.validation, .api, .String]),
BenchmarkInfo(
name: "UTF8Decode_InitDecoding_ascii",
runFunction: run_UTF8Decode_InitDecoding_ascii,
tags: [.validation, .api, .String]),
BenchmarkInfo(
name: "UTF8Decode_InitFromBytes_ascii",
runFunction: run_UTF8Decode_InitFromBytes_ascii,
tags: [.validation, .api, .String]),
BenchmarkInfo(
name: "UTF8Decode_InitFromData_ascii_as_ascii",
runFunction: run_UTF8Decode_InitFromData_ascii_as_ascii,
tags: [.validation, .api, .String]),
BenchmarkInfo(
name: "UTF8Decode_InitDecoding_ascii_as_ascii",
runFunction: run_UTF8Decode_InitDecoding_ascii_as_ascii,
tags: [.validation, .api, .String]),
BenchmarkInfo(
name: "UTF8Decode_InitFromBytes_ascii_as_ascii",
runFunction: run_UTF8Decode_InitFromBytes_ascii_as_ascii,
tags: [.validation, .api, .String]),
]
// 1-byte sequences
// This test case is the longest as it's the most performance sensitive.
let ascii = "Swift is a multi-paradigm, compiled programming language created for iOS, OS X, watchOS, tvOS and Linux development by Apple Inc. Swift is designed to work with Apple's Cocoa and Cocoa Touch frameworks and the large body of existing Objective-C code written for Apple products. Swift is intended to be more resilient to erroneous code (\"safer\") than Objective-C and also more concise. It is built with the LLVM compiler framework included in Xcode 6 and later and uses the Objective-C runtime, which allows C, Objective-C, C++ and Swift code to run within a single program."
let asciiBytes: [UInt8] = Array(ascii.utf8)
let asciiData: Data = Data(asciiBytes)
// 2-byte sequences
let russian = "Ру́сский язы́к один из восточнославянских языков, национальный язык русского народа."
// 3-byte sequences
let japanese = "日本語(にほんご、にっぽんご)は、主に日本国内や日本人同士の間で使われている言語である。"
// 4-byte sequences
// Most commonly emoji, which are usually mixed with other text.
let emoji = "Panda 🐼, Dog 🐶, Cat 🐱, Mouse 🐭."
let allStrings = [ascii, russian, japanese, emoji].map { Array($0.utf8) }
let allStringsBytes: [UInt8] = Array(allStrings.joined())
let allStringsData: Data = Data(allStringsBytes)
@inline(never)
public func run_UTF8Decode(_ N: Int) {
let strings = allStrings
func isEmpty(_ result: UnicodeDecodingResult) -> Bool {
switch result {
case .emptyInput:
return true
default:
return false
}
}
for _ in 1...200*N {
for string in strings {
var it = string.makeIterator()
var utf8 = UTF8()
while !isEmpty(utf8.decode(&it)) { }
}
}
}
@inline(never)
public func run_UTF8Decode_InitFromData(_ N: Int) {
let input = allStringsData
for _ in 0..<200*N {
blackHole(String(data: input, encoding: .utf8))
}
}
@inline(never)
public func run_UTF8Decode_InitDecoding(_ N: Int) {
let input = allStringsBytes
for _ in 0..<200*N {
blackHole(String(decoding: input, as: UTF8.self))
}
}
@inline(never)
public func run_UTF8Decode_InitFromBytes(_ N: Int) {
let input = allStringsBytes
for _ in 0..<200*N {
blackHole(String(bytes: input, encoding: .utf8))
}
}
@inline(never)
public func run_UTF8Decode_InitFromData_ascii(_ N: Int) {
let input = asciiData
for _ in 0..<1_000*N {
blackHole(String(data: input, encoding: .utf8))
}
}
@inline(never)
public func run_UTF8Decode_InitDecoding_ascii(_ N: Int) {
let input = asciiBytes
for _ in 0..<1_000*N {
blackHole(String(decoding: input, as: UTF8.self))
}
}
@inline(never)
public func run_UTF8Decode_InitFromBytes_ascii(_ N: Int) {
let input = asciiBytes
for _ in 0..<1_000*N {
blackHole(String(bytes: input, encoding: .utf8))
}
}
@inline(never)
public func run_UTF8Decode_InitFromData_ascii_as_ascii(_ N: Int) {
let input = asciiData
for _ in 0..<1_000*N {
blackHole(String(data: input, encoding: .ascii))
}
}
@inline(never)
public func run_UTF8Decode_InitDecoding_ascii_as_ascii(_ N: Int) {
let input = asciiBytes
for _ in 0..<1_000*N {
blackHole(String(decoding: input, as: Unicode.ASCII.self))
}
}
@inline(never)
public func run_UTF8Decode_InitFromBytes_ascii_as_ascii(_ N: Int) {
let input = asciiBytes
for _ in 0..<1_000*N {
blackHole(String(bytes: input, encoding: .ascii))
}
}
struct CustomContiguousCollection: Collection {
let storage: [UInt8]
typealias Index = Int
typealias Element = UInt8
init(_ bytes: [UInt8]) { self.storage = bytes }
subscript(position: Int) -> Element { self.storage[position] }
var startIndex: Index { 0 }
var endIndex: Index { storage.count }
func index(after i: Index) -> Index { i+1 }
@inline(never)
func withContiguousStorageIfAvailable<R>(
_ body: (UnsafeBufferPointer<UInt8>) throws -> R
) rethrows -> R? {
try storage.withContiguousStorageIfAvailable(body)
}
}
struct CustomNoncontiguousCollection: Collection {
let storage: [UInt8]
typealias Index = Int
typealias Element = UInt8
init(_ bytes: [UInt8]) { self.storage = bytes }
subscript(position: Int) -> Element { self.storage[position] }
var startIndex: Index { 0 }
var endIndex: Index { storage.count }
func index(after i: Index) -> Index { i+1 }
@inline(never)
func withContiguousStorageIfAvailable<R>(
_ body: (UnsafeBufferPointer<UInt8>) throws -> R
) rethrows -> R? {
nil
}
}
let allStringsCustomContiguous = CustomContiguousCollection(allStringsBytes)
let asciiCustomContiguous = CustomContiguousCollection(Array(ascii.utf8))
let allStringsCustomNoncontiguous = CustomNoncontiguousCollection(allStringsBytes)
let asciiCustomNoncontiguous = CustomNoncontiguousCollection(Array(ascii.utf8))
@inline(never)
public func run_UTF8Decode_InitFromCustom_contiguous(_ N: Int) {
let input = allStringsCustomContiguous
for _ in 0..<200*N {
blackHole(String(decoding: input, as: UTF8.self))
}
}
@inline(never)
public func run_UTF8Decode_InitFromCustom_contiguous_ascii(_ N: Int) {
let input = asciiCustomContiguous
for _ in 0..<1_000*N {
blackHole(String(decoding: input, as: UTF8.self))
}
}
@inline(never)
public func run_UTF8Decode_InitFromCustom_contiguous_ascii_as_ascii(_ N: Int) {
let input = asciiCustomContiguous
for _ in 0..<1_000*N {
blackHole(String(decoding: input, as: Unicode.ASCII.self))
}
}
@inline(never)
public func run_UTF8Decode_InitFromCustom_noncontiguous(_ N: Int) {
let input = allStringsCustomNoncontiguous
for _ in 0..<200*N {
blackHole(String(decoding: input, as: UTF8.self))
}
}
@inline(never)
public func run_UTF8Decode_InitFromCustom_noncontiguous_ascii(_ N: Int) {
let input = asciiCustomNoncontiguous
for _ in 0..<1_000*N {
blackHole(String(decoding: input, as: UTF8.self))
}
}
@inline(never)
public func run_UTF8Decode_InitFromCustom_noncontiguous_ascii_as_ascii(_ N: Int) {
let input = asciiCustomNoncontiguous
for _ in 0..<1_000*N {
blackHole(String(decoding: input, as: Unicode.ASCII.self))
}
}
| apache-2.0 | 848f2acad027b2a7b1c3aca05796a18d | 33.186131 | 589 | 0.690936 | 3.505614 | false | false | false | false |
mirego/PinLayout | Tests/iOS/Types+UIKit.swift | 1 | 1332 | // Copyright (c) 2018 Luc Dion
// 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
typealias PView = UIView
typealias PScrollView = UIScrollView
typealias PEdgeInsets = UIEdgeInsets
typealias PViewController = UIViewController
typealias PColor = UIColor
typealias PLabel = UILabel
| mit | da3cc8fc67a4e328f0ea845b78308c76 | 48.333333 | 81 | 0.77027 | 4.546075 | false | false | false | false |
tananaev/traccar-client-ios | TraccarClient/NetworkManager.swift | 1 | 2876 | //
// Copyright 2015 - 2017 Anton Tananaev ([email protected])
//
// 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 SystemConfiguration
protocol NetworkManagerDelegate: class {
func didUpdateNetwork(online: Bool)
}
class NetworkManager : NSObject {
weak var delegate: NetworkManagerDelegate?
//var reachability: SCNetworkReachability
override init() {
/*var zeroAddress = sockaddr_in()
zeroAddress.sin_len = UInt8(MemoryLayout.size(ofValue: zeroAddress))
zeroAddress.sin_family = sa_family_t(AF_INET)
reachability = withUnsafePointer(to: &zeroAddress, {
$0.withMemoryRebound(to: sockaddr.self, capacity: 1) {
SCNetworkReachabilityCreateWithAddress(nil, $0)
}
})!*/
super.init()
}
func online() -> Bool {
/*var flags: SCNetworkReachabilityFlags = []
SCNetworkReachabilityGetFlags(reachability, &flags)
return NetworkManager.online(for: flags)*/
return true
}
func start() {
/*var context = SCNetworkReachabilityContext(version: 0, info: Unmanaged.passUnretained(self).toOpaque(), retain: nil, release: nil, copyDescription: nil)
SCNetworkReachabilitySetCallback(reachability, { (reachability, flags, pointer) in
let networkManager = Unmanaged<NetworkManager>.fromOpaque(pointer!).takeUnretainedValue()
networkManager.delegate?.didUpdateNetwork(online: NetworkManager.online(for: flags))
}, &context)
SCNetworkReachabilityScheduleWithRunLoop(reachability, CFRunLoopGetCurrent(), CFRunLoopMode.defaultMode.rawValue)*/
}
func stop() {
/*SCNetworkReachabilityUnscheduleFromRunLoop(reachability, CFRunLoopGetCurrent(), CFRunLoopMode.defaultMode.rawValue)*/
}
static func online(for flags: SCNetworkReachabilityFlags) -> Bool {
if !flags.contains(.reachable) {
return false
}
if !flags.contains(.connectionRequired) {
return true
}
if flags.contains(.connectionOnDemand) || flags.contains(.connectionOnTraffic) {
if !flags.contains(.interventionRequired) {
return true
}
}
if flags.contains(.isWWAN) {
return true
}
return false
}
}
| apache-2.0 | 6ad960f81698ffce738e5bce1110f446 | 34.073171 | 162 | 0.668289 | 5.07231 | false | false | false | false |
Chaatz/SocketIOChatClient | Example/SocketIOChatClient/LoginViewController.swift | 1 | 1267 | //
// LoginViewController.swift
// SocketIO
//
// Created by Kenneth on 26/1/2016.
// Copyright © 2016 CocoaPods. All rights reserved.
//
import UIKit
class LoginViewController: UIViewController {
//MARK: Init
@IBOutlet weak var textField: UITextField!
@IBOutlet weak var sendMessageSwitch: UISwitch!
//MARK: ViewController Life Cycle
override func viewDidLoad() {
super.viewDidLoad()
textField.text = "蒼老師"
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
textField.becomeFirstResponder()
}
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
textField.resignFirstResponder()
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
guard let vc = segue.destinationViewController as? ChatViewController else { return }
vc.username = sender as? String
vc.canSendMessage = sendMessageSwitch.on
}
@IBAction func connectButtonTapped() {
guard let username = textField.text else { return }
if username.isEmpty { return }
performSegueWithIdentifier("ChatViewControllerSegue", sender: username)
}
} | mit | 32862d1229024a1ca0cd2ac8652df16e | 27.659091 | 93 | 0.676984 | 5.080645 | false | false | false | false |
yaoshenglong/GFDouYuZhiBo | DouYuZhiBo/DouYuZhiBo/Classes/Main/View/CollectionNormalCell.swift | 1 | 1582 | //
// CollectionNormalCell.swift
// DouYuZhiBo
//
// Created by 姚胜龙 on 17/3/17.
// Copyright © 2017年 DragonYao. All rights reserved.
//
import UIKit
class CollectionNormalCell: UICollectionViewCell {
@IBOutlet weak var onlineBtn: UIButton!
@IBOutlet weak var auchorBtn: UIButton!
@IBOutlet weak var thumbImgView: UIImageView!
@IBOutlet weak var roomNameLabel: UILabel!
var anchor:Anchors? {
didSet{
guard let anchor = anchor else {return}
self.roomNameLabel.text = anchor.room_name
self.onlineBtn.setImage(UIImage(named: "yuba_home_follow_selected"), for: UIControlState.normal)
var titleStr: String = ""
if anchor.online > 10000 {
titleStr = "\(Int(anchor.online/10000))在线"
}
else {
titleStr = "\(Int(anchor.online))在线"
}
self.onlineBtn.setTitle(titleStr, for: .normal)
self.auchorBtn.setImage(UIImage(named: "home_live_player_normal"), for: .normal)
self.auchorBtn.setTitle(anchor.nickname, for: .normal)
//设置图片
let imgUrl = URL(string: anchor.vertical_src)
thumbImgView.kf.setImage(with: imgUrl)
}
}
override func awakeFromNib() {
super.awakeFromNib()
}
@IBAction func showAuchorInfoView(_ sender: UIButton) {
print("主播信息")
}
@IBAction func showOnlineView(_ sender: Any) {
print("在线人数")
}
}
| apache-2.0 | 02aa160777ab5030f9335b0daf5ab7b2 | 27.537037 | 108 | 0.584036 | 4.245179 | false | false | false | false |
lojals/DoorsConcept | DoorConcept/Controllers/Doors/DoorInteractor.swift | 1 | 6942 | //
// BuildingsInteractor.swift
// DoorConcept
//
// Created by Jorge Raul Ovalle Zuleta on 3/21/16.
// Copyright © 2016 jorgeovalle. All rights reserved.
//
import UIKit
import CoreData
enum DoorState:String{
case Opened = "Opened"
case Closed = "Closed"
}
enum DoorTransacStatus:String{
case Authorized = "Authorized"
case Denied = "Access Denied!"
case Ready = "Ready!"
}
typealias CompletionHandler = ((error:String?)->Void)?
class DoorsInteractor {
private let managedObjectContext:NSManagedObjectContext = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext
init(){}
/**
Retrieve the doors in case is a detail call with a building given.
- parameter build: valid building
- parameter completion: completion description (data = [Door], error = error description)
*/
func getDoorsByBuilding(build:Building,completion:FetchCompletionHandler){
let fetchRequest = NSFetchRequest(entityName: "Door")
fetchRequest.predicate = NSPredicate(format: "building == %@", build)
do{
let fetchResults = try managedObjectContext.executeRequest(fetchRequest) as! NSAsynchronousFetchResult
let fetchBuilding = fetchResults.finalResult as! [Door]
completion!(data:fetchBuilding, error: nil)
}catch{
completion!(data:nil,error: "CoreData error!")
}
}
/**
Retrieve all the doors created. TODO: Retrieve just the permited by the current user.
- parameter completion: completion description (data = [Door], error = error description)
*/
func getDoors(completion:FetchCompletionHandler){
let fetchRequest = NSFetchRequest(entityName: "Door")
do{
let fetchResults = try managedObjectContext.executeRequest(fetchRequest) as! NSAsynchronousFetchResult
let fetchBuilding = fetchResults.finalResult as! [Door]
completion!(data:fetchBuilding, error: nil)
}catch{
completion!(data:nil,error: "CoreData error!")
}
}
/**
Retrieve all granted users for a given door.
- parameter door: valid door data type.
- parameter completion: completion description (data = [Permision], error = error description)
*/
func getPermissionsByDoor(door:Door,completion:FetchCompletionHandler){
let fetchRequest = NSFetchRequest(entityName: "Permision")
fetchRequest.predicate = NSPredicate(format: "door == %@", door)
do{
let fetchResults = try managedObjectContext.executeRequest(fetchRequest) as! NSAsynchronousFetchResult
let fetchBuilding = fetchResults.finalResult as! [Permision]
completion!(data:fetchBuilding, error: nil)
}catch{
completion!(data:nil,error: "CoreData error!")
}
}
/**
Grant access to a user with username = @name.
- parameter name: username, not empty.
- parameter door: door to be permited.
- parameter completion: completion description (error == nil => Everything ok, error != nil => Error description)
*/
func givePermission(name:String, door:Door, completion:CompletionHandler){
let fetchRequest = NSFetchRequest(entityName: "User")
fetchRequest.predicate = NSPredicate(format: "userUsername = %@", name)
do{
let fetchResults = try managedObjectContext.executeRequest(fetchRequest) as! NSAsynchronousFetchResult
let fetchUser = fetchResults.finalResult as! [User]
if fetchUser.count > 0 {
let permission = NSEntityDescription.insertNewObjectForEntityForName("Permision", inManagedObjectContext: managedObjectContext) as! Permision
permission.door = door
permission.user = fetchUser.first!
permission.date = NSDate()
try managedObjectContext.save()
completion!(error: nil)
}else{
completion!(error: "User doesn't exist")
}
}catch{
completion!(error: "CoreData error")
}
}
/**
Delete given door from db.
- parameter door: active and valid Door.
*/
func deleteDoor(door:Door){
if UserService.sharedInstance.currentUser! == door.building?.owner{
managedObjectContext.deleteObject(door)
do{
try managedObjectContext.save()
}catch{
print("Some error deleting Door")
}
}else{
//Not yet implemented in UI
print("That's not your door")
}
}
/**
Add a new door to a given Building
- parameter building: Valid Building owned by current user
- parameter name: Valid String not empty
- parameter avatar: Avatar index (0-4)
*/
func saveDoor(building:Building, name:String, avatar:String){
let door = NSEntityDescription.insertNewObjectForEntityForName("Door", inManagedObjectContext: managedObjectContext) as! Door
door.doorName = name
door.doorState = DoorState.Closed.rawValue
door.doorAvatar = avatar
door.doorCreatedAt = NSDate()
door.building = building
let permission = NSEntityDescription.insertNewObjectForEntityForName("Permision", inManagedObjectContext: managedObjectContext) as! Permision
permission.door = door
permission.user = building.owner
permission.date = NSDate()
do{
try managedObjectContext.save()
}catch{
print("Some error inserting Door")
}
}
/**
Check if a given user has permission to open an specific door
- parameter user: Valid user added to the DB
- parameter door: valid door added to the DB
- parameter completion: completion description (error == nil => Everything ok, error != nil => Error description)
*/
func checkPermission(user:User,door:Door,completion:FetchCompletionHandler){
let fetchRequest = NSFetchRequest(entityName: "Permision")
fetchRequest.predicate = NSPredicate(format: "user == %@ AND door == %@", user,door)
do{
let fetchResults = try managedObjectContext.executeRequest(fetchRequest) as! NSAsynchronousFetchResult
let fetchPermision = fetchResults.finalResult as! [Door]
if fetchPermision.count > 0 {
completion!(data:fetchPermision, error: nil)
}else{
completion!(data:fetchPermision, error: "Doesn't have permission")
}
}catch{
completion!(data:nil,error: "CoreData error!")
}
}
} | mit | 388e59b2f62b4cd109f6c0cdc8c48005 | 36.934426 | 158 | 0.623829 | 5.152932 | false | false | false | false |
guidomb/Portal | PortalTests/View/UIKit/Renderers/LabelRendererSpec.swift | 1 | 4268 | //
// LabelRendererSpec.swift
// PortalTests
//
// Created by Pablo Giorgi on 8/28/17.
// Copyright © 2017 Guido Marucci Blas. All rights reserved.
//
import Quick
import Nimble
@testable import Portal
class LabelRendererSpec: QuickSpec {
override func spec() {
var layoutEngine: LayoutEngine!
beforeEach {
layoutEngine = YogaLayoutEngine()
}
describe(".apply(changeSet: TextFieldChangeSet) -> Result") {
var changeSet: LabelChangeSet!
beforeEach {
let labelProperties: LabelProperties = properties(
text: "Hello World before layout",
textAfterLayout: "Hello World"
)
let labelStyle = labelStyleSheet { base, label in
label.textColor = .red
label.textFont = Font(name: "Helvetica")
label.textSize = 12
label.textAlignment = .center
label.adjustToFitWidth = true
label.numberOfLines = 0
label.minimumScaleFactor = 1.0
}
changeSet = LabelChangeSet.fullChangeSet(
properties: labelProperties,
style: labelStyle,
layout: layout()
)
}
context("when the change set contains label property changes") {
it("applies 'text' property before layout") {
let label = UILabel()
let _: Render<String> = label.apply(changeSet: changeSet, layoutEngine: layoutEngine)
expect(label.text).to(equal("Hello World before layout"))
}
it("applies 'textAfterLayout' property after layout") {
let label = UILabel()
let result: Render<String> = label.apply(changeSet: changeSet, layoutEngine: layoutEngine)
result.afterLayout?()
expect(label.text).to(equal("Hello World"))
}
context("when the change set contains label stylesheet changes") {
it("applies 'textColor' property changes") {
let label = UILabel()
let _: Render<String> = label.apply(changeSet: changeSet, layoutEngine: layoutEngine)
expect(label.textColor).to(equal(.red))
}
it("applies 'alignment' property changes") {
let label = UILabel()
let _: Render<String> = label.apply(changeSet: changeSet, layoutEngine: layoutEngine)
expect(label.textAlignment).to(equal(NSTextAlignment.center))
}
it("applies 'textFont' and 'textSize' property changes") {
let label = UILabel()
let _: Render<String> = label.apply(changeSet: changeSet, layoutEngine: layoutEngine)
expect(label.font).to(equal(UIFont(name: "Helvetica", size: 12)))
}
it("applies 'adjustToFitWidth' property changes") {
let label = UILabel()
let _: Render<String> = label.apply(changeSet: changeSet, layoutEngine: layoutEngine)
expect(label.adjustsFontSizeToFitWidth).to(equal(true))
}
it("applies 'numberOfLines' property changes") {
let label = UILabel()
let _: Render<String> = label.apply(changeSet: changeSet, layoutEngine: layoutEngine)
expect(label.numberOfLines).to(equal(0))
}
it("applies 'minimumScaleFactor' property changes") {
let label = UILabel()
let _: Render<String> = label.apply(changeSet: changeSet, layoutEngine: layoutEngine)
expect(label.minimumScaleFactor).to(equal(1.0))
}
}
}
}
}
}
| mit | 324016c8a64c3697833c769b10a0a9c2 | 38.146789 | 110 | 0.498711 | 5.845205 | false | false | false | false |
interstateone/Fresh | Fresh/Common/Models/SoundCloudService.swift | 1 | 8287 | //
// SoundCloudService.swift
// Fresh
//
// Created by Brandon Evans on 2015-12-29.
// Copyright © 2015 Brandon Evans. All rights reserved.
//
import Foundation
import ReactiveCocoa
import Alamofire
typealias JSONObject = [String: AnyObject]
typealias JSONArray = [JSONObject]
class SoundCloudService: NSObject {
var account = Observable<Account?>(nil)
var loggedIn: Bool {
return account.get?.soundcloudAccount != nil
}
private var nextSoundsURL: NSURL?
override init() {
super.init()
NSNotificationCenter.defaultCenter().addObserverForName(SCSoundCloudAccountDidChangeNotification, object: nil, queue: NSOperationQueue.currentQueue()) { (notification) -> Void in
if let soundcloudAccount = SCSoundCloud.account() {
let account = Account()
account.soundcloudAccount = soundcloudAccount
self.account.set(account)
}
else {
self.account.set(nil)
}
}
}
deinit {
NSNotificationCenter.defaultCenter().removeObserver(self, name: SCSoundCloudAccountDidChangeNotification, object: nil)
}
func logIn() {
SCSoundCloud.requestAccessWithPreparedAuthorizationURLHandler { (preparedURL) -> Void in
NSWorkspace.sharedWorkspace().openURL(preparedURL)
}
}
func updateSounds() -> SignalProducer<[Sound], NSError> {
guard loggedIn else { return SignalProducer.empty }
return SignalProducer<[Sound], NSError> { [weak self] observer, disposal in
guard let _self = self else {
observer.sendCompleted()
return
}
SCRequest.performMethod(SCRequestMethodGET, onResource: NSURL(string: "https://api.soundcloud.com/me/activities.json"), usingParameters: nil, withAccount: _self.account.get?.soundcloudAccount, sendingProgressHandler: nil) { (response, data, error) -> Void in
if error != nil {
observer.sendFailed(error)
observer.sendCompleted()
return
}
if let jsonResponse = (try? NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions())) as? [String: AnyObject],
soundDictionaries = jsonResponse["collection"] as? JSONArray {
let sounds = _self.createSounds(soundDictionaries)
if let nextSoundsURLString = jsonResponse["next_href"] as? String {
_self.nextSoundsURL = NSURL(string: nextSoundsURLString)
}
observer.sendNext(sounds)
observer.sendCompleted()
}
}
}
}
func fetchNextSounds() -> SignalProducer<[Sound], NSError> {
guard loggedIn else { return SignalProducer.empty }
return SignalProducer<[Sound], NSError> { [weak self] observer, disposal in
guard let _self = self else {
observer.sendCompleted()
return
}
SCRequest.performMethod(SCRequestMethodGET, onResource: _self.nextSoundsURL, usingParameters: nil, withAccount: _self.account.get?.soundcloudAccount, sendingProgressHandler: nil) { (response, data, error) -> Void in
if error != nil {
observer.sendFailed(error)
observer.sendCompleted()
return
}
if let jsonResponse = (try? NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions())) as? [String: AnyObject],
soundDictionaries = jsonResponse["collection"] as? JSONArray {
let sounds = _self.createSounds(soundDictionaries)
if let nextSoundsURLString = jsonResponse["next_href"] as? String {
_self.nextSoundsURL = NSURL(string: nextSoundsURLString)
}
observer.sendNext(sounds)
observer.sendCompleted()
}
}
}
}
func createSounds(soundDictionaries: JSONArray) -> [Sound] {
return soundDictionaries.filter { dictionary in
guard let origin = dictionary["origin"] as? JSONObject else { return false }
let streamable = (origin["streamable"] as? Bool ?? false) == true
let isTrack = (origin["kind"] as? String ?? "") == "track"
return streamable && isTrack
}.map { dictionary in
do {
return try Sound.decode(JSON(dictionary))
}
catch {
NSLog("%@", "\(error)")
return nil
}
}.flatMap {$0}
}
func fetchPlayURL(sound: Sound) -> SignalProducer<NSURL, NSError> {
return SignalProducer<NSURL, NSError> { [weak self] observer, disposal in
if let playURL = sound.playURL {
observer.sendNext(playURL)
observer.sendCompleted()
return
}
self?.getStreamURL(sound) { streamURL, error in
if let URL = streamURL {
sound.playURL = URL
observer.sendNext(URL)
}
else if let error = error {
observer.sendFailed(error)
}
observer.sendCompleted()
}
}
}
private func getStreamURL(sound: Sound, completion: (NSURL!, NSError!) -> Void) {
guard let streamURL = sound.streamURL else { return }
let request = NXOAuth2Request(resource:streamURL, method:"GET", parameters:[:])
request.account = SCSoundCloud.account().oauthAccount
request.performRequestWithSendingProgressHandler(nil) { (response: NSURLResponse!, data: NSData!, error: NSError!) in
if let response = response as? NSHTTPURLResponse, URLString = response.allHeaderFields["Location"] as? String, streamURL = NSURL(string: URLString) {
completion(streamURL, nil)
}
else {
completion(nil, nil)
}
}
}
func fetchWaveform(sound: Sound) -> SignalProducer<Waveform, NSError> {
return SignalProducer<Waveform, NSError> { observer, disposal in
guard let waveformURL = sound.waveformURL else {
observer.sendFailed(NSError(domain: "", code: 0, userInfo: nil))
observer.sendCompleted()
return
}
let request = NSMutableURLRequest(URL: waveformURL)
request.HTTPShouldHandleCookies = false
Alamofire.request(.GET, waveformURL).responseJSON { response in
switch response.result {
case .Success(let json):
if let waveform = try? Waveform.decode(JSON(json)) {
observer.sendNext(waveform)
observer.sendCompleted()
return
}
// TODO: JSON was bad but something was still returned
observer.sendFailed(NSError(domain: "", code: 0, userInfo: nil))
observer.sendCompleted()
case .Failure(let error):
observer.sendFailed(error)
observer.sendCompleted()
}
}
}
}
func toggleFavorite(sound: Sound, completion: (() -> Void)? = nil) {
sound.favorite = !sound.favorite
let method = sound.favorite ? "PUT" : "DELETE"
let resource = NSURL(string:"https://api.soundcloud.com/me/favorites/\(sound.trackID)")
let request = NXOAuth2Request(resource: resource, method: method, parameters: nil)
request.account = SCSoundCloud.account().oauthAccount
request.performRequestWithSendingProgressHandler(nil) { (response, data, error) in
if error != nil {
NSLog("%@", "Error favoriting track: \(error), favorite: \(sound.favorite)")
sound.favorite = !sound.favorite;
}
completion?()
}
}
} | mit | ee212d28aeb56206b9a415990f2de6d0 | 39.82266 | 270 | 0.565291 | 5.325193 | false | false | false | false |
EZ-NET/ESOcean | ESOcean/Localize/Localizer.swift | 1 | 1283 | //
// Localizer.swift
// ESSwim
//
// Created by Tomohiro Kumagai on H27/04/20.
//
//
import Foundation
/// Get a localizer with main bundle and 'Localizable.strings'.
public let localizer = Localizer()
/// Localized Support.
public final class Localizer {
private let bundle:NSBundle
private let table:String?
/// Create a Localizer with the bundle and the table.
public init(bundle:NSBundle, table:String? = nil) {
self.bundle = bundle
self.table = table
}
/// Create a Localizer with Main bundle.
public convenience init(table:String? = nil) {
self.init(bundle:NSBundle.mainBundle(), table:table)
}
/// Create a Localizer with bundle for the class.
public convenience init(forClass `class`:AnyClass, table:String? = nil) {
let bundle = NSBundle(forClass: `class`)
self.init(bundle:bundle, table:table)
}
/// Get localized string for the key. Then, apply arguments to the localized string.
public func string(forKey:String, _ arguments:CVarArgType...) -> String {
let string = self.bundle.localizedStringForKey(forKey, value: nil, table: self.table)
if arguments.isEmpty {
return string
}
else {
let values = getVaList(arguments)
return NSString(format: string, arguments: values) as String
}
}
}
| mit | 28eac359014dda50ab521093ba9b922c | 21.508772 | 87 | 0.697584 | 3.686782 | false | false | false | false |
PedroTrujilloV/TIY-Assignments | 02--Fourth-Dimensionally/TipCalculator/TipCalculator.playground/Contents.swift | 1 | 1699 | let tipAndTotal = (4.00, 25.19)
tipAndTotal.0
tipAndTotal.1
let (theTipAmt,theTotal) = tipAndTotal
theTipAmt
theTotal
let tipAndTotalNamed = (tipAmt: 5.00, total: 30.25)
tipAndTotalNamed.tipAmt
let total = 21.09
let taxPercent = 0.06
let subTotal = total / (taxPercent + 1)
func calcTipWithTipPercent(tipPercent: Double) -> (tipAmount: Double, finalTotal: Double)
{
let tipAmount = subTotal * tipPercent
let finalTotal = total * tipAmount
return (tipAmount, finalTotal)
}
let totalWithTip = calcTipWithTipPercent(0.20)
class TipCalculator
{
let total: Double
let taxPct: Double
let subTotal: Double
init(total: Double, taxPct: Double)
{
self.total = total
self.taxPct = taxPct
self.subTotal = total / (taxPct + 1)
}
func calcTipWithTipPct(tipPct: Double) ->Double
{
return subTotal * tipPct
}
func printPossibleTips()
{
print("15%: $\(calcTipWithTipPct(0.15))")
print("18%: $\(calcTipWithTipPct(0.18))")
print("20%: $\(calcTipWithTipPct(0.20))")
}
func returnPossibleTips() -> [Int: Double]
{
let possibleTips = [0.15, 0.18, 0.20]
var rValue = [Int:Double]()
for possibleTip in possibleTips
{
let intPct = Int(possibleTip*100)
rValue[intPct] = calcTipWithTipPct(possibleTip)
}
return rValue
}
}
let tipCalc = TipCalculator (total:33.25, taxPct:0.06)
tipCalc.calcTipWithTipPct(0.15)
tipCalc.calcTipWithTipPct(0.20)
tipCalc.printPossibleTips()
let tipDictionary = tipCalc.returnPossibleTips()
tipDictionary[20]
class BodayPart
{
}
| cc0-1.0 | c53b842e9b150f4f1a8660ed27ea5e2b | 18.755814 | 89 | 0.632137 | 3.645923 | false | false | false | false |
pixelmaid/DynamicBrushes | swift/Palette-Knife/SavedFilesPanelViewController.swift | 1 | 2331 | //
// SavedFilesPanelViewController.swift
// DynamicBrushes
//
// Created by JENNIFER MARY JACOBS on 5/22/17.
// Copyright © 2017 pixelmaid. All rights reserved.
//
import Foundation
import UIKit
class FileCellData{
let id:String
let name:String
var selected:Bool
init(id:String,name:String){
self.id = id
self.name = name
self.selected = false
}
}
class SavedFilesPanelViewController: UITableViewController{
var files = [FileCellData]()
var fileEvent = Event<(String,String,String?)>();
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func loadFiles(newFiles:[String:String]){
files.removeAll();
for (key,value) in newFiles{
let id = key
let newFile = FileCellData(id: id, name: value)
files.append(newFile);
}
DispatchQueue.main.async {
self.tableView.reloadData();
}
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
return 1;
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return files.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "FileTableCell", for: indexPath) as! FileCell
let file = files[indexPath.row]
cell.label.text = file.name
if(file.selected){
cell.contentView.backgroundColor = UIColor.darkGray;
}
else{
cell.contentView.backgroundColor = UIColor.black;
}
cell.id = file.id;
cell.name = file.name;
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
for f in files {
f.selected = false;
}
files[indexPath.row].selected = true;
tableView.reloadData();
fileEvent.raise(data:("FILE_SELECTED",files[indexPath.row].id,files[indexPath.row].name))
}
}
| mit | 195754fc0d46a9d9a6392da08782b0a9 | 24.326087 | 110 | 0.599571 | 4.697581 | false | false | false | false |
davidozhang/spycodes | Spycodes/Utilities/SCRoundedButton.swift | 1 | 878 | import UIKit
class SCRoundedButton: SCButton {
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.contentEdgeInsets = UIEdgeInsetsMake(10, 30, 10, 30)
self.backgroundColor = .spycodesGreenColor()
self.layer.borderColor = UIColor.clear.cgColor
self.layer.cornerRadius = 24.0
self.setTitleColor(
.white,
for: UIControlState()
)
self.setTitleColor(
.spycodesGrayColor(),
for: .highlighted
)
self.titleLabel?.font = SCFonts.intermediateSizeFont(.bold)
}
override var isHighlighted: Bool {
didSet {
if isHighlighted {
self.backgroundColor = .spycodesDarkGreenColor()
} else {
self.backgroundColor = .spycodesGreenColor()
}
}
}
}
| mit | 13fb4285faf7c2ae42703202791dfc0c | 28.266667 | 67 | 0.575171 | 4.932584 | false | false | false | false |
dalu93/SwiftHelpSet | Sources/Foundation/NotificationCenter.swift | 1 | 3546 | //
// NotificationCenter.swift
// SwiftHelpSet
//
// Created by Luca D'Alberti on 7/14/16.
// Copyright © 2016 dalu93. All rights reserved.
//
import Foundation
/// Shared `NotificationCenter` instance
public let NotificationManager = NotificationCenterManager.default
/// Functional and easy wrap around `NSNotificationCenter` `Foundation` API
public class NotificationCenterManager {
fileprivate static let `default` = NotificationCenterManager()
/// The common handler called when the notification is triggered
public typealias GeneralNotificationHandler = (_ notification: Notification) -> ()
/**
Adds a new observer for the specific notification name
The queue is the `NSOperationQueue.mainQueue()` by default.
It returns a new `NSObjectProtocol` object that represents the observer
- parameter name: Notification's name
- parameter object: The object. Default is `nil`
- parameter queue: The specific queue. Default is `NSOperationQueue.mainQueue()`
- parameter handler: The handler called when the notification is triggered
- returns: `NSObjectProtocol` observer
*/
public func addObserverFor(name: NSNotification.Name, object: AnyObject? = nil, queue: OperationQueue? = OperationQueue.main, handler: @escaping GeneralNotificationHandler) -> NSObjectProtocol {
return NotificationCenter.default.addObserver(
forName: name,
object: object,
queue: queue,
using: handler
)
}
public func addObserverFor(names: [NSNotification.Name], object: AnyObject? = nil, queue: OperationQueue? = OperationQueue.main, handler: @escaping GeneralNotificationHandler) -> [NSObjectProtocol] {
return names.map { NotificationManager.addObserverFor(name: $0, handler: handler) }
}
/**
Removes an `NSObjectProtocol` observer as observer
- parameter observer: The observer to remove
- returns: The same `NotificationCenter` instance
*/
public func remove(observer: NSObjectProtocol) -> Self {
NotificationCenter.default.removeObserver(observer)
return self
}
/**
Removes an array of `NSObjectProtocol` observer as observer
- parameter observer: The observers to remove
- returns: The same `NotificationCenter` instance
*/
public func remove(observers: [NSObjectProtocol]) -> Self {
observers.forEach { _ = NotificationManager.remove(observer: $0) }
return self
}
/**
Posts a `NSNotification`
- parameter notification: The notification to post
- returns: The same `NotificationCenter` instance
*/
public func post(notification: Notification) -> Self {
NotificationCenter.default.post(notification)
return self
}
/**
Post a `NSNotification` by providing some basic information
- parameter name: Notification's name
- parameter object: The object
- parameter userInfo: The dictionary to attach
- returns: The same `NotificationCenter` instance
*/
public func postNotification(with name: NSNotification.Name, object: AnyObject? = nil, userInfo: [NSObject:AnyObject]? = nil) -> Self {
_ = post(
notification: Notification(
name: name,
object: object,
userInfo: userInfo
)
)
return self
}
}
| mit | 59cabe3ae75a43ffd01bdaadaf7652c2 | 32.761905 | 203 | 0.655289 | 5.395738 | false | false | false | false |
nessBautista/iOSBackup | iOSNotebook/Pods/RxCocoa/RxCocoa/Traits/Signal/Signal+Subscription.swift | 12 | 3036 | //
// Signal+Subscription.swift
// RxCocoa
//
// Created by Krunoslav Zaher on 9/19/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
import RxSwift
extension SharedSequenceConvertibleType where SharingStrategy == SignalSharingStrategy {
/**
Creates new subscription and sends elements to observer.
In this form it's equivalent to `subscribe` method, but it communicates intent better.
- parameter to: Observer that receives events.
- returns: Disposable object that can be used to unsubscribe the observer from the subject.
*/
public func emit<O: ObserverType>(to observer: O) -> Disposable where O.E == E {
return self.asSharedSequence().asObservable().subscribe(observer)
}
/**
Creates new subscription and sends elements to observer.
In this form it's equivalent to `subscribe` method, but it communicates intent better.
- parameter to: Observer that receives events.
- returns: Disposable object that can be used to unsubscribe the observer from the subject.
*/
public func emit<O: ObserverType>(to observer: O) -> Disposable where O.E == E? {
return self.asSharedSequence().asObservable().map { $0 as E? }.subscribe(observer)
}
/**
Creates new subscription and sends elements to variable.
- parameter relay: Target relay for sequence elements.
- returns: Disposable object that can be used to unsubscribe the observer from the variable.
*/
public func emit(to relay: PublishRelay<E>) -> Disposable {
return emit(onNext: { e in
relay.accept(e)
})
}
/**
Creates new subscription and sends elements to variable.
- parameter to: Target relay for sequence elements.
- returns: Disposable object that can be used to unsubscribe the observer from the variable.
*/
public func emit(to relay: PublishRelay<E?>) -> Disposable {
return emit(onNext: { e in
relay.accept(e)
})
}
/**
Subscribes an element handler, a completion handler and disposed handler to an observable sequence.
Error callback is not exposed because `Signal` can't error out.
- parameter onNext: Action to invoke for each element in the observable sequence.
- parameter onCompleted: Action to invoke upon graceful termination of the observable sequence.
gracefully completed, errored, or if the generation is canceled by disposing subscription)
- parameter onDisposed: Action to invoke upon any type of termination of sequence (if the sequence has
gracefully completed, errored, or if the generation is canceled by disposing subscription)
- returns: Subscription object used to unsubscribe from the observable sequence.
*/
public func emit(onNext: ((E) -> Void)? = nil, onCompleted: (() -> Void)? = nil, onDisposed: (() -> Void)? = nil) -> Disposable {
return self.asObservable().subscribe(onNext: onNext, onCompleted: onCompleted, onDisposed: onDisposed)
}
}
| cc0-1.0 | c8c88fd57e1af8e6fbfe2b576f8d3c54 | 37.910256 | 133 | 0.692586 | 4.934959 | false | false | false | false |
justinhester/SmokeOrFire | SmokeOrFire/SmokeOrFire/Controllers/ViewController.swift | 1 | 2386 | //
// ViewController.swift
// SmokeOrFire
//
// Created by Justin Lawrence Hester on 8/6/16.
// Copyright © 2016 Justin Lawrence Hester. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var playButton: UIButton!
@IBOutlet weak var pickerView: UIPickerView!
var totalPlayers = 2
override func viewDidLoad() {
super.viewDidLoad()
// Customize navigation bar.
navigationController!.navigationBar.tintColor = .whiteColor()
navigationController!.navigationBar.barTintColor = .blackColor()
// Customize play button.
playButton.layer.borderWidth = 4
playButton.layer.borderColor = UIColor.whiteColor().CGColor
playButton.layer.cornerRadius = 10
// Customize player picker.
pickerView.layer.borderWidth = 4
pickerView.layer.borderColor = UIColor.whiteColor().CGColor
pickerView.layer.cornerRadius = 10
pickerView.selectRow(totalPlayers - 1, inComponent: 0, animated: false)
}
// MARK: - Segue
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) {
if segue.identifier == "gameSegue" {
let gvc = segue.destinationViewController as! GameViewController
gvc.totalPlayers = totalPlayers
}
}
}
// MARK: - UIPickerViewDataSource
extension ViewController: UIPickerViewDataSource {
func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return 8 // Maximum possible players
}
}
// MARK: - UIPickerViewDelegate
extension ViewController: UIPickerViewDelegate {
func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
return "\(row + 1)"
}
func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
totalPlayers = row + 1
}
func pickerView(pickerView: UIPickerView, attributedTitleForRow row: Int, forComponent component: Int) -> NSAttributedString? {
let string = "\(row + 1)"
return NSAttributedString(string: string, attributes: [NSForegroundColorAttributeName:UIColor.whiteColor(), NSFontAttributeName: "AmericanTypewriter-Bold"])
}
}
| gpl-3.0 | 5e8b61ead41d436af2fbf4af00a7b967 | 32.125 | 164 | 0.692243 | 5.276549 | false | false | false | false |
SusanDoggie/Doggie | Sources/DoggieGraphics/ImageContext/ImageContextExtension.swift | 1 | 3576 | //
// ImageContextExtension.swift
//
// The MIT License
// Copyright (c) 2015 - 2022 Susan Cheng. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
extension ImageContext {
@inlinable
@inline(__always)
public func draw<C: ColorProtocol>(shape: Shape, winding: Shape.WindingRule, color: C) {
let color = color.convert(to: colorSpace, intent: renderingIntent)
self.draw(shape: shape, winding: winding, color: color.color, opacity: color.opacity)
}
@inlinable
@inline(__always)
public func draw(shape: Shape, stroke: Stroke<Pixel.Model>, opacity: Double = 1) {
self.draw(shape: shape.strokePath(stroke), winding: .nonZero, color: stroke.color, opacity: opacity)
}
}
extension ImageContext {
@inlinable
@inline(__always)
public func draw(rect: Rect, color: Pixel.Model, opacity: Double = 1) {
self.draw(shape: Shape(rect: rect), winding: .nonZero, color: color, opacity: opacity)
}
@inlinable
@inline(__always)
public func draw(roundedRect rect: Rect, radius: Radius, color: Pixel.Model, opacity: Double = 1) {
self.draw(shape: Shape(roundedRect: rect, radius: radius), winding: .nonZero, color: color, opacity: opacity)
}
@inlinable
@inline(__always)
public func draw(ellipseIn rect: Rect, color: Pixel.Model, opacity: Double = 1) {
self.draw(shape: Shape(ellipseIn: rect), winding: .nonZero, color: color, opacity: opacity)
}
@inlinable
@inline(__always)
public func draw(rect: Rect, stroke: Stroke<Pixel.Model>, opacity: Double = 1) {
self.draw(shape: Shape(rect: rect), stroke: stroke, opacity: opacity)
}
@inlinable
@inline(__always)
public func draw(roundedRect rect: Rect, radius: Radius, stroke: Stroke<Pixel.Model>, opacity: Double = 1) {
self.draw(shape: Shape(roundedRect: rect, radius: radius), stroke: stroke, opacity: opacity)
}
@inlinable
@inline(__always)
public func draw(ellipseIn rect: Rect, stroke: Stroke<Pixel.Model>, opacity: Double = 1) {
self.draw(shape: Shape(ellipseIn: rect), stroke: stroke, opacity: opacity)
}
}
extension ImageContext {
@inlinable
@inline(__always)
public func draw<Image: ImageProtocol>(image: Image, transform: SDTransform) {
self.draw(texture: Texture<Float32ColorPixel<Pixel.Model>>(image: image.convert(to: colorSpace, intent: renderingIntent), resamplingAlgorithm: resamplingAlgorithm), transform: transform)
}
}
| mit | 7795a6edb89912b506885aa5d49e8615 | 42.084337 | 194 | 0.696309 | 4.054422 | false | false | false | false |
tiggleric/CVCalendar | Pod/Classes/CVCalendarViewAnimator.swift | 6 | 3271 | //
// CVCalendarViewAnimator.swift
// CVCalendar
//
// Created by E. Mozharovsky on 12/27/14.
// Copyright (c) 2014 GameApp. All rights reserved.
//
import UIKit
class CVCalendarViewAnimator: NSObject, CVCalendarViewAnimatorDelegate {
override init() {
super.init()
}
func animateSelectionWithBounceEffect(dayView: CVCalendarDayView, withControlCooordinator coordinator: CVCalendarDayViewControlCoordinator) {
dayView.setDayLabelHighlighted()
dayView.dayLabel?.transform = CGAffineTransformMakeScale(0.5, 0.5)
dayView.circleView?.transform = CGAffineTransformMakeScale(0.5, 0.5)
UIView.animateWithDuration(0.5, delay: 0, usingSpringWithDamping: 0.3, initialSpringVelocity: 0.1, options: UIViewAnimationOptions.BeginFromCurrentState, animations: { () -> Void in
coordinator.animationStarted()
dayView.circleView?.transform = CGAffineTransformMakeScale(1, 1)
dayView.dayLabel?.transform = CGAffineTransformMakeScale(1, 1)
}) { (Bool) -> Void in
coordinator.animationEnded()
}
}
func animateDeselectionWithRollingEffect(dayView: CVCalendarDayView, withControlCooordinator coordinator: CVCalendarDayViewControlCoordinator) {
UIView.animateWithDuration(0.25, delay: 0, options: UIViewAnimationOptions.CurveEaseInOut, animations: { () -> Void in
coordinator.animationStarted()
dayView.circleView?.transform = CGAffineTransformMakeScale(0.1, 0.1)
dayView.circleView?.alpha = 0.0
}) { (Bool) -> Void in
dayView.setDayLabelUnhighlighted()
coordinator.animationEnded()
}
}
func animateDeselectionWithBubbleEffect(dayView: CVCalendarDayView, withControlCooordinator coordinator: CVCalendarDayViewControlCoordinator) {
UIView.animateWithDuration(0.15, delay: 0, usingSpringWithDamping: 0.6, initialSpringVelocity: 0.8, options: UIViewAnimationOptions.CurveEaseOut, animations: { () -> Void in
coordinator.animationStarted()
dayView.circleView?.transform = CGAffineTransformMakeScale(1.3, 1.3)
}) { (Bool) -> Void in
UIView.animateWithDuration(0.2, delay: 0, options: UIViewAnimationOptions.CurveEaseInOut, animations: { () -> Void in
dayView.circleView!.transform = CGAffineTransformMakeScale(0.1, 0.1)
}) { (Bool) -> Void in
dayView.setDayLabelUnhighlighted()
coordinator.animationEnded()
}
}
}
// MARK: - Animator Delegate
func animateSelection(dayView: CVCalendarDayView, withControlCoordinator coordinator: CVCalendarDayViewControlCoordinator) {
self.animateSelectionWithBounceEffect(dayView, withControlCooordinator: coordinator)
}
func animateDeselection(dayView: CVCalendarDayView, withControlCoordinator coordinator: CVCalendarDayViewControlCoordinator) {
self.animateDeselectionWithRollingEffect(dayView, withControlCooordinator: coordinator)
}
}
| mit | 2f171c1c1e0cd3028347b9be92857031 | 43.202703 | 189 | 0.660349 | 5.488255 | false | false | false | false |
igormatyushkin014/DataKit | DataKit/Storage/InMemoryStorage.swift | 1 | 8018 | //
// InMemoryStorage.swift
// DataKit
//
// Created by Igor Matyushkin on 01.07.16.
// Copyright © 2016 Igor Matyushkin. All rights reserved.
//
import UIKit
public class InMemoryStorage: NSObject {
// MARK: Class variables & properties
// MARK: Public class methods
public class func defaultStorage() -> InMemoryStorage {
struct Singleton {
static let storage = InMemoryStorage()
}
return Singleton.storage
}
// MARK: Private class methods
// MARK: Initializers
override init() {
super.init()
// Initialize tables collection
tables = [String : AnyObject]()
}
// MARK: Deinitializer
deinit {
}
// MARK: Object variables & properties
private var tables: [String : AnyObject]!
// MARK: Public object methods
public func tableForObjectWithType<ObjectClass: NSObject>(objectType: ObjectClass.Type) -> InMemoryTable<ObjectClass> {
let objectClassName = NSStringFromClass(objectType)
var tableForSpecifiedClass = tables[objectClassName] as? InMemoryTable<ObjectClass>
if tableForSpecifiedClass == nil {
tableForSpecifiedClass = InMemoryTable<ObjectClass>()
tables[objectClassName] = tableForSpecifiedClass
}
return tableForSpecifiedClass!
}
// MARK: Private object methods
// MARK: Protocol methods
@discardableResult
public func numberOfAllObjectsOfType<ObjectClass: NSObject>(type: ObjectClass.Type, withCompletion completion: @escaping (_ numberOfObjects: Int) -> Void) -> Self {
let table = tableForObjectWithType(objectType: ObjectClass.self)
table.numberOfAllObjectsWithCompletion(completion: completion)
return self
}
@discardableResult
public func numberOfObjectsOfType<ObjectClass: NSObject>(type: ObjectClass.Type, withPredicateBlock predicateBlock: @escaping (_ object: ObjectClass) -> Bool, andCompletion completion: @escaping (_ numberOfObjects: Int) -> Void) -> Self {
let table = tableForObjectWithType(objectType: ObjectClass.self)
table.numberOfObjectsWithPredicateBlock(predicateBlock: predicateBlock, andCompletion: completion)
return self
}
@discardableResult
public func numberOfObjectsOfType<ObjectClass: NSObject>(type: ObjectClass.Type, meetingCondition condition: String, andCompletion completion: @escaping (_ numberOfObjects: Int) -> Void) -> Self {
let table = tableForObjectWithType(objectType: ObjectClass.self)
table.numberOfObjectsMeetingCondition(condition: condition, andCompletion: completion)
return self
}
@discardableResult
public func findAllObjectsOfType<ObjectClass: NSObject>(type: ObjectClass.Type, withCompletion completion: @escaping (_ objects: [ObjectClass]) -> Void) -> Self {
let table = tableForObjectWithType(objectType: ObjectClass.self)
table.findAllObjectsWithCompletion(completion: completion)
return self
}
@discardableResult
public func findAllObjectsOfType<ObjectClass: NSObject>(type: ObjectClass.Type, withPredicateBlock predicateBlock: @escaping (_ object: ObjectClass) -> Bool, andCompletion completion: @escaping (_ objects: [ObjectClass]) -> Void) -> Self {
let table = tableForObjectWithType(objectType: ObjectClass.self)
table.findAllObjectsWithPredicateBlock(predicateBlock: predicateBlock, andCompletion: completion)
return self
}
@discardableResult
public func findAllObjectsOfType<ObjectClass: NSObject>(type: ObjectClass.Type, meetingCondition condition: String, andCompletion completion: @escaping (_ objects: [ObjectClass]) -> Void) -> Self {
let table = tableForObjectWithType(objectType: ObjectClass.self)
table.findAllObjectsMeetingCondition(condition: condition, andCompletion: completion)
return self
}
@discardableResult
public func findFirstObjectOfType<ObjectClass: NSObject>(type: ObjectClass.Type, withPredicateBlock predicateBlock: @escaping (_ object: ObjectClass) -> Bool, andCompletion completion: @escaping (_ object: ObjectClass?) -> Void) -> Self {
let table = tableForObjectWithType(objectType: ObjectClass.self)
table.findFirstObjectWithPredicateBlock(predicateBlock: predicateBlock, andCompletion: completion)
return self
}
@discardableResult
public func findFirstObjectOfType<ObjectClass: NSObject>(type: ObjectClass.Type, meetingCondition condition: String, andCompletion completion: @escaping (_ object: ObjectClass?) -> Void) -> Self {
let table = tableForObjectWithType(objectType: ObjectClass.self)
table.findFirstObjectMeetingCondition(condition: condition, andCompletion: completion)
return self
}
@discardableResult
public func insertObject<ObjectClass: NSObject>(object: ObjectClass, withCompletion completion: (() -> Void)?) -> Self {
let table = tableForObjectWithType(objectType: ObjectClass.self)
table.insertObject(object: object, withCompletion: completion)
return self
}
/**
This method does nothing for in-memory storage
since no special operation is required to save
updated object.
*/
@discardableResult
public func updateObject<ObjectClass: NSObject>(object: ObjectClass, withCompletion completion: (() -> Void)?) -> Self {
completion?()
return self
}
@discardableResult
public func deleteAllObjectsOfType<ObjectClass: NSObject>(type: ObjectClass.Type, withCompletion completion: ((_ numberOfDeletedObjects: Int) -> Void)?) -> Self {
let table = tableForObjectWithType(objectType: ObjectClass.self)
table.deleteAllObjectsWithCompletion(completion: completion)
return self
}
@discardableResult
public func deleteAllObjectsOfType<ObjectClass: NSObject>(type: ObjectClass.Type, withPredicateBlock predicateBlock: @escaping (_ object: ObjectClass) -> Bool, andCompletion completion: ((_ numberOfDeletedObjects: Int) -> Void)?) -> Self {
let table = tableForObjectWithType(objectType: ObjectClass.self)
table.deleteAllObjectsWithPredicateBlock(predicateBlock: predicateBlock, andCompletion: completion)
return self
}
@discardableResult
public func deleteAllObjectsOfType<ObjectClass: NSObject>(type: ObjectClass.Type, meetingCondition condition: String, andCompletion completion: ((_ numberOfDeletedObjects: Int) -> Void)?) -> Self {
let table = tableForObjectWithType(objectType: ObjectClass.self)
table.deleteAllObjectsMeetingCondition(condition: condition, andCompletion: completion)
return self
}
@discardableResult
public func deleteFirstObjectOfType<ObjectClass: NSObject>(type: ObjectClass.Type, withPredicateBlock predicateBlock: @escaping (_ object: ObjectClass) -> Bool, andCompletion completion: ((_ deleted: Bool) -> Void)?) -> Self {
let table = tableForObjectWithType(objectType: ObjectClass.self)
table.deleteFirstObjectWithPredicateBlock(predicateBlock: predicateBlock, andCompletion: completion)
return self
}
@discardableResult
public func deleteFirstObjectOfType<ObjectClass: NSObject>(type: ObjectClass.Type, meetingCondition condition: String, andCompletion completion: ((_ deleted: Bool) -> Void)?) -> Self {
let table = tableForObjectWithType(objectType: ObjectClass.self)
table.deleteFirstObjectMeetingCondition(condition: condition, andCompletion: completion)
return self
}
@discardableResult
public func clearStorageWithCompletion(completion: (() -> Void)?) -> Self {
tables.removeAll(keepingCapacity: false)
completion?()
return self
}
}
| mit | fa93ed12bba0df651c77fd69302d0932 | 41.194737 | 243 | 0.702632 | 5.376928 | false | false | false | false |
kwallet/planet | PlanetTests/PlanetTests.swift | 1 | 2360 | //
// PlanetTests.swift
// PlanetTests
//
// Created by Mikael Konutgan on 14/07/16.
// Copyright © 2016 kWallet GmbH. All rights reserved.
//
import XCTest
@testable import Planet
class PlanetTests: XCTestCase {
func testFindingAustria() {
let locale = Locale(identifier: "de_AT")
let dataSource = CountryDataSource(locale: locale)
let country = dataSource.find("Österre").first
XCTAssertEqual(country?.name, "Österreich")
XCTAssertEqual(country?.isoCode, "AT")
XCTAssertEqual(country?.callingCode, "+43")
}
func testFindingGermany() {
let locale = Locale(identifier: "de_AT")
let dataSource = CountryDataSource(locale: locale)
let country = dataSource.find("Schland").first
XCTAssertEqual(country?.name, "Deutschland")
XCTAssertEqual(country?.isoCode, "DE")
XCTAssertEqual(country?.callingCode, "+49")
}
func testFindingAustriaInEnglish() {
let locale = Locale(identifier: "en_US")
let dataSource = CountryDataSource(locale: locale)
let country = dataSource.find("Austria").first
XCTAssertEqual(country?.name, "Austria")
XCTAssertEqual(country?.isoCode, "AT")
XCTAssertEqual(country?.callingCode, "+43")
}
func testDataSourceWithCustomCountryCodes() {
let locale = Locale(identifier: "en_US")
let dataSource = CountryDataSource(locale: locale, countryCodes: ["AT", "DE", "CH"])
XCTAssertEqual(dataSource.count(1), 3)
let includedCountry = dataSource.find("Austria").first
XCTAssertEqual(includedCountry?.isoCode, "AT")
let notIncludedCountry = dataSource.find("United States").first
XCTAssertNil(notIncludedCountry)
}
func testDataSourceWithNonRegionalLocale() {
let locale = Locale(identifier: "en")
let dataSource = CountryDataSource(locale: locale, countryCodes: ["AT", "DE", "CH"])
XCTAssertEqual(dataSource.count(1), 3)
let includedCountry = dataSource.find("Austria").first
XCTAssertEqual(includedCountry?.isoCode, "AT")
let notIncludedCountry = dataSource.find("United States").first
XCTAssertNil(notIncludedCountry)
}
}
| mit | f26b358a56c9c9f6004f700b4af1464b | 30.013158 | 92 | 0.633432 | 4.658103 | false | true | false | false |
CrowdShelf/ios | CrowdShelf/CrowdShelf/Views/MessagePopupView.swift | 1 | 4645 | //
// MessagePopupView.swift
// CrowdShelf
//
// Created by Øyvind Grimnes on 29/09/15.
// Copyright © 2015 Øyvind Grimnes. All rights reserved.
//
import UIKit
enum MessagePopupStyle: Int {
case Normal
case Success
case Error
case Warning
func textColor() -> UIColor {
return UIColor.blackColor()
switch self {
case .Normal:
return UIColor.blackColor()
case .Success:
return UIColor.greenColor()
case .Error:
return UIColor.redColor()
case .Warning:
return UIColor.yellowColor()
}
}
}
class MessagePopupView: UIVisualEffectView {
let message: String
let style: MessagePopupStyle
private var topSpaceConstraint: NSLayoutConstraint?
init(message: String, messageStyle: MessagePopupStyle = .Normal) {
self.message = message
self.style = messageStyle
super.init(effect: UIBlurEffect(style: .ExtraLight))
self.initializeView()
}
required init?(coder aDecoder: NSCoder) {
self.message = ""
self.style = .Normal
super.init(coder: aDecoder)
self.initializeView()
}
private func initializeView() {
self.translatesAutoresizingMaskIntoConstraints = false
addLabel()
addSeparator()
}
private func addSeparator() {
let separator = UIView()
separator.backgroundColor = UIColor.lightGrayColor()
separator.translatesAutoresizingMaskIntoConstraints = false
self.addSubview(separator)
self.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|[separator]|", options: .AlignAllBaseline, metrics: nil, views: ["separator": separator]))
self.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:[separator(1)]|", options: .AlignAllBaseline, metrics: nil, views: ["separator": separator]))
}
private func addLabel() {
let label = UILabel()
label.text = message
label.textColor = self.style.textColor()
label.textAlignment = .Center
label.translatesAutoresizingMaskIntoConstraints = false
self.addSubview(label)
self.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-[label]-|", options: .AlignAllBaseline, metrics: nil, views: ["label": label]))
self.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-20-[label]|", options: .AlignAllBaseline, metrics: nil, views: ["label": label]))
}
private func slideIn(completionHandler: ((Bool)->Void)?) {
self.hidden = false
self.superview?.layoutIfNeeded()
UIView.animateWithDuration(0.8, animations: { () -> Void in
self.topSpaceConstraint?.constant = 0
self.superview?.layoutIfNeeded()
}) { (finished) -> Void in
completionHandler?(finished)
}
}
private func slideOut(completionHandler: ((Bool)->Void)?) {
self.hidden = false
self.superview?.layoutIfNeeded()
UIView.animateWithDuration(0.5, animations: { () -> Void in
self.topSpaceConstraint?.constant = -64
self.superview?.layoutIfNeeded()
}) { (finished) -> Void in
completionHandler?(finished)
}
}
func show() {
dispatch_async(dispatch_get_main_queue()) { () -> Void in
let view = UIApplication.sharedApplication().keyWindow!.subviews.first!
view.addSubview(self)
/* Add constraints */
view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|[messageView]|", options: .AlignAllBaseline, metrics: nil, views: ["messageView":self]))
view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:[messageView(64)]", options: .AlignAllCenterY, metrics: nil, views: ["messageView":self]))
self.topSpaceConstraint = NSLayoutConstraint.constraintsWithVisualFormat("V:|-(-64)-[messageView]", options: .AlignAllCenterY, metrics: nil, views: ["messageView":self]).first!
view.addConstraint(self.topSpaceConstraint!)
/* Slide in and out */
self.slideIn({ (finished) -> Void in
Utilities.delayDispatchInQueue(dispatch_get_main_queue(), delay: 1.0, block: { () -> Void in
self.slideOut(nil)
})
})
}
}
} | mit | 9db7b45eb0e42a66f507e144eaed1390 | 32.644928 | 188 | 0.606204 | 5.366474 | false | false | false | false |
tad-iizuka/swift-sdk | Source/RestKit/RestToken.swift | 2 | 2329 | /**
* 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
/**
A `RestToken` object retrieves, stores, and refreshes an authentication token. The token is
retrieved at a particular URL using basic authentication credentials (i.e. username and password).
*/
public class RestToken {
public var token: String?
public var isRefreshing = false
public var retries = 0
private var tokenURL: String
private var credentials: Credentials
/**
Create a `RestToken`.
- parameter tokenURL: The URL that shall be used to obtain a token.
- parameter username: The username credential used to obtain a token.
- parameter password: The password credential used to obtain a token.
*/
public init(tokenURL: String, username: String, password: String) {
self.tokenURL = tokenURL
self.credentials = Credentials.basicAuthentication(username: username, password: password)
}
/**
Refresh the authentication token.
- parameter failure: A function executed if an error occurs.
- parameter success: A function executed after a new token is retrieved.
*/
public func refreshToken(
failure: ((Error) -> Void)? = nil,
success: ((Void) -> Void)? = nil)
{
let request = RestRequest(
method: "GET",
url: tokenURL,
credentials: credentials,
headerParameters: [:])
// TODO - validate request
request.responseString { response in
switch response.result {
case .success(let token):
self.token = token
success?()
case .failure(let error):
failure?(error)
}
}
}
}
| apache-2.0 | 42f1d2d0e36eceb64ea317dccb7799ec | 31.802817 | 99 | 0.642336 | 4.872385 | false | false | false | false |
chenchangqing/learniosmap | example01/example01/GuideLineViewController.swift | 1 | 11439 | //
// GuideLineViewController.swift
// example01
//
// Created by green on 15/8/7.
// Copyright (c) 2015年 com.chenchangqing. All rights reserved.
//
import UIKit
import MapKit
class GuideLineViewController: UIViewController,MKMapViewDelegate,UIActionSheetDelegate,CLLocationManagerDelegate {
@IBOutlet weak var lineDetailL : UILabel!
@IBOutlet weak var mapView : MKMapView!
private let request = MKDirectionsRequest() // 导航请求
private var transportType : MKDirectionsTransportType? // 当前导航类型
{
willSet {
if let newValue = newValue {
// 设置新的导航类型
request.transportType = newValue
// 删除已有的路线
for mkRoute in mkRouteArray {
mapView.removeOverlay(mkRoute.polyline)
}
// 重新绘制路线
if let destinationPlaceMark=destinationPlaceMark {
self.drawGuideLine(destinationPlaceMark)
}
}
}
}
var destinationCoordinate : CLLocationCoordinate2D? // 目标经纬度
{
willSet{
if let newValue=newValue {
if !CLLocationCoordinate2DIsValid(newValue) {
return
}
// 地图区域
let currentLocationSpan = MKCoordinateSpanMake(0.05, 0.05)
let currentRegion = MKCoordinateRegionMake(newValue, currentLocationSpan)
self.mapView.setRegion(currentRegion, animated: false)
// 经纬度转地址
geocoder.reverseGeocodeLocation(CLLocation(latitude: newValue.latitude, longitude: newValue.longitude), completionHandler: { (array, error) -> Void in
if let error=error {
println("目的地定位失败")
return
}
if array.count > 0 {
self.destinationPlaceMark = array[0] as? CLPlacemark
self.transportType = MKDirectionsTransportType.Automobile
// 增加出发地标注
self.destinationAnnotation = MKPointAnnotation()
self.destinationAnnotation!.title = self.destinationPlaceMark!.name
self.destinationAnnotation!.coordinate = newValue
self.mapView.addAnnotation(self.destinationAnnotation!)
}
})
} else {
if let destinationAnnotation=destinationAnnotation {
self.mapView.removeAnnotation(destinationAnnotation)
}
self.destinationPlaceMark = nil
self.destinationAnnotation = nil
}
}
}
private var destinationAnnotation : MKPointAnnotation? // 目的地标注
private var destinationPlaceMark : CLPlacemark? // 目的地信息
private var mapLauncher : ASMapLauncher! // 打开地图的工具类
private var mkRouteArray = [MKRoute]() // 路线数组
private let geocoder = CLGeocoder() // 编码反编码
// 定位服务
lazy var locationManager : CLLocationManager = {
let locationManager = CLLocationManager()
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.distanceFilter = 10
if UIDevice.currentDevice().systemVersion >= "8.0.0" {
locationManager.requestWhenInUseAuthorization()
}
return locationManager
}()
// MARK: -
override func viewDidLoad() {
super.viewDidLoad()
mapLauncher = ASMapLauncher()
mapView.delegate = self // 地图代理
request.requestsAlternateRoutes = false // 设置是否搜索多条线路
mapView.showsUserLocation = true
// 开始定位
startUpdatingL()
// 触发增加标注、划线
self.destinationCoordinate = CLLocationCoordinate2D(latitude:31.216739784766 , longitude: 121.587560439984)
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
}
// MARK: -
/**
* 开始定位
*/
func startUpdatingL() {
if CLLocationManager.locationServicesEnabled() {
if CLLocationManager.authorizationStatus() == CLAuthorizationStatus.Denied {
let alertVC = UIAlertController(title: "提示", message: "需要开启定位服务,请到设置->隐私,打开定位服务", preferredStyle: UIAlertControllerStyle.Alert)
let ok = UIAlertAction(title: "好", style: UIAlertActionStyle.Default, handler: nil)
alertVC.addAction(ok)
self.presentViewController(alertVC, animated: true, completion: nil)
} else {
locationManager.startUpdatingLocation()
}
}
}
/**
* 根据地理信息规划路线
* @param sourceMark 出发地位置信息
* @param destinationMark 目的地位置信息
*
* @return
*/
private func drawGuideLine(destinationMark:CLPlacemark) {
// 开始地点节点
request.setSource(MKMapItem.mapItemForCurrentLocation())
// 结束地点节点
let destinationmkmark = MKPlacemark(placemark: destinationMark)
let destinationItem = MKMapItem(placemark: destinationmkmark)
request.setDestination(destinationItem)
// 从apple服务器获取数据的连接类
let directions = MKDirections(request: request)
// 开始计算路线信息
directions.calculateDirectionsWithCompletionHandler { (response, error) -> Void in
if let error = error {
println("计算路线失败")
return
}
self.mkRouteArray = response.routes as! [MKRoute]
if self.mkRouteArray.count != 1 {
println("查询出\(self.mkRouteArray.count)条路线")
return
}
for mkRoute in self.mkRouteArray {
self.mapView.addOverlay(mkRoute.polyline)
let cgTravelTime = CGFloat(mkRoute.expectedTravelTime)
let caculatedTime = SecondFormat.formatTime(cgTravelTime)
self.lineDetailL.text = "\(caculatedTime),\(mkRoute.distance)米"
}
}
}
// MARK: -
/**
* 打开苹果地图或谷歌地图
*/
@IBAction func navigationClick(sender: UIButton) {
if let sourceCoordinate=mapView.userLocation {
if let destinationCoordinate=destinationCoordinate {
// 使用ActionSheet
let actionSheet = UIActionSheet(title: "请选择", delegate: self, cancelButtonTitle: nil, destructiveButtonTitle: nil)
for mapApp in mapLauncher.getMapApps() {
actionSheet.addButtonWithTitle(mapApp as! String)
}
actionSheet.addButtonWithTitle("取消")
actionSheet.cancelButtonIndex = mapLauncher.getMapApps().count
actionSheet.showInView(self.view)
}
}
}
// MARK: - UIActionSheetDelegate
func actionSheet(actionSheet: UIActionSheet, clickedButtonAtIndex buttonIndex: Int) {
if buttonIndex == actionSheet.numberOfButtons - 1 {
return
}
let mapApp = mapLauncher.getMapApps()[buttonIndex] as! String
let fromMapPoint = ASMapPoint(location: mapView.userLocation.location , name: "", address: "")
let toMapPoint = ASMapPoint(location: CLLocation(latitude: destinationCoordinate!.latitude, longitude: destinationCoordinate!.longitude), name: "", address: "")
mapLauncher.launchMapApp(ASMapApp(rawValue: mapApp)!, fromDirections: fromMapPoint, toDirection: toMapPoint)
}
// MARK: -
/**
* 根据导航类型重新绘制路线
*/
@IBAction func changeGuideType(sender: UISegmentedControl) {
// println(sender.titleForSegmentAtIndex(sender.selectedSegmentIndex)!)
// 自驾
if sender.selectedSegmentIndex == 0 {
self.transportType = MKDirectionsTransportType.Automobile
}
// 步行
if sender.selectedSegmentIndex == 1 {
self.transportType = MKDirectionsTransportType.Walking
}
}
// MARK: - MKMapViewDelegate
/*
* 渲染标注
*/
func mapView(mapView: MKMapView!, viewForAnnotation annotation: MKAnnotation!) -> MKAnnotationView! {
let identifierStr = "pinAnnotationView"
var pinAnnotationView = mapView.dequeueReusableAnnotationViewWithIdentifier(identifierStr) as? MKPinAnnotationView
if pinAnnotationView == nil {
pinAnnotationView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: identifierStr)
// 显示标注提示
pinAnnotationView!.canShowCallout = true
}
// 大头针颜色
if annotation is MKUserLocation {
pinAnnotationView!.pinColor = MKPinAnnotationColor.Green
}
if annotation is MKPointAnnotation {
pinAnnotationView!.pinColor = MKPinAnnotationColor.Red
}
return pinAnnotationView
}
/*
* 渲染路线
*/
func mapView(mapView: MKMapView!, rendererForOverlay overlay: MKOverlay!) -> MKOverlayRenderer! {
let render = MKPolylineRenderer(polyline: overlay as! MKPolyline)
render.lineWidth = 5
render.strokeColor = UIColor.blueColor()
return render
}
// MARK: - CLLocationManagerDelegate
func locationManager(manager: CLLocationManager!, didFailWithError error: NSError!) {
locationManager.stopUpdatingLocation()
}
func locationManager(manager: CLLocationManager!, didUpdateToLocation newLocation: CLLocation!, fromLocation oldLocation: CLLocation!) {
}
}
| mit | 72d82b93ce47ac06612faf9816c35a79 | 32.860248 | 170 | 0.533798 | 5.970975 | false | false | false | false |
EZ-NET/ESSwim | Sources/Deprecated.swift | 1 | 7132 | //
// Deprecated.swift
// ESSwim
//
// Created by Tomohiro Kumagai on H27/08/07.
//
//
import Foundation
/**
Generate an Array having `elements`.
*/
@available(*, unavailable, message="use array literal. (e.g. [t1, t2, t3, t4])")
@noreturn public func array<T>(elements:T...) -> [T] {}
@available(*, unavailable, message="access the 'forEach' method on the SequenceType")
public func foreach<C:SequenceType>(domain:C, @noescape _ predicate:(C.Generator.Element) -> Void) -> Void {}
@available(*, unavailable)
@noreturn public func foreach<C:SequenceType>(domain:C) -> (((C.Generator.Element) -> Void) -> Void) {}
/// Make indexes of `domain` by distances.
@available(*, unavailable, message="access the 'indexesOf' method on the CollectionType")
@noreturn public func indexesOf<C:CollectionType>(domain:C, by distances:[C.Index.Distance]) -> [C.Index] {}
// Make indexes of `domain` to meet `predicate`.
@available(*, unavailable, message="access the 'indexesOf' method on the CollectionType")
@noreturn public func indexesOf<C:CollectionType where C.Index.Distance : IntegerType>(domain:C, @noescape predicate:(C.Generator.Element) -> Bool) -> [C.Index] {}
/// Get elements that same element appeared more than once.
@available(*, unavailable, message="access the 'elementsAppearedDupplicately' method on the CollectionType")
@noreturn public func elementsAppearedDupplicately<C:CollectionType where C.Generator.Element : Equatable>(domain:C) -> [C.Generator.Element] {}
/// Get an Array that has distinct elements.
/// If same element found, leaved the first element only.
@available(*, unavailable, message="access the 'distinct' method on the CollectionType")
@noreturn public func distinct<C:CollectionType where C.Generator.Element : Equatable>(domain:C) -> [C.Generator.Element] {}
/// Remove elements at `indexes` from `domain`.
@available(*, unavailable, message="access the 'remvoe' method on the CollectionType")
@noreturn public func remove<C:RangeReplaceableCollectionType where C.Index.Distance : SignedIntegerType>(inout domain:C, indexes:[C.Index]) { fatalError()}
/// Get filtered Array by exclude the `indexes`.
@available(*, unavailable, message="access the 'filter' method on the CollectionType")
@noreturn public func filter<C:CollectionType>(domain:C, excludeIndexes indexes:[C.Index]) -> [C.Generator.Element] {}
/**
Find `index` in the `domain`.
:return: `FindResult` that considering if `index` was not found.
*/
@available(*, unavailable, message="'find' is unavailable: access the 'find' method on the FindableType.")
@noreturn public func find<F:FindableType>(domain:F, _ index:F.FindIndex) -> F.FindResult {}
/**
Search `value` in the domain.
:return: `SearchResult` that considering if `value` was not found.
*/
@available(*, unavailable, message="'search' is unavailable: access the 'search' method on the SearchableType.")
@noreturn public func search<S:SearchableType>(domain:S, _ value:S.SearchValue) -> S.SearchResult {}
/**
Search with `predicate` in the domain.
:return: `SearchResult` that considering if `value` was not found.
*/
@available(*, unavailable, message="'search' is unavailable: access the 'search' method on the SearchableType.")
@noreturn public func search<S:SearchableType>(domain:S, _ predicate:(S.SearchElement)->S.SearchState) -> S.SearchResult {}
/**
Returns the first index where `predicate` become true in `domain` or `nil` if `value` is not found.
*/
@available(*, unavailable, message="'find' is unavailable: access the 'indexOf' method on the CollectionType.")
@noreturn public func find<C : CollectionType>(collection domain: C, _ predicate:(C.Generator.Element) -> Bool) -> C.Index? { }
/**
Returns the first index where `value` appears in `domain` or `nil` if `value` is not found.
*/
@available(*, unavailable, message="access the 'findElement' method on the SequenceType")
@noreturn public func find<S:SequenceType where S.Generator.Element : Equatable>(sequence domain:S, _ value:S.Generator.Element) -> EnumerateSequence<S>.Generator.Element? { }
/**
Returns the first index where `predicate` become true in `domain` or `nil` if `value` is not found.
*/
@available(*, unavailable, message="access the 'findElement' method on the SequenceType")
@noreturn public func find<S:SequenceType>(sequence domain:S, _ predicate:(S.Generator.Element) -> Bool) -> EnumerateSequence<S>.Generator.Element? { }
/**
Processing each value of `domain` with `predicate` in order.
If predicate returns .Abort, abort processing and return .Aborted.
:return: .Passed if all elements processed, otherwise .Aborted.
*/
@available(*, unavailable, message="If you want index of element, use `traverse(enumerate(S), predicate)`.")
@noreturn public func traverse<S:SequenceType>(domain:S, @noescape _ predicate:(element:S.Generator.Element, index:Int) -> Swim.ContinuousState) -> Swim.ProcessingState { }
/**
Processing each value of `domain` with `predicate` in order.
If predicate returns .Abort, abort processing and return .Aborted.
If you want index of element, use this function with enumerate(sequence) as `S`.
:return: .Passed if all elements processed, otherwise .Aborted.
*/
@available(*, unavailable, message="'traverse' is unavailable: access the 'traverse' method on the SequenceType.")
@noreturn public func traverse<S:SequenceType>(domain:S, @noescape _ predicate:(S.Generator.Element) -> Swim.ContinuousState) -> Swim.ProcessingState {}
/**
Processing each value of `domain` with `predicate` in order.
If predicate returns non-nil value, abort processing and return the result value.
:return: result of `predicate` if `predicate` results non-nil value, otherwise nil.
*/
@available(*, unavailable, message="'traverse' is unavailable: access the 'traverse' method on the SequenceType.")
@noreturn public func traverse<C:SequenceType,R>(domain:C, @noescape _ predicate:(C.Generator.Element) -> R?) -> R? {}
/// Returns the first index where `string` appears in `domain`.
@available(*, unavailable, message="access the 'indexOf' method on the String")
@noreturn public func find(domain:String, _ string:String) -> String.Index? {}
/// Returns the first index where `string` appears after `fromIndex` in `domain`.
@available(*, unavailable, message="access the 'indexOf' method on the String")
@noreturn public func find(domain:String, _ string:String, fromIndex:String.Index) -> String.Index? {}
/// Split string by separator.
@available(*, unavailable, message="access the 'split' method on the String")
@noreturn public func split(string:String, _ separator:String) -> [String] {}
/// Make a quoted string by `quotation`. if `quotation` is found in `string`, replace this place to `escaping`.
@available(*, unavailable, message="access the 'quote' method on the String")
@noreturn public func quoted(string:String, _ quotation:String, _ escaping:String) -> String {}
/// Returns a new string in which all occurrences of a `target` string are replaced by `replacement`.
@available(*, unavailable, message="access the 'replace' method on the String")
@noreturn public func replaced(string:String, _ target:String, _ replacement:String) -> String {}
| mit | 85425d3449f7193c62f23803e67f8709 | 53.861538 | 175 | 0.740045 | 3.953437 | false | false | false | false |
ipfs/swift-ipfs-api | SwiftIpfsApi/Subcommands/Refs.swift | 2 | 2493 | //
// Refs.swift
// SwiftIpfsApi
//
// Created by Teo on 10/11/15.
// Copyright © 2015 Teo Sartori. All rights reserved.
//
// Licensed under MIT See LICENCE file in the root of this project for details.
import Foundation
import SwiftMultihash
/** Lists links (references) from an object */
public class Refs : ClientSubCommand {
var parent: IpfsApiClient?
// public func local(_ completionHandler: @escaping ([Multihash]) -> Void) throws {
// try parent!.fetchData("refs/local") {
// (data: Data) in
//
// /// First we turn the data into a string
// guard let dataString = String(data: data, encoding: String.Encoding.utf8) else {
// throw IpfsApiError.refsError("Could not convert data into string.")
// }
//
// /** The resulting string is a bunch of newline separated strings so:
// 1) Split the string up by the separator into a subsequence,
// 2) Map each resulting subsequence into a string,
// 3) Map each string into a Multihash with fromB58String. */
// let multiAddrs = try dataString.split(separator: "\n").map(String.init).map{ try fromB58String($0) }
// completionHandler(multiAddrs)
// }
// }
struct Reference : Codable {
let Ref: String
let Err: String
}
public func local(_ completionHandler: @escaping ([Multihash]) -> Void) throws {
try parent!.fetchData("refs/local") {
(data: Data) in
let fixedJsonData = fixStreamJson(data)
let decoder = JSONDecoder()
let refs = try decoder.decode([Reference].self, from: fixedJsonData)
/** The resulting string is a bunch of newline separated strings so:
1) Split the string up by the separator into a subsequence,
2) Map each resulting subsequence into a string,
3) Map each string into a Multihash with fromB58String. */
// let multiAddrs = try dataString.split(separator: "\n").map(String.init).map{ try fromB58String($0) }
let c = try refs.map{ reference -> Multihash in
//try fromB58String($0.Ref)
print("reference is \(reference.Ref)")
print("error is \(reference.Err)")
return try fromB58String(reference.Ref)
}
let multiAddrs = c
completionHandler(multiAddrs)
}
}
}
| mit | e3b585e4740bd106c5309856ef9b6ede | 39.193548 | 126 | 0.593499 | 4.223729 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.