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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
Piwigo/Piwigo-Mobile
|
piwigo/Album/AlbumViewController.swift
|
1
|
69008
|
//
// AlbumViewController.swift
// piwigo
//
// Created by Spencer Baker on 1/27/15.
// Copyright (c) 2015 bakercrew. All rights reserved.
//
// Converted to Swift 5.4 by Eddy Lelièvre-Berna on 11/06/2022
//
import Photos
import UIKit
import piwigoKit
//#import <StoreKit/StoreKit.h>
let kRadius: CGFloat = 25.0
let kDeg2Rad: CGFloat = 3.141592654 / 180.0
enum pwgImageAction {
case edit, delete, share
case addToFavorites, removeFromFavorites
}
@objc
class AlbumViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout, UIGestureRecognizerDelegate, UIToolbarDelegate, UIScrollViewDelegate, ImageDetailDelegate, AlbumCollectionViewCellDelegate, SelectCategoryDelegate, ChangedSettingsDelegate
{
@objc var categoryId = 0
var totalNumberOfImages = 0
var selectedImageIds = [NSNumber]()
var selectedImageIdsLoop = [Int]()
var selectedImageData = [PiwigoImageData]()
var imagesCollection: UICollectionView?
var albumData: AlbumData?
var userHasUploadRights = false
private var didScrollToImageIndex = 0
private var imageOfInterest = IndexPath(item: 0, section: 1)
var settingsBarButton: UIBarButtonItem!
var discoverBarButton: UIBarButtonItem? // Calls discover alert on iOS 9.x —> 13.x
var actionBarButton: UIBarButtonItem? // Menu presented on iOS 14.x —>
var moveBarButton: UIBarButtonItem?
var deleteBarButton: UIBarButtonItem?
var shareBarButton: UIBarButtonItem?
var favoriteBarButton: UIBarButtonItem?
var isSelect = false
var touchedImageIds = [NSNumber]()
var cancelBarButton: UIBarButtonItem!
var selectBarButton: UIBarButtonItem!
var addButton: UIButton!
var createAlbumButton: UIButton!
var createAlbumAction: UIAlertAction!
var homeAlbumButton: UIButton!
var uploadImagesButton: UIButton!
var uploadQueueButton: UIButton!
var progressLayer: CAShapeLayer!
var nberOfUploadsLabel: UILabel!
private var refreshControl: UIRefreshControl? // iOS 9.x only
private var imageDetailView: ImageViewController?
// See https://medium.com/@tungfam/custom-uiviewcontroller-transitions-in-swift-d1677e5aa0bf
//@property (nonatomic, strong) ImageCollectionViewCell *selectedCell; // Cell that was selected
//@property (nonatomic, strong) UIView *selectedCellImageViewSnapshot; // Snapshot of the image view
//@property (nonatomic, strong) ImageAnimatedTransitioning *animator; // Image cell animator
init(albumId: Int) {
super.init(nibName: nil, bundle: nil)
// Store album ID
categoryId = albumId
// Will present Settings icon if root or default album
if [0, AlbumVars.shared.defaultCategory].contains(albumId) {
// Navigation bar buttons
settingsBarButton = getSettingsBarButton()
}
// Will present Discover menu and Search bar if root
if albumId == 0 {
// Discover menu
if #available(iOS 14.0, *) {
// Menu
discoverBarButton = UIBarButtonItem(image: UIImage(systemName: "ellipsis.circle"), menu: discoverMenu())
} else {
// Fallback on earlier versions
discoverBarButton = UIBarButtonItem(image: UIImage(named: "action"), landscapeImagePhone: UIImage(named: "actionCompact"), style: .plain, target: self, action: #selector(discoverMenuOld))
}
discoverBarButton?.accessibilityIdentifier = "discover"
// For iOS 11 and later: place search bar in navigation bar for root album
if #available(iOS 11.0, *) {
// Initialise search controller when displaying root album
initSearchBar()
}
}
// Initialise selection mode
isSelect = false
// Navigation bar and toolbar buttons
selectBarButton = getSelectBarButton()
cancelBarButton = getCancelBarButton()
// Hide toolbar
navigationController?.isToolbarHidden = true
// Collection of images
imagesCollection = UICollectionView(frame: view.frame, collectionViewLayout: UICollectionViewFlowLayout())
imagesCollection?.translatesAutoresizingMaskIntoConstraints = false
imagesCollection?.alwaysBounceVertical = true
imagesCollection?.showsVerticalScrollIndicator = true
imagesCollection?.backgroundColor = UIColor.clear
imagesCollection?.dataSource = self
imagesCollection?.delegate = self
// Refresh view
let refreshControl = UIRefreshControl()
refreshControl.addTarget(self, action: #selector(self.refresh(_:)), for: .valueChanged)
if #available(iOS 10.0, *) {
imagesCollection?.refreshControl = refreshControl
} else {
// Fallback on earlier versions
self.refreshControl = refreshControl
}
imagesCollection?.register(UINib(nibName: "ImageCollectionViewCell", bundle: nil), forCellWithReuseIdentifier: "ImageCollectionViewCell")
imagesCollection?.register(AlbumCollectionViewCell.self, forCellWithReuseIdentifier: "AlbumCollectionViewCell")
imagesCollection?.register(AlbumHeaderReusableView.self, forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: "CategoryHeader")
imagesCollection?.register(NberImagesFooterCollectionReusableView.self, forSupplementaryViewOfKind: UICollectionView.elementKindSectionFooter, withReuseIdentifier: "NberImagesFooterCollection")
if let imagesCollection = imagesCollection {
view.addSubview(imagesCollection)
view.addConstraints(NSLayoutConstraint.constraintFillSize(imagesCollection)!)
}
if #available(iOS 11.0, *) {
imagesCollection?.contentInsetAdjustmentBehavior = .always
}
// "Add" button above collection view and other buttons
addButton = getAddButton()
if let imagesCollection = imagesCollection {
view.insertSubview(addButton, aboveSubview: imagesCollection)
}
// "Upload Queue" button above collection view
uploadQueueButton = getUploadQueueButton()
progressLayer = getProgressLayer()
uploadQueueButton?.layer.addSublayer(progressLayer)
nberOfUploadsLabel = getNberOfUploadsLabel()
uploadQueueButton?.addSubview(nberOfUploadsLabel)
view.insertSubview(uploadQueueButton, belowSubview: addButton)
// "Home" album button above collection view
homeAlbumButton = getHomeButton()
view.insertSubview(homeAlbumButton, belowSubview: addButton)
// "Create Album" button above collection view
createAlbumButton = getCreateAlbumButton()
view.insertSubview(createAlbumButton, belowSubview: addButton)
// "Upload Images" button above collection view
uploadImagesButton = getUploadImagesButton()
view.insertSubview(uploadImagesButton, belowSubview: addButton)
}
// MARK: - View Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
print("===============================")
print(String(format: "viewDidLoad => ID:%ld", categoryId))
// Register palette changes
NotificationCenter.default.addObserver(self,selector: #selector(applyColorPalette),
name: .pwgPaletteChanged, object: nil)
// Navigation bar
navigationController?.navigationBar.accessibilityIdentifier = "AlbumImagesNav"
}
@objc func applyColorPalette() {
// Background color of the view
view.backgroundColor = UIColor.piwigoColorBackground()
// Refresh controller
if #available(iOS 10.0, *) {
imagesCollection?.refreshControl?.backgroundColor = UIColor.piwigoColorBackground()
imagesCollection?.refreshControl?.tintColor = UIColor.piwigoColorHeader()
let attributesRefresh = [
NSAttributedString.Key.foregroundColor: UIColor.piwigoColorHeader(),
NSAttributedString.Key.font: UIFont.piwigoFontLight()
]
imagesCollection?.refreshControl?.attributedTitle = NSAttributedString(string: NSLocalizedString("pullToRefresh", comment: "Reload Photos"), attributes: attributesRefresh)
} else {
// Fallback on earlier versions
refreshControl?.backgroundColor = UIColor.piwigoColorBackground()
refreshControl?.tintColor = UIColor.piwigoColorOrange()
let attributesRefresh = [
NSAttributedString.Key.foregroundColor: UIColor.piwigoColorOrange(),
NSAttributedString.Key.font: UIFont.piwigoFontNormal()
]
refreshControl?.attributedTitle = NSAttributedString(string: NSLocalizedString("pullToRefresh", comment: "Reload Images"), attributes: attributesRefresh)
}
// Buttons
addButton.layer.shadowColor = UIColor.piwigoColorShadow().cgColor
createAlbumButton?.layer.shadowColor = UIColor.piwigoColorShadow().cgColor
uploadImagesButton?.layer.shadowColor = UIColor.piwigoColorShadow().cgColor
uploadQueueButton?.layer.shadowColor = UIColor.piwigoColorShadow().cgColor
uploadQueueButton?.backgroundColor = UIColor.piwigoColorRightLabel()
nberOfUploadsLabel?.textColor = UIColor.piwigoColorBackground()
progressLayer?.strokeColor = UIColor.piwigoColorBackground().cgColor
homeAlbumButton?.layer.shadowColor = UIColor.piwigoColorShadow().cgColor
homeAlbumButton?.backgroundColor = UIColor.piwigoColorRightLabel()
homeAlbumButton?.tintColor = UIColor.piwigoColorBackground()
if AppVars.shared.isDarkPaletteActive {
addButton.layer.shadowRadius = 1.0
addButton.layer.shadowOffset = CGSize.zero
createAlbumButton?.layer.shadowRadius = 1.0
createAlbumButton?.layer.shadowOffset = CGSize.zero
uploadImagesButton?.layer.shadowRadius = 1.0
uploadImagesButton?.layer.shadowOffset = CGSize.zero
uploadQueueButton?.layer.shadowRadius = 1.0
uploadQueueButton?.layer.shadowOffset = CGSize.zero
homeAlbumButton?.layer.shadowRadius = 1.0
homeAlbumButton?.layer.shadowOffset = CGSize.zero
} else {
addButton.layer.shadowRadius = 3.0
addButton.layer.shadowOffset = CGSize(width: 0.0, height: 0.5)
createAlbumButton?.layer.shadowRadius = 3.0
createAlbumButton?.layer.shadowOffset = CGSize(width: 0.0, height: 0.5)
uploadImagesButton?.layer.shadowRadius = 3.0
uploadImagesButton?.layer.shadowOffset = CGSize(width: 0.0, height: 0.5)
uploadQueueButton?.layer.shadowRadius = 3.0
uploadQueueButton?.layer.shadowOffset = CGSize(width: 0.0, height: 0.5)
homeAlbumButton?.layer.shadowRadius = 3.0
homeAlbumButton?.layer.shadowOffset = CGSize(width: 0.0, height: 0.5)
}
// Navigation bar appearance
let navigationBar = navigationController?.navigationBar
navigationController?.view.backgroundColor = UIColor.piwigoColorBackground()
navigationBar?.barStyle = AppVars.shared.isDarkPaletteActive ? .black : .default
navigationBar?.tintColor = UIColor.piwigoColorOrange()
// Toolbar appearance
let toolbar = navigationController?.toolbar
toolbar?.barStyle = AppVars.shared.isDarkPaletteActive ? .black : .default
toolbar?.tintColor = UIColor.piwigoColorOrange()
let attributes = [
NSAttributedString.Key.foregroundColor: UIColor.piwigoColorWhiteCream(),
NSAttributedString.Key.font: UIFont.piwigoFontNormal()
]
let attributesLarge = [
NSAttributedString.Key.foregroundColor: UIColor.piwigoColorWhiteCream(),
NSAttributedString.Key.font: UIFont.piwigoFontLargeTitle()
]
if #available(iOS 11.0, *) {
if categoryId == AlbumVars.shared.defaultCategory {
// Title
navigationBar?.largeTitleTextAttributes = attributesLarge
navigationBar?.prefersLargeTitles = true
// Search bar
let searchBar = navigationItem.searchController?.searchBar
searchBar?.barStyle = AppVars.shared.isDarkPaletteActive ? .black : .default
if #available(iOS 13.0, *) {
searchBar?.searchTextField.textColor = UIColor.piwigoColorLeftLabel()
searchBar?.searchTextField.keyboardAppearance = AppVars.shared.isDarkPaletteActive ? .dark : .light
}
} else {
navigationBar?.titleTextAttributes = attributes
navigationBar?.prefersLargeTitles = false
}
if #available(iOS 13.0, *) {
let barAppearance = UINavigationBarAppearance()
barAppearance.configureWithTransparentBackground()
barAppearance.backgroundColor = UIColor.piwigoColorBackground().withAlphaComponent(0.9)
barAppearance.titleTextAttributes = attributes
barAppearance.largeTitleTextAttributes = attributesLarge
if categoryId != AlbumVars.shared.defaultCategory {
barAppearance.shadowColor = AppVars.shared.isDarkPaletteActive ? UIColor(white: 1.0, alpha: 0.15) : UIColor(white: 0.0, alpha: 0.3)
}
navigationItem.standardAppearance = barAppearance
navigationItem.compactAppearance = barAppearance // For iPhone small navigation bar in landscape.
navigationItem.scrollEdgeAppearance = barAppearance
let toolbarAppearance = UIToolbarAppearance(barAppearance: barAppearance)
toolbar?.standardAppearance = toolbarAppearance
if #available(iOS 15.0, *) {
/// In iOS 15, UIKit has extended the usage of the scrollEdgeAppearance,
/// which by default produces a transparent background, to all navigation bars.
toolbar?.scrollEdgeAppearance = toolbarAppearance
}
}
} else {
navigationBar?.titleTextAttributes = attributes
navigationBar?.barTintColor = UIColor.piwigoColorBackground().withAlphaComponent(0.3)
toolbar?.barTintColor = UIColor.piwigoColorBackground().withAlphaComponent(0.9)
}
// Collection view
imagesCollection?.indicatorStyle = AppVars.shared.isDarkPaletteActive ? .white : .black
let headers = imagesCollection?.visibleSupplementaryViews(ofKind: UICollectionView.elementKindSectionHeader)
if (headers?.count ?? 0) > 0 {
let header = headers?.first as? AlbumHeaderReusableView
header?.commentLabel?.textColor = UIColor.piwigoColorHeader()
header?.backgroundColor = UIColor.piwigoColorBackground().withAlphaComponent(0.75)
}
for cell in imagesCollection?.visibleCells ?? [] {
if let albumCell = cell as? AlbumCollectionViewCell {
albumCell.applyColorPalette()
continue
}
if let imageCell = cell as? ImageCollectionViewCell {
imageCell.applyColorPalette()
continue
}
}
let footers = imagesCollection?.visibleSupplementaryViews(ofKind: UICollectionView.elementKindSectionFooter)
if let footer = footers?.first as? NberImagesFooterCollectionReusableView {
footer.noImagesLabel?.textColor = UIColor.piwigoColorHeader()
footer.backgroundColor = UIColor.piwigoColorBackground().withAlphaComponent(0.75)
}
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
print(String(format: "viewWillAppear => ID:%ld", categoryId))
// Initialise data source
if categoryId != 0 {
albumData = AlbumData(categoryId: categoryId, andQuery: "")
AlbumUtilities.updateDescriptionOfAlbum(withId: categoryId)
}
// Set colors, fonts, etc.
applyColorPalette()
// Always open this view with a navigation bar
// (might have been hidden during Image Previewing)
navigationController?.setNavigationBarHidden(false, animated: true)
// Set navigation bar buttons
initButtonsInPreviewMode()
updateButtonsInPreviewMode()
// Register upload manager changes
NotificationCenter.default.addObserver(self, selector: #selector(updateNberOfUploads(_:)),
name: .pwgLeftUploads, object: nil)
// Register upload progress
NotificationCenter.default.addObserver(self, selector: #selector(updateUploadQueueButton(withProgress:)),
name: .pwgUploadProgress, object: nil)
// Inform Upload view controllers that user selected this category
let userInfo = ["currentCategoryId": NSNumber(value: categoryId)]
NotificationCenter.default.post(name: NSNotification.Name(rawValue: kPiwigoNotificationChangedCurrentCategory), object: nil, userInfo: userInfo)
// If displaying smart album —> reload images
if categoryId < 0 {
// Load, sort images and reload collection
let oldImageList = albumData?.images ?? []
albumData?.updateImageSort(kPiwigoSortObjc(rawValue: UInt32(AlbumVars.shared.defaultSort)), onCompletion: { [self] in
// Reset navigation bar buttons after image load
updateButtonsInPreviewMode()
reloadImagesCollection(from: oldImageList)
}, onFailure: { [self] _, error in
dismissPiwigoError(withTitle: NSLocalizedString("albumPhotoError_title", comment: "Get Album Photos Error"), message: NSLocalizedString("albumPhotoError_message", comment: "Failed to get album photos (corrupt image in your album?)"), errorMessage: error?.localizedDescription ?? "") { }
})
} else {
// Images will be loaded if needed after displaying cells
imagesCollection?.reloadData()
}
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
print(String(format: "viewDidAppear => ID:%ld", categoryId))
// Update title of current scene (iPad only)
if #available(iOS 13.0, *) {
view?.window?.windowScene?.title = self.title
}
if #available(iOS 10.0, *) {
} else {
// Fallback on earlier versions
if let refreshControl = refreshControl {
imagesCollection?.addSubview(refreshControl)
imagesCollection?.alwaysBounceVertical = true
}
}
// Stop here if app is reloading album data
if AppVars.shared.isReloadingData {
return
}
// Determine for how long the session was open
/// Piwigo 11 session duration defaults to an hour.
let timeSinceLastLogin = NetworkVars.dateOfLastLogin.timeIntervalSinceNow
let allAlbums = CategoriesData.sharedInstance().allCategories?.filter({ $0.numberOfImages != NSNotFound})
AppVars.shared.nberOfAlbumsInCache = allAlbums?.count ?? 0
if NetworkVars.serverPath.isEmpty == false, NetworkVars.username.isEmpty == false,
((timeSinceLastLogin < TimeInterval(-1800)) || AppVars.shared.nberOfAlbumsInCache == 0) {
// Check if we have album data
AppVars.shared.isReloadingData = true
if AppVars.shared.nberOfAlbumsInCache == 0 {
reloginAndReloadAlbumData {
AppVars.shared.isReloadingData = false
}
} else {
// Check if session is active in the background
let pwgToken = NetworkVars.pwgToken
LoginUtilities.sessionGetStatus { [unowned self] in
if NetworkVars.pwgToken != pwgToken {
reloginAndReloadAlbumData {
AppVars.shared.isReloadingData = false
}
}
} failure: { _ in
print("••> Failed to check session status…")
AppVars.shared.isReloadingData = false
// Will re-check later…
}
}
return
}
if NetworkVars.serverPath.isEmpty == false, NetworkVars.username.isEmpty == true,
AppVars.shared.nberOfAlbumsInCache == 0 {
// Apparently this is the first time we load album data as Guest
/// - Reload album data
print("••> Reload album data…")
AppVars.shared.isReloadingData = true
reloadAlbumData {
AppVars.shared.isReloadingData = false
}
return
}
// Resume upload operations in background queue
// and update badge, upload button of album navigator
if UploadManager.shared.isPaused {
UploadManager.shared.backgroundQueue.async {
UploadManager.shared.resumeAll()
}
}
// Should we highlight the image of interest?
if categoryId != 0, (albumData?.images.count ?? 0) > 0,
imageOfInterest.item != 0 {
// Highlight the cell of interest
let indexPathsForVisibleItems = imagesCollection?.indexPathsForVisibleItems
if indexPathsForVisibleItems?.contains(imageOfInterest) ?? false {
// Thumbnail is already visible and is highlighted
if let cell = imagesCollection?.cellForItem(at: imageOfInterest),
let imageCell = cell as? ImageCollectionViewCell {
imageCell.highlight() {
self.imageOfInterest = IndexPath(item: 0, section: 1)
}
} else {
self.imageOfInterest = IndexPath(item: 0, section: 1)
}
}
}
// Determine which help pages should be presented
var displayHelpPagesWithID = [UInt16]()
if categoryId != 0, (albumData?.images.count ?? 0) > 5,
(AppVars.shared.didWatchHelpViews & 0b00000000_00000001) == 0 {
displayHelpPagesWithID.append(1) // i.e. multiple selection of images
}
if categoryId != 0,
let albums = CategoriesData.sharedInstance().getCategoriesForParentCategory(categoryId),
albums.count > 2, NetworkVars.hasAdminRights,
(AppVars.shared.didWatchHelpViews & 0b00000000_00000100) == 0 {
displayHelpPagesWithID.append(3) // i.e. management of albums
}
if categoryId != 0,
let album = CategoriesData.sharedInstance().getCategoryById(categoryId),
let parents = album.upperCategories, parents.count > 2,
(AppVars.shared.didWatchHelpViews & 0b00000000_10000000) == 0 {
displayHelpPagesWithID.append(8) // i.e. back to parent album
}
if displayHelpPagesWithID.count > 0 {
// Present unseen help views
let helpSB = UIStoryboard(name: "HelpViewController", bundle: nil)
guard let helpVC = helpSB.instantiateViewController(withIdentifier: "HelpViewController") as? HelpViewController else {
fatalError("No HelpViewController available!")
}
helpVC.displayHelpPagesWithID = displayHelpPagesWithID
if UIDevice.current.userInterfaceIdiom == .phone {
helpVC.popoverPresentationController?.permittedArrowDirections = .up
present(helpVC, animated: true)
} else {
helpVC.modalPresentationStyle = UIModalPresentationStyle.formSheet
helpVC.modalTransitionStyle = UIModalTransitionStyle.coverVertical
present(helpVC, animated: true)
}
}
// Replace iRate as from v2.1.5 (75) — See https://github.com/nicklockwood/iRate
// Tells StoreKit to ask the user to rate or review the app, if appropriate.
//#if !defined(DEBUG)
// if (NSClassFromString(@"SKStoreReviewController")) {
// [SKStoreReviewController requestReview];
// }
//#endif
// Inform user why the app crashed at start
if CacheVars.couldNotMigrateCoreDataStore {
dismissPiwigoError(
withTitle: NSLocalizedString("CoreDataStore_WarningTitle", comment: "Warning"),
message: NSLocalizedString("CoreDataStore_WarningMessage", comment: "A serious application error occurred…"),
errorMessage: "") {
// Reset flag
CacheVars.couldNotMigrateCoreDataStore = false
}
}
}
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
super.viewWillTransition(to: size, with: coordinator)
// Update the navigation bar on orientation change, to match the new width of the table.
coordinator.animate(alongsideTransition: { [self] context in
// Reload collection
imagesCollection?.reloadData()
// Update buttons
if isSelect {
initButtonsInSelectionMode()
} else {
// Update position of buttons (recalculated after device rotation)
addButton?.frame = getAddButtonFrame()
homeAlbumButton?.frame = getHomeAlbumButtonFrame(isHidden: homeAlbumButton?.isHidden ?? true)
uploadQueueButton?.frame = getUploadQueueButtonFrame(isHidden: uploadQueueButton?.isHidden ?? true)
createAlbumButton?.frame = getCreateAlbumButtonFrame(isHidden: createAlbumButton?.isHidden ?? true)
uploadImagesButton?.frame = getUploadImagesButtonFrame(isHidden: uploadImagesButton?.isHidden ?? true)
}
})
}
override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
super.traitCollectionDidChange(previousTraitCollection)
// Should we update user interface based on the appearance?
if #available(iOS 13.0, *) {
let isSystemDarkModeActive = UIScreen.main.traitCollection.userInterfaceStyle == .dark
if AppVars.shared.isSystemDarkModeActive != isSystemDarkModeActive {
AppVars.shared.isSystemDarkModeActive = isSystemDarkModeActive
let appDelegate = UIApplication.shared.delegate as? AppDelegate
appDelegate?.screenBrightnessChanged()
}
}
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
if #available(iOS 15, *) {
// Keep title
} else {
// Do not show album title in backButtonItem of child view to provide enough space for image title
// See https://www.paintcodeapp.com/news/ultimate-guide-to-iphone-resolutions
if view.bounds.size.width <= 414 {
// i.e. smaller than iPhones 6,7 Plus screen width
title = ""
}
}
// Hide upload button during transition
addButton.isHidden = true
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
// Make sure buttons are back to initial state
didCancelTapAddButton()
}
deinit {
// Unregister palette changes
NotificationCenter.default.removeObserver(self, name: .pwgPaletteChanged, object: nil)
// Unregister upload manager changes
NotificationCenter.default.removeObserver(self, name: .pwgLeftUploads, object: nil)
// Unregister upload progress
NotificationCenter.default.removeObserver(self, name: .pwgUploadProgress, object: nil)
}
// MARK: - Category Data
@objc func refresh(_ refreshControl: UIRefreshControl?) {
reloginAndReloadAlbumData { [self] in
// End refreshing
if #available(iOS 10.0, *) {
if imagesCollection?.refreshControl != nil {
imagesCollection?.refreshControl?.endRefreshing()
}
} else {
if refreshControl != nil {
refreshControl?.endRefreshing()
}
}
}
}
private func reloadImagesCollection(from oldImages: [PiwigoImageData]) {
if oldImages.count != albumData?.images?.count ?? NSNotFound {
// List of images has changed
imagesCollection?.reloadData()
// Cancel selection
cancelSelect()
}
else {
// Loop over the visible cells (the number of images did not changed)
for indexPath in imagesCollection?.indexPathsForVisibleItems ?? [] {
// Only concerns cells of section 1
if indexPath.section == 0 { continue }
// Check that there exists a cell at this indexPath
if indexPath.item >= oldImages.count { continue }
// We should update this cell
imagesCollection?.reloadItems(at: [indexPath])
}
}
}
@objc
func updateSubCategory(withId albumId: Int) {
// Get index of updated category
if let categories = CategoriesData.sharedInstance().getCategoriesForParentCategory(categoryId),
let indexOfExistingItem = categories.firstIndex(where: {$0.albumId == albumId}) {
// Update cell of corresponding category
let indexPath = IndexPath(item: indexOfExistingItem, section: 0)
if imagesCollection?.indexPathsForVisibleItems.contains(indexPath) ?? false {
imagesCollection?.reloadItems(at: [indexPath])
}
}
}
@objc
func addImage(withId imageId: Int) {
// Retrieve images from cache
guard let newImages = CategoriesData.sharedInstance().getCategoryById(categoryId)?.imageList else { return }
if let indexOfNewItem = newImages.firstIndex(where: {$0.imageId == imageId}),
newImages.count > (albumData?.images.count ?? 0) {
// Add image to data source
albumData?.images = newImages
// Insert corresponding cell
let indexPath = IndexPath(item: indexOfNewItem, section: 1)
imagesCollection?.insertItems(at: [indexPath])
// Update footer if visible
if (imagesCollection?.visibleSupplementaryViews(ofKind: UICollectionView.elementKindSectionFooter).count ?? 0) > 0 {
imagesCollection?.reloadSections(IndexSet(integer: 1))
}
}
// Display Select button if there was no image in the album
if newImages.count == 1 {
// Display Select button
if isSelect == false {
updateButtonsInPreviewMode()
}
}
}
@objc
func removeImage(withId imageId: Int) {
// Remove image from the selection if needed
let imageIdObject = NSNumber(value: imageId)
if selectedImageIds.contains(imageIdObject) {
selectedImageIds.removeAll { $0 === imageIdObject }
}
// Get index of deleted image
if let indexOfExistingItem = albumData?.images.firstIndex(where: {$0.imageId == imageId}) {
// Remove image from data source
var imageList = albumData?.images
imageList?.remove(at: indexOfExistingItem)
albumData?.images = imageList
// Delete corresponding cell
let indexPath = IndexPath(item: indexOfExistingItem, section: 1)
if imagesCollection?.indexPathsForVisibleItems.contains(indexPath) ?? false {
imagesCollection?.deleteItems(at: [indexPath])
}
// Update footer if visible
if (imagesCollection?.visibleSupplementaryViews(ofKind: UICollectionView.elementKindSectionFooter).count ?? 0) > 0 {
imagesCollection?.reloadSections(IndexSet(integer: 1))
}
}
}
// MARK: - Default Category Management
@objc func returnToDefaultCategory() {
// Does the default album view controller already exists?
var cur = 0, index = 0
var rootAlbumViewController: AlbumViewController? = nil
for viewController in navigationController?.viewControllers ?? []
{
// Look for AlbumImagesViewControllers
if let thisViewController = viewController as? AlbumViewController
{
// Is this the view controller of the default album?
if thisViewController.categoryId == AlbumVars.shared.defaultCategory {
// The view controller of the parent category already exist
rootAlbumViewController = thisViewController
}
// Is this the current view controller?
if thisViewController.categoryId == categoryId {
// This current view controller will become the child view controller
index = cur
}
}
cur = cur + 1
}
// The view controller of the default album does not exist yet
if rootAlbumViewController == nil {
rootAlbumViewController = AlbumViewController(albumId: AlbumVars.shared.defaultCategory)
if let rootAlbumViewController = rootAlbumViewController,
var arrayOfVC = navigationController?.viewControllers {
arrayOfVC.insert(rootAlbumViewController, at: index)
navigationController?.viewControllers = arrayOfVC
}
}
// Present the root album
if let rootAlbumViewController = rootAlbumViewController {
navigationController?.popToViewController(rootAlbumViewController, animated: true)
}
}
// MARK: - Upload Actions
@objc func didTapUploadImagesButton() {
// Check autorisation to access Photo Library before uploading
if #available(iOS 14, *) {
PhotosFetch.shared.checkPhotoLibraryAuthorizationStatus(for: PHAccessLevel.readWrite, for: self, onAccess: { [self] in
// Open local albums view controller in new navigation controller
let localAlbumsSB = UIStoryboard(name: "LocalAlbumsViewController", bundle: nil)
guard let localAlbumsVC = localAlbumsSB.instantiateViewController(withIdentifier: "LocalAlbumsViewController") as? LocalAlbumsViewController else {
fatalError("No LocalAlbumsViewController!")
}
localAlbumsVC.setCategoryId(categoryId)
let navController = UINavigationController(rootViewController: localAlbumsVC)
navController.modalTransitionStyle = .coverVertical
navController.modalPresentationStyle = .pageSheet
present(navController, animated: true)
}, onDeniedAccess: {
})
} else {
// Fallback on earlier versions
PhotosFetch.shared.checkPhotoLibraryAccessForViewController(self, onAuthorizedAccess: { [self] in
// Open local albums view controller in new navigation controller
let localAlbumsSB = UIStoryboard(name: "LocalAlbumsViewController", bundle: nil)
guard let localAlbumsVC = localAlbumsSB.instantiateViewController(withIdentifier: "LocalAlbumsViewController") as? LocalAlbumsViewController else {
fatalError("No LocalAlbumsViewController!")
}
localAlbumsVC.setCategoryId(self.categoryId)
let navController = UINavigationController(rootViewController: localAlbumsVC)
navController.modalTransitionStyle = .coverVertical
navController.modalPresentationStyle = .pageSheet
present(navController, animated: true)
}, onDeniedAccess: { })
}
// Hide CreateAlbum and UploadImages buttons
didCancelTapAddButton()
}
@objc func didTapUploadQueueButton() {
// Open upload queue controller in new navigation controller
var navController: UINavigationController? = nil
if #available(iOS 13.0, *) {
let uploadQueueSB = UIStoryboard(name: "UploadQueueViewController", bundle: nil)
guard let uploadQueueVC = uploadQueueSB.instantiateViewController(withIdentifier: "UploadQueueViewController") as? UploadQueueViewController else {
fatalError("No UploadQueueViewController!")
}
navController = UINavigationController(rootViewController: uploadQueueVC)
}
else {
// Fallback on earlier versions
let uploadQueueSB = UIStoryboard(name: "UploadQueueViewControllerOld", bundle: nil)
guard let uploadQueueVC = uploadQueueSB.instantiateViewController(withIdentifier: "UploadQueueViewControllerOld") as? UploadQueueViewControllerOld else {
fatalError("No UploadQueueViewControllerOld!")
}
navController = UINavigationController(rootViewController: uploadQueueVC)
}
navController?.modalTransitionStyle = .coverVertical
navController?.modalPresentationStyle = .formSheet
if let navController = navController {
present(navController, animated: true)
}
}
// MARK: - UICollectionView Headers & Footers
func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView
{
switch indexPath.section {
case 0 /* Section 0 — Album collection */:
var header: AlbumHeaderReusableView? = nil
if kind == UICollectionView.elementKindSectionHeader {
header = collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: "CategoryHeader", for: indexPath) as? AlbumHeaderReusableView
header?.commentLabel?.attributedText = AlbumUtilities.headerLegend(for: categoryId)
header?.commentLabel?.textColor = UIColor.piwigoColorHeader()
return header!
}
case 1 /* Section 1 — Image collection */:
if kind == UICollectionView.elementKindSectionFooter {
// Get number of images
var totalImageCount = NSNotFound
if categoryId == 0 {
// Only albums in Root Album => total number of images
for albumData in CategoriesData.sharedInstance().getCategoriesForParentCategory(0) {
if totalImageCount == NSNotFound {
totalImageCount = 0
}
totalImageCount += albumData.totalNumberOfImages
}
} else {
// Number of images in current album
if let albumData = CategoriesData.sharedInstance().getCategoryById(categoryId) {
totalImageCount = albumData.totalNumberOfImages
}
}
guard let footer = collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionView.elementKindSectionFooter, withReuseIdentifier: "NberImagesFooterCollection", for: indexPath) as? NberImagesFooterCollectionReusableView else {
fatalError("No NberImagesFooterCollectionReusableView!")
}
footer.noImagesLabel?.textColor = UIColor.piwigoColorHeader()
footer.noImagesLabel?.text = AlbumUtilities.footerLegend(for: totalImageCount)
return footer
}
default:
break
}
let view = UICollectionReusableView(frame: CGRect.zero)
return view
}
func collectionView(_ collectionView: UICollectionView, willDisplaySupplementaryView view: UICollectionReusableView, forElementKind elementKind: String, at indexPath: IndexPath) {
if (elementKind == UICollectionView.elementKindSectionHeader) ||
(elementKind == UICollectionView.elementKindSectionFooter) {
view.layer.zPosition = 0 // Below scroll indicator
view.backgroundColor = UIColor.piwigoColorBackground().withAlphaComponent(0.75)
}
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize
{
switch section {
case 0 /* Section 0 — Album collection */:
// Header height?
guard let albumData = CategoriesData.sharedInstance().getCategoryById(categoryId) else {
return CGSize.zero
}
if let desc = albumData.comment, desc.isEmpty == false,
collectionView.frame.size.width - 30.0 > 0 {
let description = AlbumUtilities.headerLegend(for: categoryId)
let context = NSStringDrawingContext()
context.minimumScaleFactor = 1.0
let headerRect = description.boundingRect(
with: CGSize(width: collectionView.frame.size.width - 30.0,
height: CGFloat.greatestFiniteMagnitude),
options: .usesLineFragmentOrigin, context: context)
return CGSize(width: collectionView.frame.size.width - 30.0,
height: ceil(headerRect.size.height))
}
default:
break
}
return CGSize.zero
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForFooterInSection section: Int) -> CGSize
{
switch section {
case 1 /* Section 1 — Image collection */:
var footer = ""
// Get number of images
var totalImageCount = NSNotFound
if categoryId == 0 {
// Only albums in Root Album => total number of images
for albumData in CategoriesData.sharedInstance().getCategoriesForParentCategory(categoryId) {
if totalImageCount == NSNotFound {
totalImageCount = 0
}
totalImageCount += albumData.totalNumberOfImages
}
} else {
// Number of images in current album
totalImageCount = CategoriesData.sharedInstance().getCategoryById(categoryId)?.totalNumberOfImages ?? 0
}
footer = AlbumUtilities.footerLegend(for: totalImageCount)
if footer.count > 0,
collectionView.frame.size.width - 30.0 > 0 {
let attributes = [NSAttributedString.Key.font: UIFont.piwigoFontLight()]
let context = NSStringDrawingContext()
context.minimumScaleFactor = 1.0
let footerRect = footer.boundingRect(
with: CGSize(width: collectionView.frame.size.width - 30.0, height: CGFloat.greatestFiniteMagnitude),
options: .usesLineFragmentOrigin,
attributes: attributes, context: context)
return CGSize(width: collectionView.frame.size.width - 30.0, height: ceil(footerRect.size.height))
}
default:
break
}
return CGSize.zero
}
// MARK: - UICollectionView - Rows
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 2
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
// Returns number of images or albums
var numberOfItems: Int
switch section {
case 0 /* Albums */:
numberOfItems = CategoriesData.sharedInstance().getCategoriesForParentCategory(categoryId)?.count ?? 0
default /* Images */:
numberOfItems = albumData?.images?.count ?? 0
}
return numberOfItems
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets
{
// Avoid unwanted spaces
switch section {
case 0 /* Albums */:
if collectionView.numberOfItems(inSection: section) == 0 {
return UIEdgeInsets(top: 0, left: AlbumUtilities.kAlbumMarginsSpacing,
bottom: 0, right: AlbumUtilities.kAlbumMarginsSpacing)
} else if categoryId == 0 {
if #available(iOS 13.0, *) {
return UIEdgeInsets(top: 0, left: AlbumUtilities.kAlbumMarginsSpacing,
bottom: 0, right: AlbumUtilities.kAlbumMarginsSpacing)
} else {
return UIEdgeInsets(top: 10, left: AlbumUtilities.kAlbumMarginsSpacing,
bottom: 0, right: AlbumUtilities.kAlbumMarginsSpacing)
}
} else {
return UIEdgeInsets(top: 10, left: AlbumUtilities.kAlbumMarginsSpacing, bottom: 0,
right: AlbumUtilities.kAlbumMarginsSpacing)
}
default /* Images */:
let albumData = CategoriesData.sharedInstance().getCategoryById(categoryId)
if collectionView.numberOfItems(inSection: section) == 0 {
return UIEdgeInsets(top: 0, left: AlbumUtilities.kImageMarginsSpacing,
bottom: 0, right: AlbumUtilities.kImageMarginsSpacing)
} else if albumData?.comment?.count == 0 {
return UIEdgeInsets(top: 4, left: AlbumUtilities.kImageMarginsSpacing,
bottom: 4, right: AlbumUtilities.kImageMarginsSpacing)
} else {
return UIEdgeInsets(top: 10, left: AlbumUtilities.kImageMarginsSpacing,
bottom: 4, right: AlbumUtilities.kImageMarginsSpacing)
}
}
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
switch section {
case 0 /* Albums */:
return 0.0
default /* Images */:
return CGFloat(AlbumUtilities.imageCellVerticalSpacing(forCollectionType: .full))
}
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
switch section {
case 0 /* Albums */:
return AlbumUtilities.kAlbumCellSpacing
default /* Images */:
return AlbumUtilities.imageCellHorizontalSpacing(forCollectionType: .full)
}
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
switch indexPath.section {
case 0 /* Albums (see XIB file) */:
let nberAlbumsPerRow = AlbumUtilities.numberOfAlbumsPerRowInPortrait(forView: collectionView, maxWidth: 384.0)
let size = AlbumUtilities.albumSize(forView: collectionView,
nberOfAlbumsPerRowInPortrait: nberAlbumsPerRow)
return CGSize(width: size, height: 156.5)
default /* Images */:
// Calculates size of image cells
let size = AlbumUtilities.imageSize(forView: imagesCollection,
imagesPerRowInPortrait: AlbumVars.shared.thumbnailsPerRowInPortrait)
return CGSize(width: size, height: size)
}
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
switch indexPath.section {
case 0 /* Albums (see XIB file) */:
guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "AlbumCollectionViewCell", for: indexPath) as? AlbumCollectionViewCell else {
fatalError("No AlbumCollectionViewCell!")
}
cell.categoryDelegate = self
// Check album data
guard let parentAlbums = CategoriesData.sharedInstance().getCategoriesForParentCategory(categoryId),
indexPath.item < parentAlbums.count else {
cell.config()
return cell
}
// Configure cell with album data
let albumData = parentAlbums[indexPath.item]
cell.config(withAlbumData: albumData)
// Disable category cells in Image selection mode
if isSelect {
cell.contentView.alpha = 0.5
cell.isUserInteractionEnabled = false
} else {
cell.contentView.alpha = 1.0
cell.isUserInteractionEnabled = true
}
return cell
default /* Images */:
guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "ImageCollectionViewCell", for: indexPath) as? ImageCollectionViewCell else {
fatalError("No ImageCollectionViewCell!")
}
if (self.albumData?.images?.count ?? 0) > indexPath.item {
// Remember that user did scroll down to this item
didScrollToImageIndex = indexPath.item
// Create cell from Piwigo data
let imageData = self.albumData?.images[indexPath.row] as? PiwigoImageData
cell.config(with: imageData, inCategoryId: categoryId)
cell.isSelection = selectedImageIds.contains(NSNumber(value: imageData?.imageId ?? NSNotFound))
// pwg.users.favorites… methods available from Piwigo version 2.10
if "2.10.0".compare(NetworkVars.pwgVersion, options: .numeric) != .orderedDescending {
cell.isFavorite = CategoriesData.sharedInstance().category(withId: kPiwigoFavoritesCategoryId, containsImagesWithId: [NSNumber(value: imageData?.imageId ?? 0)])
}
// Add pan gesture recognition
let imageSeriesRocognizer = UIPanGestureRecognizer(target: self, action: #selector(touchedImages(_:)))
imageSeriesRocognizer.minimumNumberOfTouches = 1
imageSeriesRocognizer.maximumNumberOfTouches = 1
imageSeriesRocognizer.cancelsTouchesInView = false
imageSeriesRocognizer.delegate = self
cell.addGestureRecognizer(imageSeriesRocognizer)
cell.isUserInteractionEnabled = true
}
// Load more image data if possible (page after page…)
if let currentAlbumData = CategoriesData.sharedInstance().getCategoryById(categoryId),
!currentAlbumData.isLoadingMoreImages, !currentAlbumData.hasAllImagesInCache() {
self.needToLoadMoreImages()
}
return cell
}
}
// MARK: - UICollectionViewDelegate Methods
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
switch indexPath.section {
case 0 /* Albums */:
break
default /* Images */:
guard let selectedCell = collectionView.cellForItem(at: indexPath) as? ImageCollectionViewCell else {
fatalError("No ImageCollectionViewCell!")
}
// Avoid rare crashes…
if (indexPath.row < 0) || (indexPath.row >= (albumData?.images.count ?? 0)) {
return
}
if albumData?.images?[indexPath.item].imageId == 0 {
return
}
// Action depends on mode
if !isSelect {
// Remember that user did tap this image
imageOfInterest = indexPath
// Add category to list of recent albums
let userInfo = ["categoryId": NSNumber(value: categoryId)]
NotificationCenter.default.post(name: .pwgAddRecentAlbum, object: nil, userInfo: userInfo)
// Selection mode not active => display full screen image
let imageDetailSB = UIStoryboard(name: "ImageViewController", bundle: nil)
imageDetailView = imageDetailSB.instantiateViewController(withIdentifier: "ImageViewController") as? ImageViewController
imageDetailView?.imageIndex = indexPath.row
imageDetailView?.categoryId = categoryId
imageDetailView?.images = albumData?.images ?? []
imageDetailView?.hidesBottomBarWhenPushed = true
imageDetailView?.imgDetailDelegate = self
imageDetailView?.modalPresentationCapturesStatusBarAppearance = true
// self.imageDetailView.transitioningDelegate = self;
// self.selectedCellImageViewSnapshot = [self.selectedCell.cellImage snapshotViewAfterScreenUpdates:NO];
if let imageDetailView = imageDetailView {
navigationController?.pushViewController(imageDetailView, animated: true)
}
} else {
// Selection mode active => add/remove image from selection
let imageIdObject = NSNumber(value: selectedCell.imageData?.imageId ?? NSNotFound)
if !selectedImageIds.contains(imageIdObject) {
selectedImageIds.append(imageIdObject)
selectedCell.isSelection = true
} else {
selectedCell.isSelection = false
selectedImageIds.removeAll { $0 as AnyObject === imageIdObject as AnyObject }
}
// and update nav buttons
updateButtonsInSelectionMode()
}
}
}
// MARK: - ImageDetailDelegate Methods
func didSelectImage(withId imageId: Int) {
// Determine index of image
guard let indexOfImage = albumData?.images.firstIndex(where: {$0.imageId == imageId}) else { return }
// Scroll view to center image
if (imagesCollection?.numberOfItems(inSection: 1) ?? 0) > indexOfImage {
let indexPath = IndexPath(item: indexOfImage, section: 1)
imageOfInterest = indexPath
imagesCollection?.scrollToItem(at: indexPath, at: .centeredVertically, animated: true)
}
}
func didUpdateImage(withData imageData: PiwigoImageData) {
// Update data source
let indexOfImage = albumData?.updateImage(imageData) ?? 0
if indexOfImage == NSNotFound { return }
// Refresh image banner
let indexPath = IndexPath(item: indexOfImage, section: 1)
if imagesCollection?.indexPathsForVisibleItems.contains(indexPath) ?? false {
imagesCollection?.reloadItems(at: [indexPath])
}
}
func needToLoadMoreImages() {
// Check that album data exists
guard let currentAlbumData = CategoriesData.sharedInstance().getCategoryById(categoryId) else {
debugPrint("••••••>> needToLoadMoreImages for catID \(self.categoryId)... cancelled")
return
}
// Get number of downloaded images
let downloadedImageCount = currentAlbumData.imageList.count
// Load more images
DispatchQueue.global(qos: .default).async { [self] in
let start = CFAbsoluteTimeGetCurrent()
self.albumData?.loadMoreImages(onCompletion: { [self] done in
// Did we try to collect more images?
if !done {
debugPrint("••••••>> needToLoadMoreImages for catID \(self.categoryId)... nothing done")
return
}
// Should we retry loading more images?
let newDownloadedImageCount = CategoriesData.sharedInstance().getCategoryById(categoryId)?.imageList.count ?? 0
let didProgress = (newDownloadedImageCount > downloadedImageCount)
if !didProgress {
// Did try loading more images but unsuccessfully
debugPrint("••••••>> needToLoadMoreImagesfor catID \(self.categoryId)... unsuccessful!")
if self.didScrollToImageIndex >= newDownloadedImageCount {
// Re-login before continuing to load images
LoginUtilities.reloginAndRetry() { [self] in
DispatchQueue.main.async { [self] in
self.needToLoadMoreImages()
}
} failure: { [self] error in
let title = NSLocalizedString("imageDetailsFetchError_title", comment: "Image Details Fetch Failed")
self.dismissPiwigoError(withTitle: title, completion: {})
}
}
return
}
// Prepare indexPaths of cells to reload
var indexPaths: [IndexPath] = []
for i in downloadedImageCount..<newDownloadedImageCount {
indexPaths.append(IndexPath(item: i, section: 1))
}
// Back to main thread…
DispatchQueue.main.async { [self] in
// Update detail view if needed
if let imageDetailView = self.imageDetailView {
imageDetailView.images = self.albumData?.images ?? []
}
// Add indexPaths of cell presented with placeholder
let placeHolderImage = UIImage(named: "placeholderImage")
for indexPath in self.imagesCollection?.indexPathsForVisibleItems ?? [] {
if indexPath.section == 0 { continue }
if indexPaths.contains(indexPath) { continue }
let cell = self.imagesCollection?.cellForItem(at: indexPath)
if let imageCell = cell as? ImageCollectionViewCell,
imageCell.cellImage.image == placeHolderImage {
indexPaths.append(indexPath)
}
}
// Reload cells
self.imagesCollection?.reloadItems(at: indexPaths)
// Display HUD if it will take more than a second to load image data
let diff: CFAbsoluteTime = Double((CFAbsoluteTimeGetCurrent() - start)) * 1000.0
let perImage = abs(Float(Double(diff) / Double(newDownloadedImageCount - downloadedImageCount)))
let left: Double = Double(perImage) * Double(max(0, (didScrollToImageIndex - newDownloadedImageCount)))
print(String(format: "expected time: %.2f ms (diff: %.0f, perImage: %.0f)", left, diff, perImage))
if left > 1000.0, didProgress {
if view.viewWithTag(loadingViewTag) == nil {
self.showPiwigoHUD(withTitle: NSLocalizedString("loadingHUD_label", comment: "Loading…"), inMode: .annularDeterminate)
} else {
let fraction = Float(newDownloadedImageCount) / Float(didScrollToImageIndex)
self.updatePiwigoHUD(withProgress: fraction)
}
} else {
self.hidePiwigoHUD() { }
}
// Should we continue loading images?
print(String(format: "==> Should we continue loading images? (scrolled to %ld)", didScrollToImageIndex))
if self.didScrollToImageIndex >= newDownloadedImageCount {
if didProgress {
// Continue loadding images
self.needToLoadMoreImages()
} else {
// Re-login before continuing to load images
LoginUtilities.reloginAndRetry() { [self] in
DispatchQueue.main.async { [self] in
self.needToLoadMoreImages()
}
} failure: { [unowned self] error in
let title = NSLocalizedString("imageDetailsFetchError_title", comment: "Image Details Fetch Failed")
self.dismissPiwigoError(withTitle: title, completion: {})
}
}
}
}
}, onFailure: nil)
}
}
// MARK: - SelectCategoryDelegate Methods
func didSelectCategory(withId category: Int) {
if category == NSNotFound {
setEnableStateOfButtons(true)
} else {
cancelSelect()
}
}
// MARK: - ChangedSettingsDelegate Methods
func didChangeDefaultAlbum() {
// Change default album
categoryId = AlbumVars.shared.defaultCategory
// Add/remove search bar
if #available(iOS 11.0, *) {
if categoryId == 0 {
// Initialise search bar
initSearchBar()
} else {
// Remove search bar from the navigation bar
navigationItem.searchController = nil
}
}
// Initialise data source
albumData = AlbumData(categoryId: categoryId, andQuery: "")
// Reset buttons and menus
updateButtonsInPreviewMode()
// Reload album
imagesCollection?.reloadData()
}
func didChangeRecentPeriod() {
// Reload album
imagesCollection?.reloadData()
}
// MARK: - AlbumCollectionViewCellDelegate Method (+ PushView:)
@objc
func removeCategory(_ albumCell: AlbumCollectionViewCell?) {
// Update data source
albumData = AlbumData(categoryId: categoryId, andQuery: "")
// Remove cell
var indexPath: IndexPath? = nil
if let albumCell = albumCell {
indexPath = imagesCollection?.indexPath(for: albumCell)
}
imagesCollection?.deleteItems(at: [indexPath].compactMap { $0 })
// If necessary, update the cell of the category into which the album was moved
for indexPath in imagesCollection?.indexPathsForVisibleItems ?? [] {
if indexPath.section == 1 { return }
if let cell = imagesCollection?.cellForItem(at: indexPath) as? AlbumCollectionViewCell,
cell.albumData?.albumId == albumCell?.albumData?.parentAlbumId {
imagesCollection?.reloadItems(at: [indexPath])
}
}
}
@objc
func pushCategoryView(_ viewController: UIViewController?) {
guard let viewController = viewController else {
return
}
// Push sub-album, Discover or Favorites album
if viewController is AlbumViewController {
// Push sub-album view
navigationController?.pushViewController(viewController, animated: true)
}
else {
// Push album list
if UIDevice.current.userInterfaceIdiom == .pad {
viewController.modalPresentationStyle = .popover
viewController.popoverPresentationController?.sourceView = imagesCollection
viewController.popoverPresentationController?.permittedArrowDirections = UIPopoverArrowDirection(rawValue: 0)
navigationController?.present(viewController, animated: true)
}
else {
let navController = UINavigationController(rootViewController: viewController)
navController.modalPresentationStyle = .popover
navController.popoverPresentationController?.sourceView = view
navController.modalTransitionStyle = .coverVertical
navigationController?.present(navController, animated: true)
}
}
}
func pushView(_ viewController: UIViewController?) {
guard let viewController = viewController else {
return
}
// Push album list or tag list
if UIDevice.current.userInterfaceIdiom == .pad {
viewController.modalPresentationStyle = .popover
if viewController is SelectCategoryViewController {
if #available(iOS 14.0, *) {
viewController.popoverPresentationController?.barButtonItem = actionBarButton
} else {
viewController.popoverPresentationController?.barButtonItem = moveBarButton
}
viewController.popoverPresentationController?.permittedArrowDirections = .up
navigationController?.present(viewController, animated: true)
}
else if viewController is TagSelectorViewController {
viewController.popoverPresentationController?.barButtonItem = discoverBarButton
viewController.popoverPresentationController?.permittedArrowDirections = .up
navigationController?.present(viewController, animated: true)
}
else if viewController is EditImageParamsViewController {
// Push Edit view embedded in navigation controller
let navController = UINavigationController(rootViewController: viewController)
navController.modalPresentationStyle = .popover
navController.popoverPresentationController?.barButtonItem = actionBarButton
navController.popoverPresentationController?.permittedArrowDirections = .up
navigationController?.present(navController, animated: true)
}
} else {
let navController = UINavigationController(rootViewController: viewController)
navController.modalPresentationStyle = .popover
navController.popoverPresentationController?.sourceView = view
navController.modalTransitionStyle = .coverVertical
navigationController?.present(navController, animated: true)
}
}
// MARK: - UIScrollViewDelegate
func scrollViewDidScroll(_ scrollView: UIScrollView) {
let navBarHeight = (navigationController?.navigationBar.frame.origin.y ?? 0.0) + (navigationController?.navigationBar.frame.size.height ?? 0.0)
// NSLog(@"==>> %f", scrollView.contentOffset.y + navBarHeight);
if (roundf(Float(scrollView.contentOffset.y + navBarHeight)) > 1) ||
(categoryId != AlbumVars.shared.defaultCategory) {
// Show navigation bar border
if #available(iOS 13.0, *) {
let navBar = navigationItem
let barAppearance = navBar.standardAppearance
let shadowColor = AppVars.shared.isDarkPaletteActive ? UIColor(white: 1.0, alpha: 0.15) : UIColor(white: 0.0, alpha: 0.3)
if barAppearance?.shadowColor != shadowColor {
barAppearance?.shadowColor = shadowColor
navBar.scrollEdgeAppearance = barAppearance
}
}
} else {
// Hide navigation bar border
if #available(iOS 13.0, *) {
let navBar = navigationItem
let barAppearance = navBar.standardAppearance
if barAppearance?.shadowColor != UIColor.clear {
barAppearance?.shadowColor = UIColor.clear
navBar.scrollEdgeAppearance = barAppearance
}
}
}
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
}
|
mit
|
887e041076366ad2403097be22ff4af0
| 46.179329 | 306 | 0.618274 | 5.839461 | false | false | false | false |
songzhw/2iOS
|
Swift101/Swift101/ByteManupulation.swift
|
1
|
711
|
import Foundation
let srcData = "多伦多".data(using: .utf8)!
func byteManu(){
// 使用[UInt8]
let bytes1 = [UInt8](srcData)
print(bytes1) //=> [229, 164, 154, 228, 188, 166, 229, 164, 154]
// 使用指针 (Swift5开始的用法)
let bytes2 = srcData.withUnsafeBytes { (pointer: UnsafeRawBufferPointer) -> [UInt8] in
if let ptrAddress = pointer.baseAddress, pointer.count > 0 {
let pointer : UnsafePointer<UInt8> = ptrAddress.assumingMemoryBound(to: UInt8.self)
let buffer = UnsafeBufferPointer(start: pointer, count: srcData.count)
return Array<UInt8>(buffer)
}
return Array<UInt8>()
}
print(bytes2) //=> [229, 164, 154, 228, 188, 166, 229, 164, 154]
}
|
apache-2.0
|
b107665e719e5ea867e91fe1b5c19b94
| 31.52381 | 89 | 0.657394 | 3.283654 | false | false | false | false |
huonw/swift
|
stdlib/public/core/Dictionary.swift
|
1
|
161504
|
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2018 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 SwiftShims
// Implementation notes
// ====================
//
// `Dictionary` uses two storage schemes: native storage and Cocoa storage.
//
// Native storage is a hash table with open addressing and linear probing. The
// bucket array forms a logical ring (e.g., a chain can wrap around the end of
// buckets array to the beginning of it).
//
// The logical bucket array is implemented as three arrays: Key, Value, and a
// bitmap that marks valid entries. An invalid entry marks the end of a chain.
// There is always at least one invalid entry among the buckets. `Dictionary`
// does not use tombstones.
//
// In addition to the native storage, `Dictionary` can also wrap an
// `NSDictionary` in order to allow bridging `NSDictionary` to `Dictionary` in
// `O(1)`.
//
// Currently native storage uses a data structure like this::
//
// Dictionary<K,V> (a struct)
// +------------------------------------------------+
// | _VariantDictionaryBuffer<K,V> (an enum) |
// | +--------------------------------------------+ |
// | | [_NativeDictionaryBuffer<K,V> (a struct)] | |
// | +---|----------------------------------------+ |
// +----/-------------------------------------------+
// /
// |
// V _RawNativeDictionaryStorage (a class)
// +-----------------------------------------------------------+
// | bucketCount |
// | count |
// | ptrToBits |
// | ptrToKeys |
// | ptrToValues |
// | [inline array of bits indicating whether bucket is set ] |
// | [inline array of keys ] |
// | [inline array of values ] |
// +-----------------------------------------------------------+
//
//
// Cocoa storage uses a data structure like this::
//
// Dictionary<K,V> (a struct)
// +----------------------------------------------+
// | _VariantDictionaryBuffer<K,V> (an enum) |
// | +----------------------------------------+ |
// | | [ _CocoaDictionaryBuffer (a struct) ] | |
// | +---|------------------------------------+ |
// +-----|----------------------------------------+
// |
// +---+
// |
// V NSDictionary (a class)
// +--------------+
// | [refcount#1] |
// +--------------+
// ^
// +-+
// | Dictionary<K,V>.Index (an enum)
// +---|-----------------------------------+
// | | _CocoaDictionaryIndex (a struct) |
// | +-|-----------------------------+ |
// | | * [ all keys ] [ next index ] | |
// | +-------------------------------+ |
// +---------------------------------------+
//
//
// The Native Kinds of Storage
// ---------------------------
//
// There are three different classes that can provide a native backing storage:
// * `_RawNativeDictionaryStorage`
// * `_TypedNativeDictionaryStorage<K, V>` (extends Raw)
// * `_HashableTypedNativeDictionaryStorage<K: Hashable, V>` (extends Typed)
//
// (Hereafter RawStorage, TypedStorage, and HashableStorage, respectively)
//
// In a less optimized implementation, the parent classes could
// be eliminated, as they exist only to provide special-case behaviors.
// HashableStorage has everything a full implementation of a Dictionary
// requires, and is subsequently able to provide a full NSDictionary
// implementation. Note that HashableStorage must have the `K: Hashable`
// constraint because the NSDictionary implementation can't be provided in a
// constrained extension.
//
// In normal usage, you can expect the backing storage of a Dictionary to be a
// NativeStorage.
//
// TypedStorage is distinguished from HashableStorage to allow us to create a
// `_NativeDictionaryBuffer<AnyObject, AnyObject>`. Without the Hashable
// requirement, such a Buffer is restricted to operations which can be performed
// with only the structure of the Storage: indexing and iteration. This is used
// in _SwiftDeferredNSDictionary to construct twin "native" and "bridged"
// storage. Key-based lookups are performed on the native storage, with the
// resultant index then used on the bridged storage.
//
// The only thing that TypedStorage adds over RawStorage is an implementation of
// deinit, to clean up the AnyObjects it stores. Although it nominally
// inherits an NSDictionary implementation from RawStorage, this implementation
// isn't useful and is never used.
//
// RawStorage exists to allow a type-punned empty singleton Storage to be
// created. Any time an empty Dictionary is created, this Storage is used. If
// this type didn't exist, then NativeBuffer would have to store a Storage that
// declared its actual type parameters. Similarly, the empty singleton would
// have to declare its actual type parameters. If the singleton was, for
// instance, a `HashableStorage<(), ()>`, then it would be a violation of
// Swift's strict aliasing rules to pass it where a `HashableStorage<Int, Int>`
// was expected.
//
// It's therefore necessary for several types to store a RawStorage, rather than
// a TypedStorage, to allow for the possibility of the empty singleton.
// RawStorage also provides an implementation of an always-empty NSDictionary.
//
//
// Index Invalidation
// ------------------
//
// FIXME: decide if this guarantee is worth making, as it restricts
// collision resolution to first-come-first-serve. The most obvious alternative
// would be robin hood hashing. The Rust code base is the best
// resource on a *practical* implementation of robin hood hashing I know of:
// https://github.com/rust-lang/rust/blob/ac919fcd9d4a958baf99b2f2ed5c3d38a2ebf9d0/src/libstd/collections/hash/map.rs#L70-L178
//
// Indexing a container, `c[i]`, uses the integral offset stored in the index
// to access the elements referenced by the container. Generally, an index into
// one container has no meaning for another. However copy-on-write currently
// preserves indices under insertion, as long as reallocation doesn't occur:
//
// var (i, found) = d.find(k) // i is associated with d's storage
// if found {
// var e = d // now d is sharing its data with e
// e[newKey] = newValue // e now has a unique copy of the data
// return e[i] // use i to access e
// }
//
// The result should be a set of iterator invalidation rules familiar to anyone
// familiar with the C++ standard library. Note that because all accesses to a
// dictionary storage are bounds-checked, this scheme never compromises memory
// safety.
//
//
// Bridging
// ========
//
// Bridging `NSDictionary` to `Dictionary`
// ---------------------------------------
//
// FIXME(eager-bridging): rewrite this based on modern constraints.
//
// `NSDictionary` bridges to `Dictionary<NSObject, AnyObject>` in `O(1)`,
// without memory allocation.
//
// Bridging `Dictionary` to `NSDictionary`
// ---------------------------------------
//
// `Dictionary<K, V>` bridges to `NSDictionary` in O(1)
// but may incur an allocation depending on the following conditions:
//
// * If the Dictionary is freshly allocated without any elements, then it
// contains the empty singleton Storage which is returned as a toll-free
// implementation of `NSDictionary`.
//
// * If both `K` and `V` are bridged verbatim, then `Dictionary<K, V>` is
// still toll-free bridged to `NSDictionary` by returning its Storage.
//
// * If the Dictionary is actually a lazily bridged NSDictionary, then that
// NSDictionary is returned.
//
// * Otherwise, bridging the `Dictionary` is done by wrapping its buffer in a
// `_SwiftDeferredNSDictionary<K, V>`. This incurs an O(1)-sized allocation.
//
// Complete bridging of the native Storage's elements to another Storage
// is performed on first access. This is O(n) work, but is hopefully amortized
// by future accesses.
//
// This design ensures that:
// - Every time keys or values are accessed on the bridged `NSDictionary`,
// new objects are not created.
// - Accessing the same element (key or value) multiple times will return
// the same pointer.
//
// Bridging `NSSet` to `Set` and vice versa
// ----------------------------------------
//
// Bridging guarantees for `Set<Element>` are the same as for
// `Dictionary<Element, ()>`.
//
//===--- APIs unique to Dictionary<Key, Value> ----------------------------===//
/// A collection whose elements are key-value pairs.
///
/// A dictionary is a type of hash table, providing fast access to the entries
/// it contains. Each entry in the table is identified using its key, which is
/// a hashable type such as a string or number. You use that key to retrieve
/// the corresponding value, which can be any object. In other languages,
/// similar data types are known as hashes or associated arrays.
///
/// Create a new dictionary by using a dictionary literal. A dictionary literal
/// is a comma-separated list of key-value pairs, in which a colon separates
/// each key from its associated value, surrounded by square brackets. You can
/// assign a dictionary literal to a variable or constant or pass it to a
/// function that expects a dictionary.
///
/// Here's how you would create a dictionary of HTTP response codes and their
/// related messages:
///
/// var responseMessages = [200: "OK",
/// 403: "Access forbidden",
/// 404: "File not found",
/// 500: "Internal server error"]
///
/// The `responseMessages` variable is inferred to have type `[Int: String]`.
/// The `Key` type of the dictionary is `Int`, and the `Value` type of the
/// dictionary is `String`.
///
/// To create a dictionary with no key-value pairs, use an empty dictionary
/// literal (`[:]`).
///
/// var emptyDict: [String: String] = [:]
///
/// Any type that conforms to the `Hashable` protocol can be used as a
/// dictionary's `Key` type, including all of Swift's basic types. You can use
/// your own custom types as dictionary keys by making them conform to the
/// `Hashable` protocol.
///
/// Getting and Setting Dictionary Values
/// =====================================
///
/// The most common way to access values in a dictionary is to use a key as a
/// subscript. Subscripting with a key takes the following form:
///
/// print(responseMessages[200])
/// // Prints "Optional("OK")"
///
/// Subscripting a dictionary with a key returns an optional value, because a
/// dictionary might not hold a value for the key that you use in the
/// subscript.
///
/// The next example uses key-based subscripting of the `responseMessages`
/// dictionary with two keys that exist in the dictionary and one that does
/// not.
///
/// let httpResponseCodes = [200, 403, 301]
/// for code in httpResponseCodes {
/// if let message = responseMessages[code] {
/// print("Response \(code): \(message)")
/// } else {
/// print("Unknown response \(code)")
/// }
/// }
/// // Prints "Response 200: OK"
/// // Prints "Response 403: Access Forbidden"
/// // Prints "Unknown response 301"
///
/// You can also update, modify, or remove keys and values from a dictionary
/// using the key-based subscript. To add a new key-value pair, assign a value
/// to a key that isn't yet a part of the dictionary.
///
/// responseMessages[301] = "Moved permanently"
/// print(responseMessages[301])
/// // Prints "Optional("Moved permanently")"
///
/// Update an existing value by assigning a new value to a key that already
/// exists in the dictionary. If you assign `nil` to an existing key, the key
/// and its associated value are removed. The following example updates the
/// value for the `404` code to be simply "Not found" and removes the
/// key-value pair for the `500` code entirely.
///
/// responseMessages[404] = "Not found"
/// responseMessages[500] = nil
/// print(responseMessages)
/// // Prints "[301: "Moved permanently", 200: "OK", 403: "Access forbidden", 404: "Not found"]"
///
/// In a mutable `Dictionary` instance, you can modify in place a value that
/// you've accessed through a keyed subscript. The code sample below declares a
/// dictionary called `interestingNumbers` with string keys and values that
/// are integer arrays, then sorts each array in-place in descending order.
///
/// var interestingNumbers = ["primes": [2, 3, 5, 7, 11, 13, 15],
/// "triangular": [1, 3, 6, 10, 15, 21, 28],
/// "hexagonal": [1, 6, 15, 28, 45, 66, 91]]
/// for key in interestingNumbers.keys {
/// interestingNumbers[key]?.sort(by: >)
/// }
///
/// print(interestingNumbers["primes"]!)
/// // Prints "[15, 13, 11, 7, 5, 3, 2]"
///
/// Iterating Over the Contents of a Dictionary
/// ===========================================
///
/// Every dictionary is an unordered collection of key-value pairs. You can
/// iterate over a dictionary using a `for`-`in` loop, decomposing each
/// key-value pair into the elements of a tuple.
///
/// let imagePaths = ["star": "/glyphs/star.png",
/// "portrait": "/images/content/portrait.jpg",
/// "spacer": "/images/shared/spacer.gif"]
///
/// for (name, path) in imagePaths {
/// print("The path to '\(name)' is '\(path)'.")
/// }
/// // Prints "The path to 'star' is '/glyphs/star.png'."
/// // Prints "The path to 'portrait' is '/images/content/portrait.jpg'."
/// // Prints "The path to 'spacer' is '/images/shared/spacer.gif'."
///
/// The order of key-value pairs in a dictionary is stable between mutations
/// but is otherwise unpredictable. If you need an ordered collection of
/// key-value pairs and don't need the fast key lookup that `Dictionary`
/// provides, see the `DictionaryLiteral` type for an alternative.
///
/// You can search a dictionary's contents for a particular value using the
/// `contains(where:)` or `firstIndex(where:)` methods supplied by default
/// implementation. The following example checks to see if `imagePaths` contains
/// any paths in the `"/glyphs"` directory:
///
/// let glyphIndex = imagePaths.firstIndex(where: { $0.value.hasPrefix("/glyphs") })
/// if let index = glyphIndex {
/// print("The '\(imagesPaths[index].key)' image is a glyph.")
/// } else {
/// print("No glyphs found!")
/// }
/// // Prints "The 'star' image is a glyph.")
///
/// Note that in this example, `imagePaths` is subscripted using a dictionary
/// index. Unlike the key-based subscript, the index-based subscript returns
/// the corresponding key-value pair as a non-optional tuple.
///
/// print(imagePaths[glyphIndex!])
/// // Prints "("star", "/glyphs/star.png")"
///
/// A dictionary's indices stay valid across additions to the dictionary as
/// long as the dictionary has enough capacity to store the added values
/// without allocating more buffer. When a dictionary outgrows its buffer,
/// existing indices may be invalidated without any notification.
///
/// When you know how many new values you're adding to a dictionary, use the
/// `init(minimumCapacity:)` initializer to allocate the correct amount of
/// buffer.
///
/// Bridging Between Dictionary and NSDictionary
/// ============================================
///
/// You can bridge between `Dictionary` and `NSDictionary` using the `as`
/// operator. For bridging to be possible, the `Key` and `Value` types of a
/// dictionary must be classes, `@objc` protocols, or types that bridge to
/// Foundation types.
///
/// Bridging from `Dictionary` to `NSDictionary` always takes O(1) time and
/// space. When the dictionary's `Key` and `Value` types are neither classes
/// nor `@objc` protocols, any required bridging of elements occurs at the
/// first access of each element. For this reason, the first operation that
/// uses the contents of the dictionary may take O(*n*).
///
/// Bridging from `NSDictionary` to `Dictionary` first calls the `copy(with:)`
/// method (`- copyWithZone:` in Objective-C) on the dictionary to get an
/// immutable copy and then performs additional Swift bookkeeping work that
/// takes O(1) time. For instances of `NSDictionary` that are already
/// immutable, `copy(with:)` usually returns the same dictionary in O(1) time;
/// otherwise, the copying performance is unspecified. The instances of
/// `NSDictionary` and `Dictionary` share buffer using the same copy-on-write
/// optimization that is used when two instances of `Dictionary` share
/// buffer.
@_fixed_layout
public struct Dictionary<Key: Hashable, Value> {
internal typealias _Self = Dictionary<Key, Value>
internal typealias _VariantBuffer = _VariantDictionaryBuffer<Key, Value>
internal typealias _NativeBuffer = _NativeDictionaryBuffer<Key, Value>
/// The element type of a dictionary: a tuple containing an individual
/// key-value pair.
public typealias Element = (key: Key, value: Value)
@usableFromInline
internal var _variantBuffer: _VariantBuffer
/// Creates an empty dictionary.
@inlinable // FIXME(sil-serialize-all)
public init() {
self = Dictionary<Key, Value>(_nativeBuffer: _NativeBuffer())
}
/// Creates an empty dictionary with preallocated space for at least the
/// specified number of elements.
///
/// Use this initializer to avoid intermediate reallocations of a dictionary's
/// storage buffer when you know how many key-value pairs you are adding to a
/// dictionary after creation.
///
/// - Parameter minimumCapacity: The minimum number of key-value pairs that
/// the newly created dictionary should be able to store without
// reallocating its storage buffer.
@inlinable // FIXME(sil-serialize-all)
public init(minimumCapacity: Int) {
_variantBuffer = .native(_NativeBuffer(minimumCapacity: minimumCapacity))
}
/// Creates a new dictionary from the key-value pairs in the given sequence.
///
/// You use this initializer to create a dictionary when you have a sequence
/// of key-value tuples with unique keys. Passing a sequence with duplicate
/// keys to this initializer results in a runtime error. If your
/// sequence might have duplicate keys, use the
/// `Dictionary(_:uniquingKeysWith:)` initializer instead.
///
/// The following example creates a new dictionary using an array of strings
/// as the keys and the integers in a countable range as the values:
///
/// let digitWords = ["one", "two", "three", "four", "five"]
/// let wordToValue = Dictionary(uniqueKeysWithValues: zip(digitWords, 1...5))
/// print(wordToValue["three"]!)
/// // Prints "3"
/// print(wordToValue)
/// // Prints "["three": 3, "four": 4, "five": 5, "one": 1, "two": 2]"
///
/// - Parameter keysAndValues: A sequence of key-value pairs to use for
/// the new dictionary. Every key in `keysAndValues` must be unique.
/// - Returns: A new dictionary initialized with the elements of
/// `keysAndValues`.
/// - Precondition: The sequence must not have duplicate keys.
@inlinable // FIXME(sil-serialize-all)
public init<S: Sequence>(
uniqueKeysWithValues keysAndValues: S
) where S.Element == (Key, Value) {
if let d = keysAndValues as? Dictionary<Key, Value> {
self = d
} else {
self = Dictionary(minimumCapacity: keysAndValues.underestimatedCount)
// '_MergeError.keyCollision' is caught and handled with an appropriate
// error message one level down, inside _variantBuffer.merge(_:...).
try! _variantBuffer.merge(
keysAndValues,
uniquingKeysWith: { _, _ in throw _MergeError.keyCollision})
}
}
/// Creates a new dictionary from the key-value pairs in the given sequence,
/// using a combining closure to determine the value for any duplicate keys.
///
/// You use this initializer to create a dictionary when you have a sequence
/// of key-value tuples that might have duplicate keys. As the dictionary is
/// built, the initializer calls the `combine` closure with the current and
/// new values for any duplicate keys. Pass a closure as `combine` that
/// returns the value to use in the resulting dictionary: The closure can
/// choose between the two values, combine them to produce a new value, or
/// even throw an error.
///
/// The following example shows how to choose the first and last values for
/// any duplicate keys:
///
/// let pairsWithDuplicateKeys = [("a", 1), ("b", 2), ("a", 3), ("b", 4)]
///
/// let firstValues = Dictionary(pairsWithDuplicateKeys,
/// uniquingKeysWith: { (first, _) in first })
/// // ["b": 2, "a": 1]
///
/// let lastValues = Dictionary(pairsWithDuplicateKeys,
/// uniquingKeysWith: { (_, last) in last })
/// // ["b": 4, "a": 3]
///
/// - Parameters:
/// - keysAndValues: A sequence of key-value pairs to use for the new
/// dictionary.
/// - combine: A closure that is called with the values for any duplicate
/// keys that are encountered. The closure returns the desired value for
/// the final dictionary.
@inlinable // FIXME(sil-serialize-all)
public init<S: Sequence>(
_ keysAndValues: S,
uniquingKeysWith combine: (Value, Value) throws -> Value
) rethrows where S.Element == (Key, Value) {
self = Dictionary(minimumCapacity: keysAndValues.underestimatedCount)
try _variantBuffer.merge(keysAndValues, uniquingKeysWith: combine)
}
/// Creates a new dictionary whose keys are the groupings returned by the
/// given closure and whose values are arrays of the elements that returned
/// each key.
///
/// The arrays in the "values" position of the new dictionary each contain at
/// least one element, with the elements in the same order as the source
/// sequence.
///
/// The following example declares an array of names, and then creates a
/// dictionary from that array by grouping the names by first letter:
///
/// let students = ["Kofi", "Abena", "Efua", "Kweku", "Akosua"]
/// let studentsByLetter = Dictionary(grouping: students, by: { $0.first! })
/// // ["E": ["Efua"], "K": ["Kofi", "Kweku"], "A": ["Abena", "Akosua"]]
///
/// The new `studentsByLetter` dictionary has three entries, with students'
/// names grouped by the keys `"E"`, `"K"`, and `"A"`.
///
/// - Parameters:
/// - values: A sequence of values to group into a dictionary.
/// - keyForValue: A closure that returns a key for each element in
/// `values`.
@inlinable // FIXME(sil-serialize-all)
public init<S: Sequence>(
grouping values: S,
by keyForValue: (S.Element) throws -> Key
) rethrows where Value == [S.Element] {
self = [:]
try _variantBuffer.nativeGroup(values, by: keyForValue)
}
@inlinable // FIXME(sil-serialize-all)
internal init(_nativeBuffer: _NativeDictionaryBuffer<Key, Value>) {
_variantBuffer =
.native(_nativeBuffer)
}
@inlinable // FIXME(sil-serialize-all)
internal init(_variantBuffer: _VariantBuffer) {
self._variantBuffer = _variantBuffer
}
#if _runtime(_ObjC)
/// Private initializer used for bridging.
///
/// Only use this initializer when both conditions are true:
///
/// * it is statically known that the given `NSDictionary` is immutable;
/// * `Key` and `Value` are bridged verbatim to Objective-C (i.e.,
/// are reference types).
@inlinable // FIXME(sil-serialize-all)
public init(_immutableCocoaDictionary: _NSDictionary) {
_sanityCheck(
_isBridgedVerbatimToObjectiveC(Key.self) &&
_isBridgedVerbatimToObjectiveC(Value.self),
"Dictionary can be backed by NSDictionary buffer only when both key and value are bridged verbatim to Objective-C")
_variantBuffer = .cocoa(
_CocoaDictionaryBuffer(cocoaDictionary: _immutableCocoaDictionary))
}
#endif
}
//
// All APIs below should dispatch to `_variantBuffer`, without doing any
// additional processing.
//
extension Dictionary: Sequence {
/// Returns an iterator over the dictionary's key-value pairs.
///
/// Iterating over a dictionary yields the key-value pairs as two-element
/// tuples. You can decompose the tuple in a `for`-`in` loop, which calls
/// `makeIterator()` behind the scenes, or when calling the iterator's
/// `next()` method directly.
///
/// let hues = ["Heliotrope": 296, "Coral": 16, "Aquamarine": 156]
/// for (name, hueValue) in hues {
/// print("The hue of \(name) is \(hueValue).")
/// }
/// // Prints "The hue of Heliotrope is 296."
/// // Prints "The hue of Coral is 16."
/// // Prints "The hue of Aquamarine is 156."
///
/// - Returns: An iterator over the dictionary with elements of type
/// `(key: Key, value: Value)`.
@inlinable // FIXME(sil-serialize-all)
@inline(__always)
public func makeIterator() -> DictionaryIterator<Key, Value> {
return _variantBuffer.makeIterator()
}
}
// This is not quite Sequence.filter, because that returns [Element], not Self
extension Dictionary {
/// Returns a new dictionary containing the key-value pairs of the dictionary
/// that satisfy the given predicate.
///
/// - Parameter isIncluded: A closure that takes a key-value pair as its
/// argument and returns a Boolean value indicating whether the pair
/// should be included in the returned dictionary.
/// - Returns: A dictionary of the key-value pairs that `isIncluded` allows.
@inlinable
@available(swift, introduced: 4.0)
public func filter(
_ isIncluded: (Element) throws -> Bool
) rethrows -> [Key: Value] {
var result = Dictionary()
for el in self {
if try isIncluded(el) {
result[el.key] = el.value
}
}
return result
}
}
extension Dictionary: Collection {
/// The position of the first element in a nonempty dictionary.
///
/// If the collection is empty, `startIndex` is equal to `endIndex`.
///
/// - Complexity: Amortized O(1) if the dictionary does not wrap a bridged
/// `NSDictionary`. If the dictionary wraps a bridged `NSDictionary`, the
/// performance is unspecified.
@inlinable // FIXME(sil-serialize-all)
public var startIndex: Index {
return _variantBuffer.startIndex
}
/// The dictionary's "past the end" position---that is, the position one
/// greater than the last valid subscript argument.
///
/// If the collection is empty, `endIndex` is equal to `startIndex`.
///
/// - Complexity: Amortized O(1) if the dictionary does not wrap a bridged
/// `NSDictionary`; otherwise, the performance is unspecified.
@inlinable // FIXME(sil-serialize-all)
public var endIndex: Index {
return _variantBuffer.endIndex
}
@inlinable // FIXME(sil-serialize-all)
public func index(after i: Index) -> Index {
return _variantBuffer.index(after: i)
}
/// Returns the index for the given key.
///
/// If the given key is found in the dictionary, this method returns an index
/// into the dictionary that corresponds with the key-value pair.
///
/// let countryCodes = ["BR": "Brazil", "GH": "Ghana", "JP": "Japan"]
/// let index = countryCodes.index(forKey: "JP")
///
/// print("Country code for \(countryCodes[index!].value): '\(countryCodes[index!].key)'.")
/// // Prints "Country code for Japan: 'JP'."
///
/// - Parameter key: The key to find in the dictionary.
/// - Returns: The index for `key` and its associated value if `key` is in
/// the dictionary; otherwise, `nil`.
@inlinable // FIXME(sil-serialize-all)
@inline(__always)
public func index(forKey key: Key) -> Index? {
// Complexity: amortized O(1) for native buffer, O(*n*) when wrapping an
// NSDictionary.
return _variantBuffer.index(forKey: key)
}
/// Accesses the key-value pair at the specified position.
///
/// This subscript takes an index into the dictionary, instead of a key, and
/// returns the corresponding key-value pair as a tuple. When performing
/// collection-based operations that return an index into a dictionary, use
/// this subscript with the resulting value.
///
/// For example, to find the key for a particular value in a dictionary, use
/// the `firstIndex(where:)` method.
///
/// let countryCodes = ["BR": "Brazil", "GH": "Ghana", "JP": "Japan"]
/// if let index = countryCodes.firstIndex(where: { $0.value == "Japan" }) {
/// print(countryCodes[index])
/// print("Japan's country code is '\(countryCodes[index].key)'.")
/// } else {
/// print("Didn't find 'Japan' as a value in the dictionary.")
/// }
/// // Prints "("JP", "Japan")"
/// // Prints "Japan's country code is 'JP'."
///
/// - Parameter position: The position of the key-value pair to access.
/// `position` must be a valid index of the dictionary and not equal to
/// `endIndex`.
/// - Returns: A two-element tuple with the key and value corresponding to
/// `position`.
@inlinable // FIXME(sil-serialize-all)
public subscript(position: Index) -> Element {
return _variantBuffer.assertingGet(position)
}
/// The number of key-value pairs in the dictionary.
///
/// - Complexity: O(1).
@inlinable // FIXME(sil-serialize-all)
public var count: Int {
return _variantBuffer.count
}
//
// `Sequence` conformance
//
/// A Boolean value that indicates whether the dictionary is empty.
///
/// Dictionaries are empty when created with an initializer or an empty
/// dictionary literal.
///
/// var frequencies: [String: Int] = [:]
/// print(frequencies.isEmpty)
/// // Prints "true"
@inlinable // FIXME(sil-serialize-all)
public var isEmpty: Bool {
return count == 0
}
}
extension Dictionary {
/// Accesses the value associated with the given key for reading and writing.
///
/// This *key-based* subscript returns the value for the given key if the key
/// is found in the dictionary, or `nil` if the key is not found.
///
/// The following example creates a new dictionary and prints the value of a
/// key found in the dictionary (`"Coral"`) and a key not found in the
/// dictionary (`"Cerise"`).
///
/// var hues = ["Heliotrope": 296, "Coral": 16, "Aquamarine": 156]
/// print(hues["Coral"])
/// // Prints "Optional(16)"
/// print(hues["Cerise"])
/// // Prints "nil"
///
/// When you assign a value for a key and that key already exists, the
/// dictionary overwrites the existing value. If the dictionary doesn't
/// contain the key, the key and value are added as a new key-value pair.
///
/// Here, the value for the key `"Coral"` is updated from `16` to `18` and a
/// new key-value pair is added for the key `"Cerise"`.
///
/// hues["Coral"] = 18
/// print(hues["Coral"])
/// // Prints "Optional(18)"
///
/// hues["Cerise"] = 330
/// print(hues["Cerise"])
/// // Prints "Optional(330)"
///
/// If you assign `nil` as the value for the given key, the dictionary
/// removes that key and its associated value.
///
/// In the following example, the key-value pair for the key `"Aquamarine"`
/// is removed from the dictionary by assigning `nil` to the key-based
/// subscript.
///
/// hues["Aquamarine"] = nil
/// print(hues)
/// // Prints "["Coral": 18, "Heliotrope": 296, "Cerise": 330]"
///
/// - Parameter key: The key to find in the dictionary.
/// - Returns: The value associated with `key` if `key` is in the dictionary;
/// otherwise, `nil`.
@inlinable // FIXME(sil-serialize-all)
public subscript(key: Key) -> Value? {
@inline(__always)
get {
return _variantBuffer.maybeGet(key)
}
set(newValue) {
if let x = newValue {
// FIXME(performance): this loads and discards the old value.
_variantBuffer.updateValue(x, forKey: key)
}
else {
// FIXME(performance): this loads and discards the old value.
removeValue(forKey: key)
}
}
}
}
extension Dictionary: ExpressibleByDictionaryLiteral {
/// Creates a dictionary initialized with a dictionary literal.
///
/// Do not call this initializer directly. It is called by the compiler to
/// handle dictionary literals. To use a dictionary literal as the initial
/// value of a dictionary, enclose a comma-separated list of key-value pairs
/// in square brackets.
///
/// For example, the code sample below creates a dictionary with string keys
/// and values.
///
/// let countryCodes = ["BR": "Brazil", "GH": "Ghana", "JP": "Japan"]
/// print(countryCodes)
/// // Prints "["BR": "Brazil", "JP": "Japan", "GH": "Ghana"]"
///
/// - Parameter elements: The key-value pairs that will make up the new
/// dictionary. Each key in `elements` must be unique.
@inlinable // FIXME(sil-serialize-all)
@_effects(readonly)
public init(dictionaryLiteral elements: (Key, Value)...) {
self.init(_nativeBuffer: _NativeDictionaryBuffer.fromArray(elements))
}
}
extension Dictionary {
/// Accesses the element with the given key, or the specified default value,
/// if the dictionary doesn't contain the given key.
@inlinable // FIXME(sil-serialize-all)
public subscript(
key: Key, default defaultValue: @autoclosure () -> Value
) -> Value {
@inline(__always)
get {
return _variantBuffer.maybeGet(key) ?? defaultValue()
}
mutableAddressWithNativeOwner {
let (_, address) = _variantBuffer
.pointerToValue(forKey: key, insertingDefault: defaultValue)
return (address, Builtin.castToNativeObject(
_variantBuffer.asNative._storage))
}
}
/// Returns a new dictionary containing the keys of this dictionary with the
/// values transformed by the given closure.
///
/// - Parameter transform: A closure that transforms a value. `transform`
/// accepts each value of the dictionary as its parameter and returns a
/// transformed value of the same or of a different type.
/// - Returns: A dictionary containing the keys and transformed values of
/// this dictionary.
@inlinable // FIXME(sil-serialize-all)
public func mapValues<T>(
_ transform: (Value) throws -> T
) rethrows -> Dictionary<Key, T> {
return try Dictionary<Key, T>(
_variantBuffer: _variantBuffer.mapValues(transform))
}
/// Updates the value stored in the dictionary for the given key, or adds a
/// new key-value pair if the key does not exist.
///
/// Use this method instead of key-based subscripting when you need to know
/// whether the new value supplants the value of an existing key. If the
/// value of an existing key is updated, `updateValue(_:forKey:)` returns
/// the original value.
///
/// var hues = ["Heliotrope": 296, "Coral": 16, "Aquamarine": 156]
///
/// if let oldValue = hues.updateValue(18, forKey: "Coral") {
/// print("The old value of \(oldValue) was replaced with a new one.")
/// }
/// // Prints "The old value of 16 was replaced with a new one."
///
/// If the given key is not present in the dictionary, this method adds the
/// key-value pair and returns `nil`.
///
/// if let oldValue = hues.updateValue(330, forKey: "Cerise") {
/// print("The old value of \(oldValue) was replaced with a new one.")
/// } else {
/// print("No value was found in the dictionary for that key.")
/// }
/// // Prints "No value was found in the dictionary for that key."
///
/// - Parameters:
/// - value: The new value to add to the dictionary.
/// - key: The key to associate with `value`. If `key` already exists in
/// the dictionary, `value` replaces the existing associated value. If
/// `key` isn't already a key of the dictionary, the `(key, value)` pair
/// is added.
/// - Returns: The value that was replaced, or `nil` if a new key-value pair
/// was added.
@inlinable // FIXME(sil-serialize-all)
@discardableResult
public mutating func updateValue(
_ value: Value, forKey key: Key
) -> Value? {
return _variantBuffer.updateValue(value, forKey: key)
}
/// Merges the key-value pairs in the given sequence into the dictionary,
/// using a combining closure to determine the value for any duplicate keys.
///
/// Use the `combine` closure to select a value to use in the updated
/// dictionary, or to combine existing and new values. As the key-value
/// pairs are merged with the dictionary, the `combine` closure is called
/// with the current and new values for any duplicate keys that are
/// encountered.
///
/// This example shows how to choose the current or new values for any
/// duplicate keys:
///
/// var dictionary = ["a": 1, "b": 2]
///
/// // Keeping existing value for key "a":
/// dictionary.merge(zip(["a", "c"], [3, 4])) { (current, _) in current }
/// // ["b": 2, "a": 1, "c": 4]
///
/// // Taking the new value for key "a":
/// dictionary.merge(zip(["a", "d"], [5, 6])) { (_, new) in new }
/// // ["b": 2, "a": 5, "c": 4, "d": 6]
///
/// - Parameters:
/// - other: A sequence of key-value pairs.
/// - combine: A closure that takes the current and new values for any
/// duplicate keys. The closure returns the desired value for the final
/// dictionary.
@inlinable // FIXME(sil-serialize-all)
public mutating func merge<S: Sequence>(
_ other: S,
uniquingKeysWith combine: (Value, Value) throws -> Value
) rethrows where S.Element == (Key, Value) {
try _variantBuffer.merge(other, uniquingKeysWith: combine)
}
/// Merges the given dictionary into this dictionary, using a combining
/// closure to determine the value for any duplicate keys.
///
/// Use the `combine` closure to select a value to use in the updated
/// dictionary, or to combine existing and new values. As the key-values
/// pairs in `other` are merged with this dictionary, the `combine` closure
/// is called with the current and new values for any duplicate keys that
/// are encountered.
///
/// This example shows how to choose the current or new values for any
/// duplicate keys:
///
/// var dictionary = ["a": 1, "b": 2]
///
/// // Keeping existing value for key "a":
/// dictionary.merge(["a": 3, "c": 4]) { (current, _) in current }
/// // ["b": 2, "a": 1, "c": 4]
///
/// // Taking the new value for key "a":
/// dictionary.merge(["a": 5, "d": 6]) { (_, new) in new }
/// // ["b": 2, "a": 5, "c": 4, "d": 6]
///
/// - Parameters:
/// - other: A dictionary to merge.
/// - combine: A closure that takes the current and new values for any
/// duplicate keys. The closure returns the desired value for the final
/// dictionary.
@inlinable // FIXME(sil-serialize-all)
public mutating func merge(
_ other: [Key: Value],
uniquingKeysWith combine: (Value, Value) throws -> Value) rethrows
{
try _variantBuffer.merge(
other.lazy.map { ($0, $1) }, uniquingKeysWith: combine)
}
/// Creates a dictionary by merging key-value pairs in a sequence into the
/// dictionary, using a combining closure to determine the value for
/// duplicate keys.
///
/// Use the `combine` closure to select a value to use in the returned
/// dictionary, or to combine existing and new values. As the key-value
/// pairs are merged with the dictionary, the `combine` closure is called
/// with the current and new values for any duplicate keys that are
/// encountered.
///
/// This example shows how to choose the current or new values for any
/// duplicate keys:
///
/// let dictionary = ["a": 1, "b": 2]
/// let newKeyValues = zip(["a", "b"], [3, 4])
///
/// let keepingCurrent = dictionary.merging(newKeyValues) { (current, _) in current }
/// // ["b": 2, "a": 1]
/// let replacingCurrent = dictionary.merging(newKeyValues) { (_, new) in new }
/// // ["b": 4, "a": 3]
///
/// - Parameters:
/// - other: A sequence of key-value pairs.
/// - combine: A closure that takes the current and new values for any
/// duplicate keys. The closure returns the desired value for the final
/// dictionary.
/// - Returns: A new dictionary with the combined keys and values of this
/// dictionary and `other`.
@inlinable // FIXME(sil-serialize-all)
public func merging<S: Sequence>(
_ other: S,
uniquingKeysWith combine: (Value, Value) throws -> Value
) rethrows -> [Key: Value] where S.Element == (Key, Value) {
var result = self
try result._variantBuffer.merge(other, uniquingKeysWith: combine)
return result
}
/// Creates a dictionary by merging the given dictionary into this
/// dictionary, using a combining closure to determine the value for
/// duplicate keys.
///
/// Use the `combine` closure to select a value to use in the returned
/// dictionary, or to combine existing and new values. As the key-value
/// pairs in `other` are merged with this dictionary, the `combine` closure
/// is called with the current and new values for any duplicate keys that
/// are encountered.
///
/// This example shows how to choose the current or new values for any
/// duplicate keys:
///
/// let dictionary = ["a": 1, "b": 2]
/// let otherDictionary = ["a": 3, "b": 4]
///
/// let keepingCurrent = dictionary.merging(otherDictionary)
/// { (current, _) in current }
/// // ["b": 2, "a": 1]
/// let replacingCurrent = dictionary.merging(otherDictionary)
/// { (_, new) in new }
/// // ["b": 4, "a": 3]
///
/// - Parameters:
/// - other: A dictionary to merge.
/// - combine: A closure that takes the current and new values for any
/// duplicate keys. The closure returns the desired value for the final
/// dictionary.
/// - Returns: A new dictionary with the combined keys and values of this
/// dictionary and `other`.
@inlinable // FIXME(sil-serialize-all)
public func merging(
_ other: [Key: Value],
uniquingKeysWith combine: (Value, Value) throws -> Value
) rethrows -> [Key: Value] {
var result = self
try result.merge(other, uniquingKeysWith: combine)
return result
}
/// Removes and returns the key-value pair at the specified index.
///
/// Calling this method invalidates any existing indices for use with this
/// dictionary.
///
/// - Parameter index: The position of the key-value pair to remove. `index`
/// must be a valid index of the dictionary, and must not equal the
/// dictionary's end index.
/// - Returns: The key-value pair that correspond to `index`.
///
/// - Complexity: O(*n*), where *n* is the number of key-value pairs in the
/// dictionary.
@inlinable // FIXME(sil-serialize-all)
@discardableResult
public mutating func remove(at index: Index) -> Element {
return _variantBuffer.remove(at: index)
}
/// Removes the given key and its associated value from the dictionary.
///
/// If the key is found in the dictionary, this method returns the key's
/// associated value. On removal, this method invalidates all indices with
/// respect to the dictionary.
///
/// var hues = ["Heliotrope": 296, "Coral": 16, "Aquamarine": 156]
/// if let value = hues.removeValue(forKey: "Coral") {
/// print("The value \(value) was removed.")
/// }
/// // Prints "The value 16 was removed."
///
/// If the key isn't found in the dictionary, `removeValue(forKey:)` returns
/// `nil`.
///
/// if let value = hues.removeValueForKey("Cerise") {
/// print("The value \(value) was removed.")
/// } else {
/// print("No value found for that key.")
/// }
/// // Prints "No value found for that key.""
///
/// - Parameter key: The key to remove along with its associated value.
/// - Returns: The value that was removed, or `nil` if the key was not
/// present in the dictionary.
///
/// - Complexity: O(*n*), where *n* is the number of key-value pairs in the
/// dictionary.
@inlinable // FIXME(sil-serialize-all)
@discardableResult
public mutating func removeValue(forKey key: Key) -> Value? {
return _variantBuffer.removeValue(forKey: key)
}
/// Removes all key-value pairs from the dictionary.
///
/// Calling this method invalidates all indices with respect to the
/// dictionary.
///
/// - Parameter keepCapacity: Whether the dictionary should keep its
/// underlying buffer. If you pass `true`, the operation preserves the
/// buffer capacity that the collection has, otherwise the underlying
/// buffer is released. The default is `false`.
///
/// - Complexity: O(*n*), where *n* is the number of key-value pairs in the
/// dictionary.
@inlinable // FIXME(sil-serialize-all)
public mutating func removeAll(keepingCapacity keepCapacity: Bool = false) {
// The 'will not decrease' part in the documentation comment is worded very
// carefully. The capacity can increase if we replace Cocoa buffer with
// native buffer.
_variantBuffer.removeAll(keepingCapacity: keepCapacity)
}
}
// Maintain old `keys` and `values` types in Swift 3 mode.
extension Dictionary {
/// A collection containing just the keys of the dictionary.
///
/// When iterated over, keys appear in this collection in the same order as
/// they occur in the dictionary's key-value pairs. Each key in the keys
/// collection has a unique value.
///
/// let countryCodes = ["BR": "Brazil", "GH": "Ghana", "JP": "Japan"]
/// print(countryCodes)
/// // Prints "["BR": "Brazil", "JP": "Japan", "GH": "Ghana"]"
///
/// for k in countryCodes.keys {
/// print(k)
/// }
/// // Prints "BR"
/// // Prints "JP"
/// // Prints "GH"
@inlinable // FIXME(sil-serialize-all)
@available(swift, obsoleted: 4.0)
public var keys: LazyMapCollection<[Key: Value], Key> {
return self.lazy.map { $0.key }
}
/// A collection containing just the values of the dictionary.
///
/// When iterated over, values appear in this collection in the same order as
/// they occur in the dictionary's key-value pairs.
///
/// let countryCodes = ["BR": "Brazil", "GH": "Ghana", "JP": "Japan"]
/// print(countryCodes)
/// // Prints "["BR": "Brazil", "JP": "Japan", "GH": "Ghana"]"
///
/// for v in countryCodes.values {
/// print(v)
/// }
/// // Prints "Brazil"
/// // Prints "Japan"
/// // Prints "Ghana"
@inlinable // FIXME(sil-serialize-all)
@available(swift, obsoleted: 4.0)
public var values: LazyMapCollection<[Key: Value], Value> {
return self.lazy.map { $0.value }
}
}
extension Dictionary {
/// A collection containing just the keys of the dictionary.
///
/// When iterated over, keys appear in this collection in the same order as
/// they occur in the dictionary's key-value pairs. Each key in the keys
/// collection has a unique value.
///
/// let countryCodes = ["BR": "Brazil", "GH": "Ghana", "JP": "Japan"]
/// print(countryCodes)
/// // Prints "["BR": "Brazil", "JP": "Japan", "GH": "Ghana"]"
///
/// for k in countryCodes.keys {
/// print(k)
/// }
/// // Prints "BR"
/// // Prints "JP"
/// // Prints "GH"
@inlinable // FIXME(sil-serialize-all)
@available(swift, introduced: 4.0)
public var keys: Keys {
return Keys(self)
}
/// A collection containing just the values of the dictionary.
///
/// When iterated over, values appear in this collection in the same order as
/// they occur in the dictionary's key-value pairs.
///
/// let countryCodes = ["BR": "Brazil", "GH": "Ghana", "JP": "Japan"]
/// print(countryCodes)
/// // Prints "["BR": "Brazil", "JP": "Japan", "GH": "Ghana"]"
///
/// for v in countryCodes.values {
/// print(v)
/// }
/// // Prints "Brazil"
/// // Prints "Japan"
/// // Prints "Ghana"
@inlinable // FIXME(sil-serialize-all)
@available(swift, introduced: 4.0)
public var values: Values {
get {
return Values(self)
}
set {
self = Dictionary(_variantBuffer: newValue._variantBuffer)
}
}
/// A view of a dictionary's keys.
@_fixed_layout // FIXME(sil-serialize-all)
public struct Keys
: Collection, Equatable,
CustomStringConvertible, CustomDebugStringConvertible {
public typealias Element = Key
@usableFromInline // FIXME(sil-serialize-all)
internal var _variantBuffer: Dictionary._VariantBuffer
@inlinable // FIXME(sil-serialize-all)
internal init(_ _dictionary: Dictionary) {
self._variantBuffer = _dictionary._variantBuffer
}
// Collection Conformance
// ----------------------
@inlinable // FIXME(sil-serialize-all)
public var startIndex: Index {
return _variantBuffer.startIndex
}
@inlinable // FIXME(sil-serialize-all)
public var endIndex: Index {
return _variantBuffer.endIndex
}
@inlinable // FIXME(sil-serialize-all)
public func index(after i: Index) -> Index {
return _variantBuffer.index(after: i)
}
@inlinable // FIXME(sil-serialize-all)
public subscript(position: Index) -> Element {
return _variantBuffer.assertingGet(position).key
}
// Customization
// -------------
/// The number of keys in the dictionary.
///
/// - Complexity: O(1).
@inlinable // FIXME(sil-serialize-all)
public var count: Int {
return _variantBuffer.count
}
@inlinable // FIXME(sil-serialize-all)
public var isEmpty: Bool {
return count == 0
}
@inlinable // FIXME(sil-serialize-all)
public func _customContainsEquatableElement(_ element: Element) -> Bool? {
return _variantBuffer.containsKey(element)
}
@inlinable // FIXME(sil-serialize-all)
public func _customIndexOfEquatableElement(_ element: Element) -> Index?? {
return Optional(_variantBuffer.index(forKey: element))
}
@inlinable // FIXME(sil-serialize-all)
public func _customLastIndexOfEquatableElement(_ element: Element) -> Index?? {
// The first and last elements are the same because each element is unique.
return _customIndexOfEquatableElement(element)
}
@inlinable // FIXME(sil-serialize-all)
public static func ==(lhs: Keys, rhs: Keys) -> Bool {
// Equal if the two dictionaries share storage.
if case (.native(let lhsNative), .native(let rhsNative)) =
(lhs._variantBuffer, rhs._variantBuffer),
lhsNative._storage === rhsNative._storage {
return true
}
// Not equal if the dictionaries are different sizes.
if lhs.count != rhs.count {
return false
}
// Perform unordered comparison of keys.
for key in lhs {
if !rhs.contains(key) {
return false
}
}
return true
}
@inlinable // FIXME(sil-serialize-all)
public var description: String {
return _makeCollectionDescription(for: self, withTypeName: nil)
}
@inlinable // FIXME(sil-serialize-all)
public var debugDescription: String {
return _makeCollectionDescription(for: self, withTypeName: "Dictionary.Keys")
}
}
/// A view of a dictionary's values.
@_fixed_layout // FIXME(sil-serialize-all)
public struct Values
: MutableCollection, CustomStringConvertible, CustomDebugStringConvertible {
public typealias Element = Value
@usableFromInline // FIXME(sil-serialize-all)
internal var _variantBuffer: Dictionary._VariantBuffer
@inlinable // FIXME(sil-serialize-all)
internal init(_ _dictionary: Dictionary) {
self._variantBuffer = _dictionary._variantBuffer
}
// Collection Conformance
// ----------------------
@inlinable // FIXME(sil-serialize-all)
public var startIndex: Index {
return _variantBuffer.startIndex
}
@inlinable // FIXME(sil-serialize-all)
public var endIndex: Index {
return _variantBuffer.endIndex
}
@inlinable // FIXME(sil-serialize-all)
public func index(after i: Index) -> Index {
return _variantBuffer.index(after: i)
}
@inlinable // FIXME(sil-serialize-all)
public subscript(position: Index) -> Element {
get {
return _variantBuffer.assertingGet(position).value
}
mutableAddressWithNativeOwner {
let address = _variantBuffer.pointerToValue(at: position)
return (address, Builtin.castToNativeObject(
_variantBuffer.asNative._storage))
}
}
// Customization
// -------------
/// The number of values in the dictionary.
///
/// - Complexity: O(1).
@inlinable // FIXME(sil-serialize-all)
public var count: Int {
return _variantBuffer.count
}
@inlinable // FIXME(sil-serialize-all)
public var isEmpty: Bool {
return count == 0
}
@inlinable // FIXME(sil-serialize-all)
public var description: String {
return _makeCollectionDescription(for: self, withTypeName: nil)
}
@inlinable // FIXME(sil-serialize-all)
public var debugDescription: String {
return _makeCollectionDescription(for: self, withTypeName: "Dictionary.Values")
}
}
}
extension Dictionary: Equatable where Value: Equatable {
@inlinable // FIXME(sil-serialize-all)
public static func == (lhs: [Key: Value], rhs: [Key: Value]) -> Bool {
switch (lhs._variantBuffer, rhs._variantBuffer) {
case (.native(let lhsNative), .native(let rhsNative)):
if lhsNative._storage === rhsNative._storage {
return true
}
if lhsNative.count != rhsNative.count {
return false
}
for (k, v) in lhs {
let (pos, found) = rhsNative._find(k, startBucket: rhsNative._bucket(k))
// FIXME: Can't write the simple code pending
// <rdar://problem/15484639> Refcounting bug
/*
if !found || rhs[pos].value != lhsElement.value {
return false
}
*/
if !found {
return false
}
if rhsNative.value(at: pos.offset) != v {
return false
}
}
return true
#if _runtime(_ObjC)
case (.cocoa(let lhsCocoa), .cocoa(let rhsCocoa)):
return _stdlib_NSObject_isEqual(
lhsCocoa.cocoaDictionary, rhsCocoa.cocoaDictionary)
case (.native(let lhsNative), .cocoa(let rhsCocoa)):
if lhsNative.count != rhsCocoa.count {
return false
}
let endIndex = lhsNative.endIndex
var index = lhsNative.startIndex
while index != endIndex {
let (key, value) = lhsNative.assertingGet(index)
let optRhsValue: AnyObject? =
rhsCocoa.maybeGet(_bridgeAnythingToObjectiveC(key))
guard let rhsValue = optRhsValue,
value == _forceBridgeFromObjectiveC(rhsValue, Value.self)
else {
return false
}
lhsNative.formIndex(after: &index)
continue
}
return true
case (.cocoa, .native):
return rhs == lhs
#endif
}
}
@inlinable // FIXME(sil-serialize-all)
public static func != (lhs: [Key: Value], rhs: [Key: Value]) -> Bool {
return !(lhs == rhs)
}
}
extension Dictionary: Hashable where Value: Hashable {
/// Hashes the essential components of this value by feeding them into the
/// given hasher.
///
/// - Parameter hasher: The hasher to use when combining the components
/// of this instance.
@inlinable
public func hash(into hasher: inout Hasher) {
var commutativeHash = 0
for (k, v) in self {
// Note that we use a copy of our own hasher here. This makes hash values
// dependent on its state, eliminating static collision patterns.
var elementHasher = hasher
elementHasher.combine(k)
elementHasher.combine(v)
commutativeHash ^= elementHasher._finalize()
}
hasher.combine(commutativeHash)
}
}
extension Dictionary: CustomStringConvertible, CustomDebugStringConvertible {
@inlinable // FIXME(sil-serialize-all)
internal func _makeDescription() -> String {
if count == 0 {
return "[:]"
}
var result = "["
var first = true
for (k, v) in self {
if first {
first = false
} else {
result += ", "
}
debugPrint(k, terminator: "", to: &result)
result += ": "
debugPrint(v, terminator: "", to: &result)
}
result += "]"
return result
}
/// A string that represents the contents of the dictionary.
@inlinable // FIXME(sil-serialize-all)
public var description: String {
return _makeDescription()
}
/// A string that represents the contents of the dictionary, suitable for
/// debugging.
@inlinable // FIXME(sil-serialize-all)
public var debugDescription: String {
return _makeDescription()
}
}
@usableFromInline // FIXME(sil-serialize-all)
@_frozen // FIXME(sil-serialize-all)
internal enum _MergeError: Error {
case keyCollision
}
#if _runtime(_ObjC)
/// Equivalent to `NSDictionary.allKeys`, but does not leave objects on the
/// autorelease pool.
@inlinable // FIXME(sil-serialize-all)
internal func _stdlib_NSDictionary_allKeys(_ nsd: _NSDictionary)
-> _HeapBuffer<Int, AnyObject> {
let count = nsd.count
let storage = _HeapBuffer<Int, AnyObject>(
_HeapBufferStorage<Int, AnyObject>.self, count, count)
nsd.getObjects(nil, andKeys: storage.baseAddress)
return storage
}
#endif
//===--- Compiler conversion/casting entry points for Dictionary<K, V> ----===//
/// Perform a non-bridged upcast that always succeeds.
///
/// - Precondition: `BaseKey` and `BaseValue` are base classes or base `@objc`
/// protocols (such as `AnyObject`) of `DerivedKey` and `DerivedValue`,
/// respectively.
@inlinable // FIXME(sil-serialize-all)
public func _dictionaryUpCast<DerivedKey, DerivedValue, BaseKey, BaseValue>(
_ source: Dictionary<DerivedKey, DerivedValue>
) -> Dictionary<BaseKey, BaseValue> {
var result = Dictionary<BaseKey, BaseValue>(minimumCapacity: source.count)
for (k, v) in source {
result[k as! BaseKey] = (v as! BaseValue)
}
return result
}
#if _runtime(_ObjC)
/// Implements an unconditional upcast that involves bridging.
///
/// The cast can fail if bridging fails.
///
/// - Precondition: `SwiftKey` and `SwiftValue` are bridged to Objective-C,
/// and at least one of them requires non-trivial bridging.
@inline(never)
public func _dictionaryBridgeToObjectiveC<
SwiftKey, SwiftValue, ObjCKey, ObjCValue
>(
_ source: Dictionary<SwiftKey, SwiftValue>
) -> Dictionary<ObjCKey, ObjCValue> {
// Note: We force this function to stay in the swift dylib because
// it is not performance sensitive and keeping it in the dylib saves
// a new kilobytes for each specialization for all users of dictionary.
_sanityCheck(
!_isBridgedVerbatimToObjectiveC(SwiftKey.self) ||
!_isBridgedVerbatimToObjectiveC(SwiftValue.self))
_sanityCheck(
_isClassOrObjCExistential(ObjCKey.self) ||
_isClassOrObjCExistential(ObjCValue.self))
var result = Dictionary<ObjCKey, ObjCValue>(minimumCapacity: source.count)
let keyBridgesDirectly =
_isBridgedVerbatimToObjectiveC(SwiftKey.self) ==
_isBridgedVerbatimToObjectiveC(ObjCKey.self)
let valueBridgesDirectly =
_isBridgedVerbatimToObjectiveC(SwiftValue.self) ==
_isBridgedVerbatimToObjectiveC(ObjCValue.self)
for (key, value) in source {
// Bridge the key
var bridgedKey: ObjCKey
if keyBridgesDirectly {
bridgedKey = unsafeBitCast(key, to: ObjCKey.self)
} else {
let bridged: AnyObject = _bridgeAnythingToObjectiveC(key)
bridgedKey = unsafeBitCast(bridged, to: ObjCKey.self)
}
// Bridge the value
var bridgedValue: ObjCValue
if valueBridgesDirectly {
bridgedValue = unsafeBitCast(value, to: ObjCValue.self)
} else {
let bridged: AnyObject? = _bridgeAnythingToObjectiveC(value)
bridgedValue = unsafeBitCast(bridged, to: ObjCValue.self)
}
result[bridgedKey] = bridgedValue
}
return result
}
#endif
/// Called by the casting machinery.
@_silgen_name("_swift_dictionaryDownCastIndirect")
internal func _dictionaryDownCastIndirect<SourceKey, SourceValue,
TargetKey, TargetValue>(
_ source: UnsafePointer<Dictionary<SourceKey, SourceValue>>,
_ target: UnsafeMutablePointer<Dictionary<TargetKey, TargetValue>>) {
target.initialize(to: _dictionaryDownCast(source.pointee))
}
/// Implements a forced downcast. This operation should have O(1) complexity.
///
/// The cast can fail if bridging fails. The actual checks and bridging can be
/// deferred.
///
/// - Precondition: `DerivedKey` is a subtype of `BaseKey`, `DerivedValue` is
/// a subtype of `BaseValue`, and all of these types are reference types.
@inlinable // FIXME(sil-serialize-all)
public func _dictionaryDownCast<BaseKey, BaseValue, DerivedKey, DerivedValue>(
_ source: Dictionary<BaseKey, BaseValue>
) -> Dictionary<DerivedKey, DerivedValue> {
#if _runtime(_ObjC)
if _isClassOrObjCExistential(BaseKey.self)
&& _isClassOrObjCExistential(BaseValue.self)
&& _isClassOrObjCExistential(DerivedKey.self)
&& _isClassOrObjCExistential(DerivedValue.self) {
switch source._variantBuffer {
case .native(let buffer):
// Note: it is safe to treat the buffer as immutable here because
// Dictionary will not mutate buffer with reference count greater than 1.
return Dictionary(_immutableCocoaDictionary: buffer.bridged())
case .cocoa(let cocoaBuffer):
return Dictionary(_immutableCocoaDictionary: cocoaBuffer.cocoaDictionary)
}
}
#endif
return _dictionaryDownCastConditional(source)!
}
/// Called by the casting machinery.
@_silgen_name("_swift_dictionaryDownCastConditionalIndirect")
internal func _dictionaryDownCastConditionalIndirect<SourceKey, SourceValue,
TargetKey, TargetValue>(
_ source: UnsafePointer<Dictionary<SourceKey, SourceValue>>,
_ target: UnsafeMutablePointer<Dictionary<TargetKey, TargetValue>>
) -> Bool {
if let result: Dictionary<TargetKey, TargetValue>
= _dictionaryDownCastConditional(source.pointee) {
target.initialize(to: result)
return true
}
return false
}
/// Implements a conditional downcast.
///
/// If the cast fails, the function returns `nil`. All checks should be
/// performed eagerly.
///
/// - Precondition: `DerivedKey` is a subtype of `BaseKey`, `DerivedValue` is
/// a subtype of `BaseValue`, and all of these types are reference types.
@inlinable // FIXME(sil-serialize-all)
public func _dictionaryDownCastConditional<
BaseKey, BaseValue, DerivedKey, DerivedValue
>(
_ source: Dictionary<BaseKey, BaseValue>
) -> Dictionary<DerivedKey, DerivedValue>? {
var result = Dictionary<DerivedKey, DerivedValue>()
for (k, v) in source {
guard let k1 = k as? DerivedKey, let v1 = v as? DerivedValue
else { return nil }
result[k1] = v1
}
return result
}
#if _runtime(_ObjC)
/// Implements an unconditional downcast that involves bridging.
///
/// - Precondition: At least one of `SwiftKey` or `SwiftValue` is a bridged value
/// type, and the corresponding `ObjCKey` or `ObjCValue` is a reference type.
@inlinable // FIXME(sil-serialize-all)
public func _dictionaryBridgeFromObjectiveC<
ObjCKey, ObjCValue, SwiftKey, SwiftValue
>(
_ source: Dictionary<ObjCKey, ObjCValue>
) -> Dictionary<SwiftKey, SwiftValue> {
let result: Dictionary<SwiftKey, SwiftValue>? =
_dictionaryBridgeFromObjectiveCConditional(source)
_precondition(result != nil, "Dictionary cannot be bridged from Objective-C")
return result!
}
/// Implements a conditional downcast that involves bridging.
///
/// If the cast fails, the function returns `nil`. All checks should be
/// performed eagerly.
///
/// - Precondition: At least one of `SwiftKey` or `SwiftValue` is a bridged value
/// type, and the corresponding `ObjCKey` or `ObjCValue` is a reference type.
@inlinable // FIXME(sil-serialize-all)
public func _dictionaryBridgeFromObjectiveCConditional<
ObjCKey, ObjCValue, SwiftKey, SwiftValue
>(
_ source: Dictionary<ObjCKey, ObjCValue>
) -> Dictionary<SwiftKey, SwiftValue>? {
_sanityCheck(
_isClassOrObjCExistential(ObjCKey.self) ||
_isClassOrObjCExistential(ObjCValue.self))
_sanityCheck(
!_isBridgedVerbatimToObjectiveC(SwiftKey.self) ||
!_isBridgedVerbatimToObjectiveC(SwiftValue.self))
let keyBridgesDirectly =
_isBridgedVerbatimToObjectiveC(SwiftKey.self) ==
_isBridgedVerbatimToObjectiveC(ObjCKey.self)
let valueBridgesDirectly =
_isBridgedVerbatimToObjectiveC(SwiftValue.self) ==
_isBridgedVerbatimToObjectiveC(ObjCValue.self)
var result = Dictionary<SwiftKey, SwiftValue>(minimumCapacity: source.count)
for (key, value) in source {
// Downcast the key.
var resultKey: SwiftKey
if keyBridgesDirectly {
if let bridgedKey = key as? SwiftKey {
resultKey = bridgedKey
} else {
return nil
}
} else {
if let bridgedKey = _conditionallyBridgeFromObjectiveC(
_reinterpretCastToAnyObject(key), SwiftKey.self) {
resultKey = bridgedKey
} else {
return nil
}
}
// Downcast the value.
var resultValue: SwiftValue
if valueBridgesDirectly {
if let bridgedValue = value as? SwiftValue {
resultValue = bridgedValue
} else {
return nil
}
} else {
if let bridgedValue = _conditionallyBridgeFromObjectiveC(
_reinterpretCastToAnyObject(value), SwiftValue.self) {
resultValue = bridgedValue
} else {
return nil
}
}
result[resultKey] = resultValue
}
return result
}
#endif
//===--- APIs templated for Dictionary and Set ----------------------------===//
/// An instance of this class has all `Dictionary` data tail-allocated.
/// Enough bytes are allocated to hold the bitmap for marking valid entries,
/// keys, and values. The data layout starts with the bitmap, followed by the
/// keys, followed by the values.
//
// See the docs at the top of the file for more details on this type
//
// NOTE: The precise layout of this type is relied on in the runtime
// to provide a statically allocated empty singleton.
// See stdlib/public/stubs/GlobalObjects.cpp for details.
@_fixed_layout // FIXME(sil-serialize-all)
@usableFromInline // FIXME(sil-serialize-all)
@_objc_non_lazy_realization
internal class _RawNativeDictionaryStorage
: _SwiftNativeNSDictionary, _NSDictionaryCore
{
internal typealias RawStorage = _RawNativeDictionaryStorage
@usableFromInline // FIXME(sil-serialize-all)
@nonobjc
internal final var bucketCount: Int
@usableFromInline // FIXME(sil-serialize-all)
internal final var count: Int
@usableFromInline // FIXME(sil-serialize-all)
internal final var initializedEntries: _UnsafeBitMap
@usableFromInline // FIXME(sil-serialize-all)
@nonobjc
internal final var keys: UnsafeMutableRawPointer
@usableFromInline // FIXME(sil-serialize-all)
@nonobjc
internal final var values: UnsafeMutableRawPointer
@usableFromInline // FIXME(sil-serialize-all)
internal final var seed: (UInt64, UInt64)
// This API is unsafe and needs a `_fixLifetime` in the caller.
@inlinable // FIXME(sil-serialize-all)
@nonobjc
internal final
var _initializedHashtableEntriesBitMapBuffer: UnsafeMutablePointer<UInt> {
return UnsafeMutablePointer(Builtin.projectTailElems(self, UInt.self))
}
/// The empty singleton that is used for every single Dictionary that is
/// created without any elements. The contents of the storage should never
/// be mutated.
@inlinable // FIXME(sil-serialize-all)
@nonobjc
internal static var empty: RawStorage {
return Builtin.bridgeFromRawPointer(
Builtin.addressof(&_swiftEmptyDictionaryStorage))
}
// This type is made with allocWithTailElems, so no init is ever called.
// But we still need to have an init to satisfy the compiler.
@inlinable // FIXME(sil-serialize-all)
@nonobjc
internal init(_doNotCallMe: ()) {
_sanityCheckFailure("Only create this by using the `empty` singleton")
}
#if _runtime(_ObjC)
//
// NSDictionary implementation, assuming Self is the empty singleton
//
/// Get the NSEnumerator implementation for self.
/// _HashableTypedNativeDictionaryStorage overloads this to give
/// _NativeSelfNSEnumerator proper type parameters.
@inlinable // FIXME(sil-serialize-all)
@objc
internal func enumerator() -> _NSEnumerator {
return _NativeDictionaryNSEnumerator<AnyObject, AnyObject>(
_NativeDictionaryBuffer(_storage: self))
}
@inlinable // FIXME(sil-serialize-all)
@objc(copyWithZone:)
internal func copy(with zone: _SwiftNSZone?) -> AnyObject {
return self
}
@inlinable // FIXME(sil-serialize-all)
@objc(countByEnumeratingWithState:objects:count:)
internal func countByEnumerating(
with state: UnsafeMutablePointer<_SwiftNSFastEnumerationState>,
objects: UnsafeMutablePointer<AnyObject>?, count: Int
) -> Int {
// Even though we never do anything in here, we need to update the
// state so that callers know we actually ran.
var theState = state.pointee
if theState.state == 0 {
theState.state = 1 // Arbitrary non-zero value.
theState.itemsPtr = AutoreleasingUnsafeMutablePointer(objects)
theState.mutationsPtr = _fastEnumerationStorageMutationsPtr
}
state.pointee = theState
return 0
}
@inlinable // FIXME(sil-serialize-all)
@objc
internal required init(
objects: UnsafePointer<AnyObject?>,
forKeys: UnsafeRawPointer,
count: Int
) {
_sanityCheckFailure("don't call this designated initializer")
}
@inlinable // FIXME(sil-serialize-all)
@objc(objectForKey:)
internal func objectFor(_ aKey: AnyObject) -> AnyObject? {
return nil
}
@inlinable // FIXME(sil-serialize-all)
internal func keyEnumerator() -> _NSEnumerator {
return enumerator()
}
@inlinable // FIXME(sil-serialize-all)
internal func getObjects(_ objects: UnsafeMutablePointer<AnyObject>?,
andKeys keys: UnsafeMutablePointer<AnyObject>?) {
// Do nothing, we're empty
}
#endif
}
// See the docs at the top of this file for a description of this type
@_fixed_layout // FIXME(sil-serialize-all)
@usableFromInline
internal class _TypedNativeDictionaryStorage<Key, Value>
: _RawNativeDictionaryStorage {
deinit {
let keys = self.keys.assumingMemoryBound(to: Key.self)
let values = self.values.assumingMemoryBound(to: Value.self)
if !_isPOD(Key.self) {
for i in 0 ..< bucketCount {
if initializedEntries[i] {
(keys+i).deinitialize(count: 1)
}
}
}
if !_isPOD(Value.self) {
for i in 0 ..< bucketCount {
if initializedEntries[i] {
(values+i).deinitialize(count: 1)
}
}
}
_fixLifetime(self)
}
// This type is made with allocWithTailElems, so no init is ever called.
// But we still need to have an init to satisfy the compiler.
@inlinable // FIXME(sil-serialize-all)
@nonobjc
override internal init(_doNotCallMe: ()) {
_sanityCheckFailure("Only create this by calling Buffer's inits")
}
#if _runtime(_ObjC)
@inlinable // FIXME(sil-serialize-all)
@objc
internal required init(
objects: UnsafePointer<AnyObject?>,
forKeys: UnsafeRawPointer,
count: Int
) {
_sanityCheckFailure("don't call this designated initializer")
}
#endif
}
// See the docs at the top of this file for a description of this type
@_fixed_layout // FIXME(sil-serialize-all)
@usableFromInline
final internal class _HashableTypedNativeDictionaryStorage<Key: Hashable, Value>
: _TypedNativeDictionaryStorage<Key, Value> {
internal typealias FullContainer = Dictionary<Key, Value>
internal typealias Buffer = _NativeDictionaryBuffer<Key, Value>
// This type is made with allocWithTailElems, so no init is ever called.
// But we still need to have an init to satisfy the compiler.
@inlinable // FIXME(sil-serialize-all)
@nonobjc
override internal init(_doNotCallMe: ()) {
_sanityCheckFailure("Only create this by calling Buffer's inits'")
}
#if _runtime(_ObjC)
// NSDictionary bridging:
// All actual functionality comes from buffer/full, which are
// just wrappers around a RawNativeDictionaryStorage.
@inlinable // FIXME(sil-serialize-all)
internal var buffer: Buffer {
return Buffer(_storage: self)
}
@inlinable // FIXME(sil-serialize-all)
internal var full: FullContainer {
return FullContainer(_nativeBuffer: buffer)
}
@inlinable // FIXME(sil-serialize-all)
internal override func enumerator() -> _NSEnumerator {
return _NativeDictionaryNSEnumerator<Key, Value>(
Buffer(_storage: self))
}
@inlinable // FIXME(sil-serialize-all)
@objc(countByEnumeratingWithState:objects:count:)
internal override func countByEnumerating(
with state: UnsafeMutablePointer<_SwiftNSFastEnumerationState>,
objects: UnsafeMutablePointer<AnyObject>?, count: Int
) -> Int {
var theState = state.pointee
if theState.state == 0 {
theState.state = 1 // Arbitrary non-zero value.
theState.itemsPtr = AutoreleasingUnsafeMutablePointer(objects)
theState.mutationsPtr = _fastEnumerationStorageMutationsPtr
theState.extra.0 = CUnsignedLong(full.startIndex._nativeIndex.offset)
}
// Test 'objects' rather than 'count' because (a) this is very rare anyway,
// and (b) the optimizer should then be able to optimize away the
// unwrapping check below.
if _slowPath(objects == nil) {
return 0
}
let unmanagedObjects = _UnmanagedAnyObjectArray(objects!)
var currIndex = _NativeDictionaryIndex<Key, Value>(
offset: Int(theState.extra.0))
let endIndex = buffer.endIndex
var stored = 0
for i in 0..<count {
if (currIndex == endIndex) {
break
}
unmanagedObjects[i] = buffer.bridgedKey(at: currIndex)
stored += 1
buffer.formIndex(after: &currIndex)
}
theState.extra.0 = CUnsignedLong(currIndex.offset)
state.pointee = theState
return stored
}
@inlinable // FIXME(sil-serialize-all)
@nonobjc
internal func getObjectFor(_ aKey: AnyObject) -> AnyObject? {
guard let nativeKey = _conditionallyBridgeFromObjectiveC(aKey, Key.self)
else { return nil }
let (i, found) = buffer._find(nativeKey,
startBucket: buffer._bucket(nativeKey))
if found {
return buffer.bridgedValue(at: i)
}
return nil
}
@inlinable // FIXME(sil-serialize-all)
@objc
internal required init(
objects: UnsafePointer<AnyObject?>,
forKeys: UnsafeRawPointer,
count: Int
) {
_sanityCheckFailure("don't call this designated initializer")
}
@inlinable // FIXME(sil-serialize-all)
@objc(objectForKey:)
override func objectFor(_ aKey: AnyObject) -> AnyObject? {
return getObjectFor(aKey)
}
// We also override the following methods for efficiency.
@inlinable // FIXME(sil-serialize-all)
@objc
override func getObjects(_ objects: UnsafeMutablePointer<AnyObject>?,
andKeys keys: UnsafeMutablePointer<AnyObject>?) {
// The user is expected to provide a storage of the correct size
if let unmanagedKeys = _UnmanagedAnyObjectArray(keys) {
if let unmanagedObjects = _UnmanagedAnyObjectArray(objects) {
// keys nonnull, objects nonnull
for (offset: i, element: (key: key, value: val)) in full.enumerated() {
unmanagedObjects[i] = _bridgeAnythingToObjectiveC(val)
unmanagedKeys[i] = _bridgeAnythingToObjectiveC(key)
}
} else {
// keys nonnull, objects null
for (offset: i, element: (key: key, value: _)) in full.enumerated() {
unmanagedKeys[i] = _bridgeAnythingToObjectiveC(key)
}
}
} else {
if let unmanagedObjects = _UnmanagedAnyObjectArray(objects) {
// keys null, objects nonnull
for (offset: i, element: (key: _, value: val)) in full.enumerated() {
unmanagedObjects[i] = _bridgeAnythingToObjectiveC(val)
}
} else {
// do nothing, both are null
}
}
}
#endif
}
/// A wrapper around _RawNativeDictionaryStorage that provides most of the
/// implementation of Dictionary.
///
/// This type and most of its functionality doesn't require Hashable at all.
/// The reason for this is to support storing AnyObject for bridging
/// with _SwiftDeferredNSDictionary. What functionality actually relies on
/// Hashable can be found in an extension.
@usableFromInline
@_fixed_layout
internal struct _NativeDictionaryBuffer<Key, Value> {
internal typealias RawStorage = _RawNativeDictionaryStorage
internal typealias TypedStorage = _TypedNativeDictionaryStorage<Key, Value>
internal typealias Buffer = _NativeDictionaryBuffer<Key, Value>
internal typealias Index = _NativeDictionaryIndex<Key, Value>
internal typealias SequenceElementWithoutLabels = (Key, Value)
/// See this comments on _RawNativeDictionaryStorage and its subclasses to
/// understand why we store an untyped storage here.
@usableFromInline // FIXME(sil-serialize-all)
internal var _storage: RawStorage
/// Creates a Buffer with a storage that is typed, but doesn't understand
/// Hashing. Mostly for bridging; prefer `init(minimumCapacity:)`.
@inlinable // FIXME(sil-serialize-all)
internal init(_exactBucketCount bucketCount: Int, unhashable: ()) {
let bitmapWordCount = _UnsafeBitMap.sizeInWords(forSizeInBits: bucketCount)
let storage = Builtin.allocWithTailElems_3(TypedStorage.self,
bitmapWordCount._builtinWordValue, UInt.self,
bucketCount._builtinWordValue, Key.self,
bucketCount._builtinWordValue, Value.self)
self.init(_exactBucketCount: bucketCount, storage: storage)
}
/// Given a bucket count and uninitialized RawStorage, completes the
/// initialization and returns a Buffer.
@inlinable // FIXME(sil-serialize-all)
internal init(_exactBucketCount bucketCount: Int, storage: RawStorage) {
storage.bucketCount = bucketCount
storage.count = 0
self.init(_storage: storage)
let initializedEntries = _UnsafeBitMap(
storage: _initializedHashtableEntriesBitMapBuffer,
bitCount: bucketCount)
initializedEntries.initializeToZero()
// Compute all the array offsets now, so we don't have to later
let bitmapAddr = Builtin.projectTailElems(_storage, UInt.self)
let bitmapWordCount = _UnsafeBitMap.sizeInWords(forSizeInBits: bucketCount)
let keysAddr = Builtin.getTailAddr_Word(bitmapAddr,
bitmapWordCount._builtinWordValue, UInt.self, Key.self)
// Initialize header
_storage.initializedEntries = initializedEntries
_storage.keys = UnsafeMutableRawPointer(keysAddr)
let valuesAddr = Builtin.getTailAddr_Word(keysAddr,
bucketCount._builtinWordValue, Key.self, Value.self)
_storage.values = UnsafeMutableRawPointer(valuesAddr)
// We assign a unique hash seed to each distinct hash table size, so that we
// avoid certain copy operations becoming quadratic, without breaking value
// semantics. (See https://bugs.swift.org/browse/SR-3268)
//
// We don't need to generate a brand new seed for each table size: it's
// enough to change a single bit in the global seed by XORing the bucket
// count to it. (The bucket count is always a power of two.)
//
// FIXME: Use an approximation of true per-instance seeding. We can't just
// use the base address, because COW copies need to share the same seed.
let seed = Hasher._seed
let perturbation = bucketCount
_storage.seed = (seed.0 ^ UInt64(truncatingIfNeeded: perturbation), seed.1)
}
// Forwarding the individual fields of the storage in various forms
@inlinable // FIXME(sil-serialize-all)
internal var bucketCount: Int {
return _assumeNonNegative(_storage.bucketCount)
}
@inlinable // FIXME(sil-serialize-all)
internal var count: Int {
set {
_storage.count = newValue
}
get {
return _assumeNonNegative(_storage.count)
}
}
@inlinable // FIXME(sil-serialize-all)
internal
var _initializedHashtableEntriesBitMapBuffer: UnsafeMutablePointer<UInt> {
return _storage._initializedHashtableEntriesBitMapBuffer
}
// This API is unsafe and needs a `_fixLifetime` in the caller.
@inlinable // FIXME(sil-serialize-all)
internal var keys: UnsafeMutablePointer<Key> {
return _storage.keys.assumingMemoryBound(to: Key.self)
}
// This API is unsafe and needs a `_fixLifetime` in the caller.
@inlinable // FIXME(sil-serialize-all)
internal var values: UnsafeMutablePointer<Value> {
return _storage.values.assumingMemoryBound(to: Value.self)
}
/// Constructs a buffer adopting the given storage.
@inlinable // FIXME(sil-serialize-all)
internal init(_storage: RawStorage) {
self._storage = _storage
}
/// Constructs an instance from the empty singleton.
@inlinable // FIXME(sil-serialize-all)
internal init() {
self._storage = RawStorage.empty
}
// Most of the implementation of the _HashBuffer protocol,
// but only the parts that don't actually rely on hashing.
@inlinable // FIXME(sil-serialize-all)
@inline(__always)
internal func key(at i: Int) -> Key {
_sanityCheck(i >= 0 && i < bucketCount)
_sanityCheck(isInitializedEntry(at: i))
defer { _fixLifetime(self) }
let res = (keys + i).pointee
return res
}
#if _runtime(_ObjC)
/// Returns the key at the given Index, bridged.
///
/// Intended for use with verbatim bridgeable keys.
@inlinable // FIXME(sil-serialize-all)
internal func bridgedKey(at index: Index) -> AnyObject {
let k = key(at: index.offset)
return _bridgeAnythingToObjectiveC(k)
}
/// Returns the value at the given Index, bridged.
///
/// Intended for use with verbatim bridgeable keys.
@inlinable // FIXME(sil-serialize-all)
internal func bridgedValue(at index: Index) -> AnyObject {
let v = value(at: index.offset)
return _bridgeAnythingToObjectiveC(v)
}
#endif
@inlinable // FIXME(sil-serialize-all)
internal func isInitializedEntry(at i: Int) -> Bool {
_sanityCheck(i >= 0 && i < bucketCount)
defer { _fixLifetime(self) }
return _storage.initializedEntries[i]
}
@inlinable // FIXME(sil-serialize-all)
@_transparent
internal func destroyEntry(at i: Int) {
_sanityCheck(isInitializedEntry(at: i))
defer { _fixLifetime(self) }
(keys + i).deinitialize(count: 1)
(values + i).deinitialize(count: 1)
_storage.initializedEntries[i] = false
}
@inlinable // FIXME(sil-serialize-all)
@_transparent
internal func initializeKey(_ k: Key, value v: Value, at i: Int) {
_sanityCheck(!isInitializedEntry(at: i))
defer { _fixLifetime(self) }
(keys + i).initialize(to: k)
(values + i).initialize(to: v)
_storage.initializedEntries[i] = true
}
@inlinable // FIXME(sil-serialize-all)
@_transparent
internal func moveInitializeEntry(from: Buffer, at: Int, toEntryAt: Int) {
_sanityCheck(!isInitializedEntry(at: toEntryAt))
defer { _fixLifetime(self) }
(keys + toEntryAt).initialize(to: (from.keys + at).move())
(values + toEntryAt).initialize(to: (from.values + at).move())
from._storage.initializedEntries[at] = false
_storage.initializedEntries[toEntryAt] = true
}
@inlinable // FIXME(sil-serialize-all)
@_transparent
internal func value(at i: Int) -> Value {
_sanityCheck(isInitializedEntry(at: i))
defer { _fixLifetime(self) }
return (values + i).pointee
}
@inlinable // FIXME(sil-serialize-all)
@_transparent
internal func setKey(_ key: Key, value: Value, at i: Int) {
_sanityCheck(isInitializedEntry(at: i))
defer { _fixLifetime(self) }
(keys + i).pointee = key
(values + i).pointee = value
}
@inlinable // FIXME(sil-serialize-all)
internal var startIndex: Index {
// We start at "index after -1" instead of "0" because we need to find the
// first occupied slot.
return index(after: Index(offset: -1))
}
@inlinable // FIXME(sil-serialize-all)
internal var endIndex: Index {
return Index(offset: bucketCount)
}
@inlinable // FIXME(sil-serialize-all)
internal func index(after i: Index) -> Index {
_precondition(i != endIndex)
var idx = i.offset + 1
while idx < bucketCount && !isInitializedEntry(at: idx) {
idx += 1
}
return Index(offset: idx)
}
@inlinable // FIXME(sil-serialize-all)
internal func formIndex(after i: inout Index) {
i = index(after: i)
}
@inlinable // FIXME(sil-serialize-all)
internal func assertingGet(_ i: Index) -> SequenceElement {
_precondition(i.offset >= 0 && i.offset < bucketCount)
_precondition(
isInitializedEntry(at: i.offset),
"Attempting to access Dictionary elements using an invalid Index")
let key = self.key(at: i.offset)
return (key, self.value(at: i.offset))
}
}
extension _NativeDictionaryBuffer where Key: Hashable
{
internal typealias HashTypedStorage =
_HashableTypedNativeDictionaryStorage<Key, Value>
internal typealias SequenceElement = (key: Key, value: Value)
@inlinable // FIXME(sil-serialize-all)
@inline(__always)
internal init(minimumCapacity: Int) {
let bucketCount = _NativeDictionaryBuffer.bucketCount(
forCapacity: minimumCapacity,
maxLoadFactorInverse: _hashContainerDefaultMaxLoadFactorInverse)
self.init(bucketCount: bucketCount)
}
@inlinable // FIXME(sil-serialize-all)
@inline(__always)
internal init(bucketCount: Int) {
// Actual bucket count is the next power of 2 greater than or equal to
// bucketCount. Make sure that is representable.
_sanityCheck(bucketCount <= (Int.max >> 1) + 1)
let buckets = 1 &<< ((Swift.max(bucketCount, 2) - 1)._binaryLogarithm() + 1)
self.init(_exactBucketCount: buckets)
}
/// Create a buffer instance with room for at least 'bucketCount' entries,
/// marking all entries invalid.
@inlinable // FIXME(sil-serialize-all)
internal init(_exactBucketCount bucketCount: Int) {
let bitmapWordCount = _UnsafeBitMap.sizeInWords(forSizeInBits: bucketCount)
let storage = Builtin.allocWithTailElems_3(HashTypedStorage.self,
bitmapWordCount._builtinWordValue, UInt.self,
bucketCount._builtinWordValue, Key.self,
bucketCount._builtinWordValue, Value.self)
self.init(_exactBucketCount: bucketCount, storage: storage)
}
#if _runtime(_ObjC)
@inlinable // FIXME(sil-serialize-all)
internal func bridged() -> _NSDictionary {
// We can zero-cost bridge if our keys are verbatim
// or if we're the empty singleton.
// Temporary var for SOME type safety before a cast.
let nsSet: _NSDictionaryCore
if (_isBridgedVerbatimToObjectiveC(Key.self) &&
_isBridgedVerbatimToObjectiveC(Value.self)) ||
self._storage === RawStorage.empty {
nsSet = self._storage
} else {
nsSet = _SwiftDeferredNSDictionary(nativeBuffer: self)
}
// Cast from "minimal NSDictionary" to "NSDictionary"
// Note that if you actually ask Swift for this cast, it will fail.
// Never trust a shadow protocol!
return unsafeBitCast(nsSet, to: _NSDictionary.self)
}
#endif
/// A textual representation of `self`.
@inlinable // FIXME(sil-serialize-all)
internal var description: String {
var result = ""
#if INTERNAL_CHECKS_ENABLED
for i in 0..<bucketCount {
if isInitializedEntry(at: i) {
let key = self.key(at: i)
result += "bucket \(i), ideal bucket = \(_bucket(key)), key = \(key)\n"
} else {
result += "bucket \(i), empty\n"
}
}
#endif
return result
}
@inlinable // FIXME(sil-serialize-all)
internal var _bucketMask: Int {
// The bucket count is not negative, therefore subtracting 1 will not
// overflow.
return bucketCount &- 1
}
@inlinable // FIXME(sil-serialize-all)
@inline(__always) // For performance reasons.
internal func _bucket(_ k: Key) -> Int {
return k._rawHashValue(seed: _storage.seed) & _bucketMask
}
@inlinable // FIXME(sil-serialize-all)
internal func _index(after bucket: Int) -> Int {
// Bucket is within 0 and bucketCount. Therefore adding 1 does not overflow.
return (bucket &+ 1) & _bucketMask
}
@inlinable // FIXME(sil-serialize-all)
internal func _prev(_ bucket: Int) -> Int {
// Bucket is not negative. Therefore subtracting 1 does not overflow.
return (bucket &- 1) & _bucketMask
}
/// Search for a given key starting from the specified bucket.
///
/// If the key is not present, returns the position where it could be
/// inserted.
@inlinable // FIXME(sil-serialize-all)
@inline(__always)
internal func _find(_ key: Key, startBucket: Int)
-> (pos: Index, found: Bool) {
var bucket = startBucket
// The invariant guarantees there's always a hole, so we just loop
// until we find one
while true {
let isHole = !isInitializedEntry(at: bucket)
if isHole {
return (Index(offset: bucket), false)
}
if self.key(at: bucket) == key {
return (Index(offset: bucket), true)
}
bucket = _index(after: bucket)
}
}
@inlinable // FIXME(sil-serialize-all)
@_transparent
internal static func bucketCount(
forCapacity capacity: Int,
maxLoadFactorInverse: Double
) -> Int {
// `capacity + 1` below ensures that we don't fill in the last hole
return max(Int((Double(capacity) * maxLoadFactorInverse).rounded(.up)),
capacity + 1)
}
/// Buffer should be uniquely referenced.
/// The `key` should not be present in the Dictionary.
/// This function does *not* update `count`.
@inlinable // FIXME(sil-serialize-all)
internal func unsafeAddNew(key newKey: Key, value: Value) {
let (i, found) = _find(newKey, startBucket: _bucket(newKey))
_precondition(
!found, "Duplicate key found in Dictionary. Keys may have been mutated after insertion")
initializeKey(newKey, value: value, at: i.offset)
}
//
// _HashBuffer conformance
//
@inlinable // FIXME(sil-serialize-all)
@inline(__always)
internal func index(forKey key: Key) -> Index? {
if count == 0 {
// Fast path that avoids computing the hash of the key.
return nil
}
let (i, found) = _find(key, startBucket: _bucket(key))
return found ? i : nil
}
@inlinable // FIXME(sil-serialize-all)
internal func assertingGet(_ key: Key) -> Value {
let (i, found) = _find(key, startBucket: _bucket(key))
_precondition(found, "Key not found")
return self.value(at: i.offset)
}
@inlinable // FIXME(sil-serialize-all)
@inline(__always)
internal func maybeGet(_ key: Key) -> Value? {
if count == 0 {
// Fast path that avoids computing the hash of the key.
return nil
}
let (i, found) = _find(key, startBucket: _bucket(key))
if found {
return self.value(at: i.offset)
}
return nil
}
@inlinable // FIXME(sil-serialize-all)
@discardableResult
internal func updateValue(_ value: Value, forKey key: Key) -> Value? {
_sanityCheckFailure(
"don't call mutating methods on _NativeDictionaryBuffer")
}
@inlinable // FIXME(sil-serialize-all)
@discardableResult
internal func insert(
_ value: Value, forKey key: Key
) -> (inserted: Bool, memberAfterInsert: Value) {
_sanityCheckFailure(
"don't call mutating methods on _NativeDictionaryBuffer")
}
@inlinable // FIXME(sil-serialize-all)
@discardableResult
internal func remove(at index: Index) -> SequenceElement {
_sanityCheckFailure(
"don't call mutating methods on _NativeDictionaryBuffer")
}
@inlinable // FIXME(sil-serialize-all)
@discardableResult
internal func removeValue(forKey key: Key) -> Value? {
_sanityCheckFailure(
"don't call mutating methods on _NativeDictionaryBuffer")
}
@inlinable // FIXME(sil-serialize-all)
internal func removeAll(keepingCapacity keepCapacity: Bool) {
_sanityCheckFailure(
"don't call mutating methods on _NativeDictionaryBuffer")
}
@inlinable // FIXME(sil-serialize-all)
internal static func fromArray(_ elements: [SequenceElementWithoutLabels])
-> Buffer
{
if elements.isEmpty {
return Buffer()
}
var nativeBuffer = Buffer(minimumCapacity: elements.count)
for (key, value) in elements {
let (i, found) =
nativeBuffer._find(key, startBucket: nativeBuffer._bucket(key))
_precondition(!found, "Dictionary literal contains duplicate keys")
nativeBuffer.initializeKey(key, value: value, at: i.offset)
}
nativeBuffer.count = elements.count
return nativeBuffer
}
}
#if _runtime(_ObjC)
/// An NSEnumerator that works with any NativeDictionaryBuffer of
/// verbatim bridgeable elements. Used by the various NSDictionary impls.
@_fixed_layout // FIXME(sil-serialize-all)
@usableFromInline // FIXME(sil-serialize-all)
final internal class _NativeDictionaryNSEnumerator<Key, Value>
: _SwiftNativeNSEnumerator, _NSEnumerator {
internal typealias Buffer = _NativeDictionaryBuffer<Key, Value>
internal typealias Index = _NativeDictionaryIndex<Key, Value>
@inlinable // FIXME(sil-serialize-all)
internal override required init() {
_sanityCheckFailure("don't call this designated initializer")
}
@inlinable // FIXME(sil-serialize-all)
internal init(_ buffer: Buffer) {
self.buffer = buffer
nextIndex = buffer.startIndex
endIndex = buffer.endIndex
}
@usableFromInline // FIXME(sil-serialize-all)
internal var buffer: Buffer
@usableFromInline // FIXME(sil-serialize-all)
internal var nextIndex: Index
@usableFromInline // FIXME(sil-serialize-all)
internal var endIndex: Index
//
// NSEnumerator implementation.
//
// Do not call any of these methods from the standard library!
//
@inlinable // FIXME(sil-serialize-all)
@objc
internal func nextObject() -> AnyObject? {
if nextIndex == endIndex {
return nil
}
let key = buffer.bridgedKey(at: nextIndex)
buffer.formIndex(after: &nextIndex)
return key
}
@inlinable // FIXME(sil-serialize-all)
@objc(countByEnumeratingWithState:objects:count:)
internal func countByEnumerating(
with state: UnsafeMutablePointer<_SwiftNSFastEnumerationState>,
objects: UnsafeMutablePointer<AnyObject>,
count: Int
) -> Int {
var theState = state.pointee
if theState.state == 0 {
theState.state = 1 // Arbitrary non-zero value.
theState.itemsPtr = AutoreleasingUnsafeMutablePointer(objects)
theState.mutationsPtr = _fastEnumerationStorageMutationsPtr
}
if nextIndex == endIndex {
state.pointee = theState
return 0
}
// Return only a single element so that code can start iterating via fast
// enumeration, terminate it, and continue via NSEnumerator.
let key = buffer.bridgedKey(at: nextIndex)
buffer.formIndex(after: &nextIndex)
let unmanagedObjects = _UnmanagedAnyObjectArray(objects)
unmanagedObjects[0] = key
state.pointee = theState
return 1
}
}
#endif
#if _runtime(_ObjC)
/// This class exists for Objective-C bridging. It holds a reference to a
/// NativeDictionaryBuffer, and can be upcast to NSSelf when bridging is necessary.
/// This is the fallback implementation for situations where toll-free bridging
/// isn't possible. On first access, a NativeDictionaryBuffer of AnyObject will be
/// constructed containing all the bridged elements.
@_fixed_layout // FIXME(sil-serialize-all)
@usableFromInline // FIXME(sil-serialize-all)
final internal class _SwiftDeferredNSDictionary<Key: Hashable, Value>
: _SwiftNativeNSDictionary, _NSDictionaryCore {
internal typealias NativeBuffer = _NativeDictionaryBuffer<Key, Value>
internal typealias BridgedBuffer = _NativeDictionaryBuffer<AnyObject, AnyObject>
internal typealias NativeIndex = _NativeDictionaryIndex<Key, Value>
internal typealias BridgedIndex = _NativeDictionaryIndex<AnyObject, AnyObject>
@inlinable // FIXME(sil-serialize-all)
@nonobjc
internal init(bucketCount: Int = 2) {
nativeBuffer = NativeBuffer(bucketCount: bucketCount)
super.init()
}
@inlinable // FIXME(sil-serialize-all)
internal init(nativeBuffer: NativeBuffer) {
self.nativeBuffer = nativeBuffer
super.init()
}
// This stored property should be stored at offset zero. We perform atomic
// operations on it.
//
// Do not access this property directly.
@usableFromInline // FIXME(sil-serialize-all)
@nonobjc
internal var _heapStorageBridged_DoNotUse: AnyObject?
/// The unbridged elements.
@usableFromInline // FIXME(sil-serialize-all)
internal var nativeBuffer: NativeBuffer
@inlinable // FIXME(sil-serialize-all)
@objc(copyWithZone:)
internal func copy(with zone: _SwiftNSZone?) -> AnyObject {
// Instances of this class should be visible outside of standard library as
// having `NSDictionary` type, which is immutable.
return self
}
//
// NSDictionary implementation.
//
// Do not call any of these methods from the standard library! Use only
// `nativeBuffer`.
//
@inlinable // FIXME(sil-serialize-all)
@objc
internal required init(
objects: UnsafePointer<AnyObject?>,
forKeys: UnsafeRawPointer,
count: Int
) {
_sanityCheckFailure("don't call this designated initializer")
}
@inlinable // FIXME(sil-serialize-all)
@objc(objectForKey:)
internal func objectFor(_ aKey: AnyObject) -> AnyObject? {
return bridgingObjectForKey(aKey)
}
@inlinable // FIXME(sil-serialize-all)
@objc
internal func keyEnumerator() -> _NSEnumerator {
return enumerator()
}
@inlinable // FIXME(sil-serialize-all)
@objc
internal func getObjects(
_ objects: UnsafeMutablePointer<AnyObject>?,
andKeys keys: UnsafeMutablePointer<AnyObject>?
) {
bridgedAllKeysAndValues(objects, keys)
}
@inlinable // FIXME(sil-serialize-all)
@objc(enumerateKeysAndObjectsWithOptions:usingBlock:)
internal func enumerateKeysAndObjects(options: Int,
using block: @convention(block) (Unmanaged<AnyObject>, Unmanaged<AnyObject>,
UnsafeMutablePointer<UInt8>) -> Void) {
bridgeEverything()
let bucketCount = nativeBuffer.bucketCount
var stop: UInt8 = 0
for position in 0..<bucketCount {
if bridgedBuffer.isInitializedEntry(at: position) {
block(Unmanaged.passUnretained(bridgedBuffer.key(at: position)),
Unmanaged.passUnretained(bridgedBuffer.value(at: position)),
&stop)
}
if stop != 0 { return }
}
}
/// Returns the pointer to the stored property, which contains bridged
/// Dictionary elements.
@inlinable // FIXME(sil-serialize-all)
@nonobjc
internal var _heapStorageBridgedPtr: UnsafeMutablePointer<AnyObject?> {
return _getUnsafePointerToStoredProperties(self).assumingMemoryBound(
to: Optional<AnyObject>.self)
}
/// The buffer for bridged Dictionary elements, if present.
@inlinable // FIXME(sil-serialize-all)
@nonobjc
internal var _bridgedStorage: BridgedBuffer.RawStorage? {
get {
if let ref = _stdlib_atomicLoadARCRef(object: _heapStorageBridgedPtr) {
return unsafeDowncast(ref, to: BridgedBuffer.RawStorage.self)
}
return nil
}
}
/// Attach a buffer for bridged Dictionary elements.
@inlinable // FIXME(sil-serialize-all)
@nonobjc
internal func _initializeHeapStorageBridged(_ newStorage: AnyObject) {
_stdlib_atomicInitializeARCRef(
object: _heapStorageBridgedPtr, desired: newStorage)
}
/// Returns the bridged Dictionary values.
@inlinable // FIXME(sil-serialize-all)
internal var bridgedBuffer: BridgedBuffer {
return BridgedBuffer(_storage: _bridgedStorage!)
}
@inlinable // FIXME(sil-serialize-all)
@nonobjc
internal func bridgeEverything() {
if _fastPath(_bridgedStorage != nil) {
return
}
// FIXME: rdar://problem/19486139 (split bridged buffers for keys and values)
// We bridge keys and values unconditionally here, even if one of them
// actually is verbatim bridgeable (e.g. Dictionary<Int, AnyObject>).
// Investigate only allocating the buffer for a Set in this case.
// Create buffer for bridged data.
let bridged = BridgedBuffer(
_exactBucketCount: nativeBuffer.bucketCount,
unhashable: ())
// Bridge everything.
for i in 0..<nativeBuffer.bucketCount {
if nativeBuffer.isInitializedEntry(at: i) {
let key = _bridgeAnythingToObjectiveC(nativeBuffer.key(at: i))
let val = _bridgeAnythingToObjectiveC(nativeBuffer.value(at: i))
bridged.initializeKey(key, value: val, at: i)
}
}
// Atomically put the bridged elements in place.
_initializeHeapStorageBridged(bridged._storage)
}
@inlinable // FIXME(sil-serialize-all)
@nonobjc
internal func bridgedAllKeysAndValues(
_ objects: UnsafeMutablePointer<AnyObject>?,
_ keys: UnsafeMutablePointer<AnyObject>?
) {
bridgeEverything()
// The user is expected to provide a storage of the correct size
var i = 0 // Position in the input storage
let bucketCount = nativeBuffer.bucketCount
if let unmanagedKeys = _UnmanagedAnyObjectArray(keys) {
if let unmanagedObjects = _UnmanagedAnyObjectArray(objects) {
// keys nonnull, objects nonnull
for position in 0..<bucketCount {
if bridgedBuffer.isInitializedEntry(at: position) {
unmanagedObjects[i] = bridgedBuffer.value(at: position)
unmanagedKeys[i] = bridgedBuffer.key(at: position)
i += 1
}
}
} else {
// keys nonnull, objects null
for position in 0..<bucketCount {
if bridgedBuffer.isInitializedEntry(at: position) {
unmanagedKeys[i] = bridgedBuffer.key(at: position)
i += 1
}
}
}
} else {
if let unmanagedObjects = _UnmanagedAnyObjectArray(objects) {
// keys null, objects nonnull
for position in 0..<bucketCount {
if bridgedBuffer.isInitializedEntry(at: position) {
unmanagedObjects[i] = bridgedBuffer.value(at: position)
i += 1
}
}
} else {
// do nothing, both are null
}
}
}
@inlinable // FIXME(sil-serialize-all)
@objc
internal var count: Int {
return nativeBuffer.count
}
@inlinable // FIXME(sil-serialize-all)
@nonobjc
internal func bridgingObjectForKey(_ aKey: AnyObject)
-> AnyObject? {
guard let nativeKey = _conditionallyBridgeFromObjectiveC(aKey, Key.self)
else { return nil }
let (i, found) = nativeBuffer._find(
nativeKey, startBucket: nativeBuffer._bucket(nativeKey))
if found {
bridgeEverything()
return bridgedBuffer.value(at: i.offset)
}
return nil
}
@inlinable // FIXME(sil-serialize-all)
@objc
internal func enumerator() -> _NSEnumerator {
bridgeEverything()
return _NativeDictionaryNSEnumerator<AnyObject, AnyObject>(bridgedBuffer)
}
@inlinable // FIXME(sil-serialize-all)
@objc(countByEnumeratingWithState:objects:count:)
internal func countByEnumerating(
with state: UnsafeMutablePointer<_SwiftNSFastEnumerationState>,
objects: UnsafeMutablePointer<AnyObject>?,
count: Int
) -> Int {
var theState = state.pointee
if theState.state == 0 {
theState.state = 1 // Arbitrary non-zero value.
theState.itemsPtr = AutoreleasingUnsafeMutablePointer(objects)
theState.mutationsPtr = _fastEnumerationStorageMutationsPtr
theState.extra.0 = CUnsignedLong(nativeBuffer.startIndex.offset)
}
// Test 'objects' rather than 'count' because (a) this is very rare anyway,
// and (b) the optimizer should then be able to optimize away the
// unwrapping check below.
if _slowPath(objects == nil) {
return 0
}
let unmanagedObjects = _UnmanagedAnyObjectArray(objects!)
var currIndex = _NativeDictionaryIndex<Key, Value>(
offset: Int(theState.extra.0))
let endIndex = nativeBuffer.endIndex
var stored = 0
// Only need to bridge once, so we can hoist it out of the loop.
if (currIndex != endIndex) {
bridgeEverything()
}
for i in 0..<count {
if (currIndex == endIndex) {
break
}
let bridgedKey = bridgedBuffer.key(at: currIndex.offset)
unmanagedObjects[i] = bridgedKey
stored += 1
nativeBuffer.formIndex(after: &currIndex)
}
theState.extra.0 = CUnsignedLong(currIndex.offset)
state.pointee = theState
return stored
}
}
#else
@_fixed_layout // FIXME(sil-serialize-all)
@usableFromInline // FIXME(sil-serialize-all)
final internal class _SwiftDeferredNSDictionary<Key: Hashable, Value> { }
#endif
#if _runtime(_ObjC)
@usableFromInline
@_fixed_layout
internal struct _CocoaDictionaryBuffer: _HashBuffer {
@usableFromInline
internal var cocoaDictionary: _NSDictionary
@inlinable // FIXME(sil-serialize-all)
internal init(cocoaDictionary: _NSDictionary) {
self.cocoaDictionary = cocoaDictionary
}
internal typealias Index = _CocoaDictionaryIndex
internal typealias SequenceElement = (AnyObject, AnyObject)
internal typealias SequenceElementWithoutLabels = (AnyObject, AnyObject)
internal typealias Key = AnyObject
internal typealias Value = AnyObject
@inlinable // FIXME(sil-serialize-all)
internal var startIndex: Index {
return Index(cocoaDictionary, startIndex: ())
}
@inlinable // FIXME(sil-serialize-all)
internal var endIndex: Index {
return Index(cocoaDictionary, endIndex: ())
}
@inlinable // FIXME(sil-serialize-all)
internal func index(after i: Index) -> Index {
return i.successor()
}
@inlinable // FIXME(sil-serialize-all)
internal func formIndex(after i: inout Index) {
// FIXME: swift-3-indexing-model: optimize if possible.
i = i.successor()
}
@inlinable // FIXME(sil-serialize-all)
internal func index(forKey key: Key) -> Index? {
// Fast path that does not involve creating an array of all keys. In case
// the key is present, this lookup is a penalty for the slow path, but the
// potential savings are significant: we could skip a memory allocation and
// a linear search.
if maybeGet(key) == nil {
return nil
}
let allKeys = _stdlib_NSDictionary_allKeys(cocoaDictionary)
var keyIndex = -1
for i in 0..<allKeys.value {
if _stdlib_NSObject_isEqual(key, allKeys[i]) {
keyIndex = i
break
}
}
_sanityCheck(keyIndex >= 0,
"Key was found in fast path, but not found later?")
return Index(cocoaDictionary, allKeys, keyIndex)
}
@inlinable // FIXME(sil-serialize-all)
internal func assertingGet(_ i: Index) -> SequenceElement {
let key: Key = i.allKeys[i.currentKeyIndex]
let value: Value = i.cocoaDictionary.objectFor(key)!
return (key, value)
}
@inlinable // FIXME(sil-serialize-all)
internal func assertingGet(_ key: Key) -> Value {
let value: Value? = cocoaDictionary.objectFor(key)
_precondition(value != nil, "Key not found in underlying NSDictionary")
return value!
}
@inlinable // FIXME(sil-serialize-all)
@inline(__always)
internal func maybeGet(_ key: Key) -> Value? {
return cocoaDictionary.objectFor(key)
}
@inlinable // FIXME(sil-serialize-all)
@discardableResult
internal mutating func updateValue(_ value: Value, forKey key: Key) -> Value? {
_sanityCheckFailure("cannot mutate NSDictionary")
}
@inlinable // FIXME(sil-serialize-all)
@discardableResult
internal mutating func insert(
_ value: Value, forKey key: Key
) -> (inserted: Bool, memberAfterInsert: Value) {
_sanityCheckFailure("cannot mutate NSDictionary")
}
@inlinable // FIXME(sil-serialize-all)
@discardableResult
internal mutating func remove(at index: Index) -> SequenceElement {
_sanityCheckFailure("cannot mutate NSDictionary")
}
@inlinable // FIXME(sil-serialize-all)
@discardableResult
internal mutating func removeValue(forKey key: Key) -> Value? {
_sanityCheckFailure("cannot mutate NSDictionary")
}
@inlinable // FIXME(sil-serialize-all)
internal mutating func removeAll(keepingCapacity keepCapacity: Bool) {
_sanityCheckFailure("cannot mutate NSDictionary")
}
@inlinable // FIXME(sil-serialize-all)
internal var count: Int {
return cocoaDictionary.count
}
@inlinable // FIXME(sil-serialize-all)
internal static func fromArray(_ elements: [SequenceElementWithoutLabels])
-> _CocoaDictionaryBuffer {
_sanityCheckFailure("this function should never be called")
}
}
#endif
@usableFromInline
@_frozen
internal enum _VariantDictionaryBuffer<Key: Hashable, Value>: _HashBuffer {
internal typealias NativeBuffer = _NativeDictionaryBuffer<Key, Value>
internal typealias NativeIndex = _NativeDictionaryIndex<Key, Value>
#if _runtime(_ObjC)
internal typealias CocoaBuffer = _CocoaDictionaryBuffer
#endif
internal typealias SequenceElement = (key: Key, value: Value)
internal typealias SequenceElementWithoutLabels = (key: Key, value: Value)
internal typealias SelfType = _VariantDictionaryBuffer
case native(NativeBuffer)
#if _runtime(_ObjC)
case cocoa(CocoaBuffer)
#endif
@inlinable // FIXME(sil-serialize-all)
@_transparent
internal var guaranteedNative: Bool {
return _canBeClass(Key.self) == 0 || _canBeClass(Value.self) == 0
}
@inlinable // FIXME(sil-serialize-all)
internal mutating func isUniquelyReferenced() -> Bool {
// Note that &self drills down through .native(NativeBuffer) to the first
// property in NativeBuffer, which is the reference to the storage.
if _fastPath(guaranteedNative) {
return _isUnique_native(&self)
}
switch self {
case .native:
return _isUnique_native(&self)
#if _runtime(_ObjC)
case .cocoa:
// Don't consider Cocoa buffer mutable, even if it is mutable and is
// uniquely referenced.
return false
#endif
}
}
@inlinable // FIXME(sil-serialize-all)
internal var asNative: NativeBuffer {
get {
switch self {
case .native(let buffer):
return buffer
#if _runtime(_ObjC)
case .cocoa:
_sanityCheckFailure("internal error: not backed by native buffer")
#endif
}
}
set {
self = .native(newValue)
}
}
@inlinable // FIXME(sil-serialize-all)
internal mutating func ensureNativeBuffer() {
#if _runtime(_ObjC)
if _fastPath(guaranteedNative) { return }
if case .cocoa(let cocoaBuffer) = self {
migrateDataToNativeBuffer(cocoaBuffer)
}
#endif
}
#if _runtime(_ObjC)
@inlinable // FIXME(sil-serialize-all)
internal var asCocoa: CocoaBuffer {
switch self {
case .native:
_sanityCheckFailure("internal error: not backed by NSDictionary")
case .cocoa(let cocoaBuffer):
return cocoaBuffer
}
}
#endif
/// Return true if self is native.
@inlinable // FIXME(sil-serialize-all)
internal var _isNative: Bool {
#if _runtime(_ObjC)
switch self {
case .native:
return true
case .cocoa:
return false
}
#else
return true
#endif
}
@inline(__always)
@inlinable // FIXME(sil-serialize-all)
internal mutating func ensureUniqueNativeBufferNative(
withBucketCount desiredBucketCount: Int
) -> (reallocated: Bool, capacityChanged: Bool) {
let oldBucketCount = asNative.bucketCount
if oldBucketCount >= desiredBucketCount && isUniquelyReferenced() {
return (reallocated: false, capacityChanged: false)
}
let oldNativeBuffer = asNative
var newNativeBuffer = NativeBuffer(bucketCount: desiredBucketCount)
let newBucketCount = newNativeBuffer.bucketCount
for i in 0..<oldBucketCount {
if oldNativeBuffer.isInitializedEntry(at: i) {
if oldBucketCount == newBucketCount {
let key = oldNativeBuffer.key(at: i)
let value = oldNativeBuffer.value(at: i)
newNativeBuffer.initializeKey(key, value: value , at: i)
} else {
let key = oldNativeBuffer.key(at: i)
newNativeBuffer.unsafeAddNew(
key: key,
value: oldNativeBuffer.value(at: i))
}
}
}
newNativeBuffer.count = oldNativeBuffer.count
self = .native(newNativeBuffer)
return (reallocated: true,
capacityChanged: oldBucketCount != newBucketCount)
}
@inline(__always)
@inlinable // FIXME(sil-serialize-all)
internal mutating func ensureUniqueNativeBuffer(
withCapacity minimumCapacity: Int
) -> (reallocated: Bool, capacityChanged: Bool) {
let bucketCount = NativeBuffer.bucketCount(
forCapacity: minimumCapacity,
maxLoadFactorInverse: _hashContainerDefaultMaxLoadFactorInverse)
return ensureUniqueNativeBuffer(withBucketCount: bucketCount)
}
/// Ensure this we hold a unique reference to a native buffer
/// having at least `minimumCapacity` elements.
@inlinable // FIXME(sil-serialize-all)
internal mutating func ensureUniqueNativeBuffer(
withBucketCount desiredBucketCount: Int
) -> (reallocated: Bool, capacityChanged: Bool) {
#if _runtime(_ObjC)
// This is a performance optimization that was put in to ensure that we did
// not make a copy of self to call _isNative over the entire if region
// causing at -Onone the uniqueness check to fail. This code used to be:
//
// if _isNative {
// return ensureUniqueNativeBufferNative(
// withBucketCount: desiredBucketCount)
// }
//
// SR-6437
let n = _isNative
if n {
return ensureUniqueNativeBufferNative(withBucketCount: desiredBucketCount)
}
switch self {
case .native:
fatalError("This should have been handled earlier")
case .cocoa(let cocoaBuffer):
let cocoaDictionary = cocoaBuffer.cocoaDictionary
var newNativeBuffer = NativeBuffer(bucketCount: desiredBucketCount)
let oldCocoaIterator = _CocoaDictionaryIterator(cocoaDictionary)
while let (key, value) = oldCocoaIterator.next() {
newNativeBuffer.unsafeAddNew(
key: _forceBridgeFromObjectiveC(key, Key.self),
value: _forceBridgeFromObjectiveC(value, Value.self))
}
newNativeBuffer.count = cocoaDictionary.count
self = .native(newNativeBuffer)
return (reallocated: true, capacityChanged: true)
}
#else
return ensureUniqueNativeBufferNative(withBucketCount: desiredBucketCount)
#endif
}
#if _runtime(_ObjC)
@inline(never)
@usableFromInline
internal mutating func migrateDataToNativeBuffer(
_ cocoaBuffer: _CocoaDictionaryBuffer
) {
let allocated = ensureUniqueNativeBuffer(
withCapacity: cocoaBuffer.count).reallocated
_sanityCheck(allocated, "failed to allocate native Dictionary buffer")
}
#endif
/// Reserves enough space for the specified number of elements to be stored
/// without reallocating additional storage.
@inlinable // FIXME(sil-serialize-all)
internal mutating func reserveCapacity(_ capacity: Int) {
_ = ensureUniqueNativeBuffer(withCapacity: capacity)
}
/// The number of elements that can be stored without expanding the current
/// storage.
///
/// For bridged storage, this is equal to the current count of the
/// collection, since any addition will trigger a copy of the elements into
/// newly allocated storage. For native storage, this is the element count
/// at which adding any more elements will exceed the load factor.
@inlinable // FIXME(sil-serialize-all)
internal var capacity: Int {
switch self {
case .native:
return Int(Double(asNative.bucketCount) /
_hashContainerDefaultMaxLoadFactorInverse)
#if _runtime(_ObjC)
case .cocoa(let cocoaBuffer):
return cocoaBuffer.count
#endif
}
}
//
// _HashBuffer conformance
//
internal typealias Index = DictionaryIndex<Key, Value>
@inlinable // FIXME(sil-serialize-all)
internal var startIndex: Index {
if _fastPath(guaranteedNative) {
return ._native(asNative.startIndex)
}
switch self {
case .native:
return ._native(asNative.startIndex)
#if _runtime(_ObjC)
case .cocoa(let cocoaBuffer):
return ._cocoa(cocoaBuffer.startIndex)
#endif
}
}
@inlinable // FIXME(sil-serialize-all)
internal var endIndex: Index {
if _fastPath(guaranteedNative) {
return ._native(asNative.endIndex)
}
switch self {
case .native:
return ._native(asNative.endIndex)
#if _runtime(_ObjC)
case .cocoa(let cocoaBuffer):
return ._cocoa(cocoaBuffer.endIndex)
#endif
}
}
@inlinable // FIXME(sil-serialize-all)
internal func index(after i: Index) -> Index {
if _fastPath(guaranteedNative) {
return ._native(asNative.index(after: i._nativeIndex))
}
switch self {
case .native:
return ._native(asNative.index(after: i._nativeIndex))
#if _runtime(_ObjC)
case .cocoa(let cocoaBuffer):
return ._cocoa(cocoaBuffer.index(after: i._cocoaIndex))
#endif
}
}
@inlinable // FIXME(sil-serialize-all)
internal func formIndex(after i: inout Index) {
// FIXME: swift-3-indexing-model: optimize if possible.
i = index(after: i)
}
@inlinable // FIXME(sil-serialize-all)
@inline(__always)
internal func index(forKey key: Key) -> Index? {
if _fastPath(guaranteedNative) {
if let nativeIndex = asNative.index(forKey: key) {
return ._native(nativeIndex)
}
return nil
}
switch self {
case .native:
if let nativeIndex = asNative.index(forKey: key) {
return ._native(nativeIndex)
}
return nil
#if _runtime(_ObjC)
case .cocoa(let cocoaBuffer):
let anyObjectKey: AnyObject = _bridgeAnythingToObjectiveC(key)
if let cocoaIndex = cocoaBuffer.index(forKey: anyObjectKey) {
return ._cocoa(cocoaIndex)
}
return nil
#endif
}
}
@inlinable // FIXME(sil-serialize-all)
@inline(__always)
internal func containsKey(_ key: Key) -> Bool {
if _fastPath(guaranteedNative) {
return asNative.index(forKey: key) != nil
}
switch self {
case .native:
return asNative.index(forKey: key) != nil
#if _runtime(_ObjC)
case .cocoa(let cocoaBuffer):
return SelfType.maybeGetFromCocoaBuffer(cocoaBuffer, forKey: key) != nil
#endif
}
}
@inlinable // FIXME(sil-serialize-all)
internal func assertingGet(_ i: Index) -> SequenceElement {
if _fastPath(guaranteedNative) {
return asNative.assertingGet(i._nativeIndex)
}
switch self {
case .native:
return asNative.assertingGet(i._nativeIndex)
#if _runtime(_ObjC)
case .cocoa(let cocoaBuffer):
let (anyObjectKey, anyObjectValue) =
cocoaBuffer.assertingGet(i._cocoaIndex)
let nativeKey = _forceBridgeFromObjectiveC(anyObjectKey, Key.self)
let nativeValue = _forceBridgeFromObjectiveC(anyObjectValue, Value.self)
return (nativeKey, nativeValue)
#endif
}
}
@inlinable // FIXME(sil-serialize-all)
internal func assertingGet(_ key: Key) -> Value {
if _fastPath(guaranteedNative) {
return asNative.assertingGet(key)
}
switch self {
case .native:
return asNative.assertingGet(key)
#if _runtime(_ObjC)
case .cocoa(let cocoaBuffer):
// FIXME: This assumes that Key and Value are bridged verbatim.
let anyObjectKey: AnyObject = _bridgeAnythingToObjectiveC(key)
let anyObjectValue: AnyObject = cocoaBuffer.assertingGet(anyObjectKey)
return _forceBridgeFromObjectiveC(anyObjectValue, Value.self)
#endif
}
}
#if _runtime(_ObjC)
@inline(never)
@usableFromInline
internal static func maybeGetFromCocoaBuffer(
_ cocoaBuffer: CocoaBuffer, forKey key: Key
) -> Value? {
let anyObjectKey: AnyObject = _bridgeAnythingToObjectiveC(key)
if let anyObjectValue = cocoaBuffer.maybeGet(anyObjectKey) {
return _forceBridgeFromObjectiveC(anyObjectValue, Value.self)
}
return nil
}
#endif
@inlinable // FIXME(sil-serialize-all)
@inline(__always)
internal func maybeGet(_ key: Key) -> Value? {
if _fastPath(guaranteedNative) {
return asNative.maybeGet(key)
}
switch self {
case .native:
return asNative.maybeGet(key)
#if _runtime(_ObjC)
case .cocoa(let cocoaBuffer):
return SelfType.maybeGetFromCocoaBuffer(cocoaBuffer, forKey: key)
#endif
}
}
@inlinable // FIXME(sil-serialize-all)
internal mutating func nativeUpdateValue(
_ value: Value, forKey key: Key
) -> Value? {
var (i, found) = asNative._find(key, startBucket: asNative._bucket(key))
let minBuckets = found
? asNative.bucketCount
: NativeBuffer.bucketCount(
forCapacity: asNative.count + 1,
maxLoadFactorInverse: _hashContainerDefaultMaxLoadFactorInverse)
let (_, capacityChanged) = ensureUniqueNativeBuffer(
withBucketCount: minBuckets)
if capacityChanged {
i = asNative._find(key, startBucket: asNative._bucket(key)).pos
}
let oldValue: Value? = found ? asNative.value(at: i.offset) : nil
if found {
asNative.setKey(key, value: value, at: i.offset)
} else {
asNative.initializeKey(key, value: value, at: i.offset)
asNative.count += 1
}
return oldValue
}
@inlinable // FIXME(sil-serialize-all)
@discardableResult
internal mutating func updateValue(
_ value: Value, forKey key: Key
) -> Value? {
if _fastPath(guaranteedNative) {
return nativeUpdateValue(value, forKey: key)
}
switch self {
case .native:
return nativeUpdateValue(value, forKey: key)
#if _runtime(_ObjC)
case .cocoa(let cocoaBuffer):
migrateDataToNativeBuffer(cocoaBuffer)
return nativeUpdateValue(value, forKey: key)
#endif
}
}
@inlinable // FIXME(sil-serialize-all)
internal mutating func nativePointerToValue(at i: Index)
-> UnsafeMutablePointer<Value> {
// This is a performance optimization that was put in to ensure that we did
// not make a copy of self to call asNative.bucketCount over
// ensureUniqueNativeBefore causing at -Onone the uniqueness check to
// fail. This code used to be:
//
// _ = ensureUniqueNativeBuffer(withBucketCount: bucketCount)
//
// SR-6437
let bucketCount = asNative.bucketCount
_ = ensureUniqueNativeBuffer(withBucketCount: bucketCount)
return asNative.values + i._nativeIndex.offset
}
@inlinable // FIXME(sil-serialize-all)
internal mutating func pointerToValue(at i: Index)
-> UnsafeMutablePointer<Value> {
if _fastPath(guaranteedNative) {
return nativePointerToValue(at: i)
}
switch self {
case .native:
return nativePointerToValue(at: i)
#if _runtime(_ObjC)
case .cocoa(let cocoaStorage):
// We have to migrate the data to native storage before we can return a
// mutable pointer. But after we migrate, the Cocoa index becomes
// useless, so get the key first.
let cocoaIndex = i._cocoaIndex
let anyObjectKey: AnyObject =
cocoaIndex.allKeys[cocoaIndex.currentKeyIndex]
migrateDataToNativeBuffer(cocoaStorage)
let key = _forceBridgeFromObjectiveC(anyObjectKey, Key.self)
let nativeIndex = asNative.index(forKey: key)!
return nativePointerToValue(at: ._native(nativeIndex))
#endif
}
}
@inlinable // FIXME(sil-serialize-all)
internal mutating func nativePointerToValue(
forKey key: Key, insertingDefault defaultValue: () -> Value
) -> (inserted: Bool, pointer: UnsafeMutablePointer<Value>) {
var (i, found) = asNative._find(key, startBucket: asNative._bucket(key))
if found {
let pointer = nativePointerToValue(at: ._native(i))
return (inserted: false, pointer: pointer)
}
let minCapacity = asNative.count + 1
let (_, capacityChanged) = ensureUniqueNativeBuffer(
withCapacity: minCapacity)
if capacityChanged {
i = asNative._find(key, startBucket: asNative._bucket(key)).pos
}
asNative.initializeKey(key, value: defaultValue(), at: i.offset)
asNative.count += 1
return (inserted: true, pointer: asNative.values + i.offset)
}
@inlinable // FIXME(sil-serialize-all)
internal mutating func pointerToValue(
forKey key: Key, insertingDefault defaultValue: () -> Value
) -> (inserted: Bool, pointer: UnsafeMutablePointer<Value>) {
ensureNativeBuffer()
return nativePointerToValue(forKey: key, insertingDefault: defaultValue)
}
@inlinable // FIXME(sil-serialize-all)
internal mutating func nativeInsert(
_ value: Value, forKey key: Key
) -> (inserted: Bool, memberAfterInsert: Value) {
var (i, found) = asNative._find(key, startBucket: asNative._bucket(key))
if found {
return (inserted: false, memberAfterInsert: asNative.value(at: i.offset))
}
let minCapacity = asNative.count + 1
let (_, capacityChanged) = ensureUniqueNativeBuffer(
withCapacity: minCapacity)
if capacityChanged {
i = asNative._find(key, startBucket: asNative._bucket(key)).pos
}
asNative.initializeKey(key, value: value, at: i.offset)
asNative.count += 1
return (inserted: true, memberAfterInsert: value)
}
@inlinable // FIXME(sil-serialize-all)
@discardableResult
internal mutating func insert(
_ value: Value, forKey key: Key
) -> (inserted: Bool, memberAfterInsert: Value) {
ensureNativeBuffer()
return nativeInsert(value, forKey: key)
}
@inlinable // FIXME(sil-serialize-all)
internal func nativeMapValues<T>(
_ transform: (Value) throws -> T
) rethrows -> _VariantDictionaryBuffer<Key, T> {
var buffer = _NativeDictionaryBuffer<Key, T>(
_exactBucketCount: asNative.bucketCount)
// Because the keys in the current and new buffer are the same, we can
// initialize to the same locations in the new buffer, skipping hash value
// recalculations.
var i = asNative.startIndex
while i != asNative.endIndex {
let (k, v) = asNative.assertingGet(i)
try buffer.initializeKey(k, value: transform(v), at: i.offset)
asNative.formIndex(after: &i)
}
buffer.count = asNative.count
return .native(buffer)
}
@inlinable // FIXME(sil-serialize-all)
internal func mapValues<T>(
_ transform: (Value) throws -> T
) rethrows -> _VariantDictionaryBuffer<Key, T> {
if _fastPath(guaranteedNative) {
return try nativeMapValues(transform)
}
switch self {
case .native:
return try nativeMapValues(transform)
#if _runtime(_ObjC)
case .cocoa(let cocoaStorage):
var storage: _VariantDictionaryBuffer<Key, T> = .native(
_NativeDictionaryBuffer<Key, T>(minimumCapacity: cocoaStorage.count))
var i = cocoaStorage.startIndex
while i != cocoaStorage.endIndex {
let (anyObjectKey, anyObjectValue) = cocoaStorage.assertingGet(i)
let nativeKey = _forceBridgeFromObjectiveC(anyObjectKey, Key.self)
let nativeValue = _forceBridgeFromObjectiveC(anyObjectValue, Value.self)
_ = try storage.nativeInsert(transform(nativeValue), forKey: nativeKey)
cocoaStorage.formIndex(after: &i)
}
return storage
#endif
}
}
@inlinable // FIXME(sil-serialize-all)
internal mutating func nativeMerge<S: Sequence>(
_ keysAndValues: S,
uniquingKeysWith combine: (Value, Value) throws -> Value
) rethrows where S.Element == (Key, Value) {
for (key, value) in keysAndValues {
var (i, found) = asNative._find(key, startBucket: asNative._bucket(key))
if found {
// This is a performance optimization that was put in to ensure that we
// did not make a copy of self to call asNative.bucketCount over
// ensureUniqueNativeBefore causing at -Onone the uniqueness check to
// fail. This code used to be:
//
// _ = ensureUniqueNativeBuffer(withBucketCount: asNative.bucketCount)
//
// SR-6437
let bucketCount = asNative.bucketCount
_ = ensureUniqueNativeBuffer(withBucketCount: bucketCount)
do {
let newValue = try combine(asNative.value(at: i.offset), value)
asNative.setKey(key, value: newValue, at: i.offset)
} catch _MergeError.keyCollision {
fatalError("Duplicate values for key: '\(key)'")
}
} else {
let minCapacity = asNative.count + 1
let (_, capacityChanged) = ensureUniqueNativeBuffer(
withCapacity: minCapacity)
if capacityChanged {
i = asNative._find(key, startBucket: asNative._bucket(key)).pos
}
asNative.initializeKey(key, value: value, at: i.offset)
asNative.count += 1
}
}
}
@inlinable // FIXME(sil-serialize-all)
internal mutating func merge<S: Sequence>(
_ keysAndValues: S,
uniquingKeysWith combine: (Value, Value) throws -> Value
) rethrows where S.Element == (Key, Value) {
ensureNativeBuffer()
try nativeMerge(keysAndValues, uniquingKeysWith: combine)
}
@inlinable // FIXME(sil-serialize-all)
internal mutating func nativeGroup<S: Sequence>(
_ values: S,
by keyForValue: (S.Element) throws -> Key
) rethrows where Value == [S.Element] {
defer { _fixLifetime(asNative) }
for value in values {
let key = try keyForValue(value)
var (i, found) = asNative._find(key, startBucket: asNative._bucket(key))
if found {
asNative.values[i.offset].append(value)
} else {
let minCapacity = asNative.count + 1
let (_, capacityChanged) = ensureUniqueNativeBuffer(
withCapacity: minCapacity)
if capacityChanged {
i = asNative._find(key, startBucket: asNative._bucket(key)).pos
}
asNative.initializeKey(key, value: [value], at: i.offset)
asNative.count += 1
}
}
}
/// - parameter idealBucket: The ideal bucket for the element being deleted.
/// - parameter offset: The offset of the element that will be deleted.
/// Precondition: there should be an initialized entry at offset.
@inlinable // FIXME(sil-serialize-all)
internal mutating func nativeDelete(
_ nativeBuffer: NativeBuffer, idealBucket: Int, offset: Int
) {
_sanityCheck(
nativeBuffer.isInitializedEntry(at: offset), "expected initialized entry")
var nativeBuffer = nativeBuffer
// remove the element
nativeBuffer.destroyEntry(at: offset)
nativeBuffer.count -= 1
// If we've put a hole in a chain of contiguous elements, some
// element after the hole may belong where the new hole is.
var hole = offset
// Find the first bucket in the contiguous chain
var start = idealBucket
while nativeBuffer.isInitializedEntry(at: nativeBuffer._prev(start)) {
start = nativeBuffer._prev(start)
}
// Find the last bucket in the contiguous chain
var lastInChain = hole
var b = nativeBuffer._index(after: lastInChain)
while nativeBuffer.isInitializedEntry(at: b) {
lastInChain = b
b = nativeBuffer._index(after: b)
}
// Relocate out-of-place elements in the chain, repeating until
// none are found.
while hole != lastInChain {
// Walk backwards from the end of the chain looking for
// something out-of-place.
var b = lastInChain
while b != hole {
let idealBucket = nativeBuffer._bucket(nativeBuffer.key(at: b))
// Does this element belong between start and hole? We need
// two separate tests depending on whether [start, hole] wraps
// around the end of the storage
let c0 = idealBucket >= start
let c1 = idealBucket <= hole
if start <= hole ? (c0 && c1) : (c0 || c1) {
break // Found it
}
b = nativeBuffer._prev(b)
}
if b == hole { // No out-of-place elements found; we're done adjusting
break
}
// Move the found element into the hole
nativeBuffer.moveInitializeEntry(
from: nativeBuffer,
at: b,
toEntryAt: hole)
hole = b
}
}
@inlinable // FIXME(sil-serialize-all)
internal mutating func nativeRemoveObject(forKey key: Key) -> Value? {
var idealBucket = asNative._bucket(key)
var (index, found) = asNative._find(key, startBucket: idealBucket)
// Fast path: if the key is not present, we will not mutate the set,
// so don't force unique buffer.
if !found {
return nil
}
// This is a performance optimization that was put in to ensure that we
// did not make a copy of self to call asNative.bucketCount over
// ensureUniqueNativeBefore causing at -Onone the uniqueness check to
// fail. This code used to be:
//
// ... = ensureUniqueNativeBuffer(withBucketCount: asNative.bucketCount)
//
// SR-6437
let bucketCount = asNative.bucketCount
let (_, capacityChanged) = ensureUniqueNativeBuffer(
withBucketCount: bucketCount)
let nativeBuffer = asNative
if capacityChanged {
idealBucket = nativeBuffer._bucket(key)
(index, found) = nativeBuffer._find(key, startBucket: idealBucket)
_sanityCheck(found, "key was lost during buffer migration")
}
let oldValue = nativeBuffer.value(at: index.offset)
nativeDelete(nativeBuffer, idealBucket: idealBucket,
offset: index.offset)
return oldValue
}
@inlinable // FIXME(sil-serialize-all)
internal mutating func nativeRemove(
at nativeIndex: NativeIndex
) -> SequenceElement {
// This is a performance optimization that was put in to ensure that we did
// not make a copy of self to call asNative.bucketCount over
// ensureUniqueNativeBefore causing at -Onone the uniqueness check to
// fail. This code used to be:
//
// _ = ensureUniqueNativeBuffer(withBucketCount: asNative.bucketCount)
//
// SR-6437
let bucketCount = asNative.bucketCount
// The provided index should be valid, so we will always mutating the
// set buffer. Request unique buffer.
_ = ensureUniqueNativeBuffer(withBucketCount: bucketCount)
let nativeBuffer = asNative
let result = nativeBuffer.assertingGet(nativeIndex)
let key = result.0
nativeDelete(nativeBuffer, idealBucket: nativeBuffer._bucket(key),
offset: nativeIndex.offset)
return result
}
@inlinable // FIXME(sil-serialize-all)
@discardableResult
internal mutating func remove(at index: Index) -> SequenceElement {
if _fastPath(guaranteedNative) {
return nativeRemove(at: index._nativeIndex)
}
switch self {
case .native:
return nativeRemove(at: index._nativeIndex)
#if _runtime(_ObjC)
case .cocoa(let cocoaBuffer):
// We have to migrate the data first. But after we do so, the Cocoa
// index becomes useless, so get the key first.
//
// FIXME(performance): fuse data migration and element deletion into one
// operation.
let index = index._cocoaIndex
let anyObjectKey: AnyObject = index.allKeys[index.currentKeyIndex]
migrateDataToNativeBuffer(cocoaBuffer)
let key = _forceBridgeFromObjectiveC(anyObjectKey, Key.self)
let value = nativeRemoveObject(forKey: key)
return (key, value._unsafelyUnwrappedUnchecked)
#endif
}
}
@inlinable // FIXME(sil-serialize-all)
@discardableResult
internal mutating func removeValue(forKey key: Key) -> Value? {
if _fastPath(guaranteedNative) {
return nativeRemoveObject(forKey: key)
}
switch self {
case .native:
return nativeRemoveObject(forKey: key)
#if _runtime(_ObjC)
case .cocoa(let cocoaBuffer):
let anyObjectKey: AnyObject = _bridgeAnythingToObjectiveC(key)
if cocoaBuffer.maybeGet(anyObjectKey) == nil {
return nil
}
migrateDataToNativeBuffer(cocoaBuffer)
return nativeRemoveObject(forKey: key)
#endif
}
}
@inlinable // FIXME(sil-serialize-all)
internal mutating func nativeRemoveAll() {
if !isUniquelyReferenced() {
asNative = NativeBuffer(_exactBucketCount: asNative.bucketCount)
return
}
// We have already checked for the empty dictionary case and unique
// reference, so we will always mutate the dictionary buffer.
var nativeBuffer = asNative
for b in 0..<nativeBuffer.bucketCount {
if nativeBuffer.isInitializedEntry(at: b) {
nativeBuffer.destroyEntry(at: b)
}
}
nativeBuffer.count = 0
}
@inlinable // FIXME(sil-serialize-all)
internal mutating func removeAll(keepingCapacity keepCapacity: Bool) {
if count == 0 {
return
}
if !keepCapacity {
self = .native(NativeBuffer(bucketCount: 2))
return
}
if _fastPath(guaranteedNative) {
nativeRemoveAll()
return
}
switch self {
case .native:
nativeRemoveAll()
#if _runtime(_ObjC)
case .cocoa(let cocoaBuffer):
self = .native(NativeBuffer(minimumCapacity: cocoaBuffer.count))
#endif
}
}
@inlinable // FIXME(sil-serialize-all)
internal var count: Int {
if _fastPath(guaranteedNative) {
return asNative.count
}
switch self {
case .native:
return asNative.count
#if _runtime(_ObjC)
case .cocoa(let cocoaBuffer):
return cocoaBuffer.count
#endif
}
}
/// Returns an iterator over the `(Key, Value)` pairs.
///
/// - Complexity: O(1).
@inlinable // FIXME(sil-serialize-all)
@inline(__always)
internal func makeIterator() -> DictionaryIterator<Key, Value> {
switch self {
case .native(let buffer):
return ._native(
start: asNative.startIndex, end: asNative.endIndex, buffer: buffer)
#if _runtime(_ObjC)
case .cocoa(let cocoaBuffer):
return ._cocoa(_CocoaDictionaryIterator(cocoaBuffer.cocoaDictionary))
#endif
}
}
@inlinable // FIXME(sil-serialize-all)
internal static func fromArray(_ elements: [SequenceElement])
-> _VariantDictionaryBuffer<Key, Value> {
_sanityCheckFailure("this function should never be called")
}
}
@_fixed_layout // FIXME(sil-serialize-all)
@usableFromInline
internal struct _NativeDictionaryIndex<Key, Value>: Comparable {
@usableFromInline
internal var offset: Int
@inlinable // FIXME(sil-serialize-all)
internal init(offset: Int) {
self.offset = offset
}
}
extension _NativeDictionaryIndex {
@inlinable // FIXME(sil-serialize-all)
internal static func < (
lhs: _NativeDictionaryIndex<Key, Value>,
rhs: _NativeDictionaryIndex<Key, Value>
) -> Bool {
return lhs.offset < rhs.offset
}
@inlinable // FIXME(sil-serialize-all)
internal static func <= (
lhs: _NativeDictionaryIndex<Key, Value>,
rhs: _NativeDictionaryIndex<Key, Value>
) -> Bool {
return lhs.offset <= rhs.offset
}
@inlinable // FIXME(sil-serialize-all)
internal static func > (
lhs: _NativeDictionaryIndex<Key, Value>,
rhs: _NativeDictionaryIndex<Key, Value>
) -> Bool {
return lhs.offset > rhs.offset
}
@inlinable // FIXME(sil-serialize-all)
internal static func >= (
lhs: _NativeDictionaryIndex<Key, Value>,
rhs: _NativeDictionaryIndex<Key, Value>
) -> Bool {
return lhs.offset >= rhs.offset
}
@inlinable // FIXME(sil-serialize-all)
internal static func == (
lhs: _NativeDictionaryIndex<Key, Value>,
rhs: _NativeDictionaryIndex<Key, Value>
) -> Bool {
return lhs.offset == rhs.offset
}
}
#if _runtime(_ObjC)
@_fixed_layout // FIXME(sil-serialize-all)
@usableFromInline
internal struct _CocoaDictionaryIndex: Comparable {
// Assumption: we rely on NSDictionary.getObjects when being
// repeatedly called on the same NSDictionary, returning items in the same
// order every time.
// Similarly, the same assumption holds for NSSet.allObjects.
/// A reference to the NSDictionary, which owns members in `allObjects`,
/// or `allKeys`, for NSSet and NSDictionary respectively.
@usableFromInline // FIXME(sil-serialize-all)
internal let cocoaDictionary: _NSDictionary
// FIXME: swift-3-indexing-model: try to remove the cocoa reference, but make
// sure that we have a safety check for accessing `allKeys`. Maybe move both
// into the dictionary/set itself.
/// An unowned array of keys.
@usableFromInline // FIXME(sil-serialize-all)
internal var allKeys: _HeapBuffer<Int, AnyObject>
/// Index into `allKeys`
@usableFromInline // FIXME(sil-serialize-all)
internal var currentKeyIndex: Int
@inlinable // FIXME(sil-serialize-all)
internal init(_ cocoaDictionary: _NSDictionary, startIndex: ()) {
self.cocoaDictionary = cocoaDictionary
self.allKeys = _stdlib_NSDictionary_allKeys(cocoaDictionary)
self.currentKeyIndex = 0
}
@inlinable // FIXME(sil-serialize-all)
internal init(_ cocoaDictionary: _NSDictionary, endIndex: ()) {
self.cocoaDictionary = cocoaDictionary
self.allKeys = _stdlib_NSDictionary_allKeys(cocoaDictionary)
self.currentKeyIndex = allKeys.value
}
@inlinable // FIXME(sil-serialize-all)
internal init(_ cocoaDictionary: _NSDictionary,
_ allKeys: _HeapBuffer<Int, AnyObject>,
_ currentKeyIndex: Int
) {
self.cocoaDictionary = cocoaDictionary
self.allKeys = allKeys
self.currentKeyIndex = currentKeyIndex
}
/// Returns the next consecutive value after `self`.
///
/// - Precondition: The next value is representable.
@inlinable // FIXME(sil-serialize-all)
internal func successor() -> _CocoaDictionaryIndex {
// FIXME: swift-3-indexing-model: remove this method.
_precondition(
currentKeyIndex < allKeys.value, "Cannot increment endIndex")
return _CocoaDictionaryIndex(cocoaDictionary, allKeys, currentKeyIndex + 1)
}
}
extension _CocoaDictionaryIndex {
@inlinable // FIXME(sil-serialize-all)
internal static func < (
lhs: _CocoaDictionaryIndex,
rhs: _CocoaDictionaryIndex
) -> Bool {
return lhs.currentKeyIndex < rhs.currentKeyIndex
}
@inlinable // FIXME(sil-serialize-all)
internal static func <= (
lhs: _CocoaDictionaryIndex,
rhs: _CocoaDictionaryIndex
) -> Bool {
return lhs.currentKeyIndex <= rhs.currentKeyIndex
}
@inlinable // FIXME(sil-serialize-all)
internal static func > (
lhs: _CocoaDictionaryIndex,
rhs: _CocoaDictionaryIndex
) -> Bool {
return lhs.currentKeyIndex > rhs.currentKeyIndex
}
@inlinable // FIXME(sil-serialize-all)
internal static func >= (
lhs: _CocoaDictionaryIndex,
rhs: _CocoaDictionaryIndex
) -> Bool {
return lhs.currentKeyIndex >= rhs.currentKeyIndex
}
@inlinable // FIXME(sil-serialize-all)
internal static func == (
lhs: _CocoaDictionaryIndex,
rhs: _CocoaDictionaryIndex
) -> Bool {
return lhs.currentKeyIndex == rhs.currentKeyIndex
}
}
#endif
@_frozen // FIXME(sil-serialize-all)
@usableFromInline // FIXME(sil-serialize-all)
internal enum DictionaryIndexRepresentation<Key: Hashable, Value> {
typealias _Index = DictionaryIndex<Key, Value>
typealias _NativeIndex = _Index._NativeIndex
#if _runtime(_ObjC)
typealias _CocoaIndex = _Index._CocoaIndex
#endif
case _native(_NativeIndex)
#if _runtime(_ObjC)
case _cocoa(_CocoaIndex)
#endif
}
extension Dictionary {
/// The position of a key-value pair in a dictionary.
///
/// Dictionary has two subscripting interfaces:
///
/// 1. Subscripting with a key, yielding an optional value:
///
/// v = d[k]!
///
/// 2. Subscripting with an index, yielding a key-value pair:
///
/// (k, v) = d[i]
@_fixed_layout // FIXME(sil-serialize-all)
public struct Index: Comparable, Hashable {
// Index for native buffer is efficient. Index for bridged NSDictionary is
// not, because neither NSEnumerator nor fast enumeration support moving
// backwards. Even if they did, there is another issue: NSEnumerator does
// not support NSCopying, and fast enumeration does not document that it is
// safe to copy the state. So, we cannot implement Index that is a value
// type for bridged NSDictionary in terms of Cocoa enumeration facilities.
internal typealias _NativeIndex = _NativeDictionaryIndex<Key, Value>
#if _runtime(_ObjC)
internal typealias _CocoaIndex = _CocoaDictionaryIndex
#endif
@inlinable // FIXME(sil-serialize-all)
internal init(_value: DictionaryIndexRepresentation<Key, Value>) {
self._value = _value
}
@usableFromInline // FIXME(sil-serialize-all)
internal var _value: DictionaryIndexRepresentation<Key, Value>
@inlinable // FIXME(sil-serialize-all)
internal static func _native(_ index: _NativeIndex) -> Index {
return DictionaryIndex(_value: ._native(index))
}
#if _runtime(_ObjC)
@inlinable // FIXME(sil-serialize-all)
internal static func _cocoa(_ index: _CocoaIndex) -> Index {
return DictionaryIndex(_value: ._cocoa(index))
}
#endif
@inlinable // FIXME(sil-serialize-all)
@_transparent
internal var _guaranteedNative: Bool {
return _canBeClass(Key.self) == 0 && _canBeClass(Value.self) == 0
}
@inlinable // FIXME(sil-serialize-all)
@_transparent
internal var _nativeIndex: _NativeIndex {
switch _value {
case ._native(let nativeIndex):
return nativeIndex
#if _runtime(_ObjC)
case ._cocoa:
_sanityCheckFailure("internal error: does not contain a native index")
#endif
}
}
#if _runtime(_ObjC)
@inlinable // FIXME(sil-serialize-all)
@_transparent
internal var _cocoaIndex: _CocoaIndex {
switch _value {
case ._native:
_sanityCheckFailure("internal error: does not contain a Cocoa index")
case ._cocoa(let cocoaIndex):
return cocoaIndex
}
}
#endif
}
}
public typealias DictionaryIndex<Key: Hashable, Value> =
Dictionary<Key, Value>.Index
extension Dictionary.Index {
@inlinable // FIXME(sil-serialize-all)
public static func == (
lhs: Dictionary<Key, Value>.Index,
rhs: Dictionary<Key, Value>.Index
) -> Bool {
if _fastPath(lhs._guaranteedNative) {
return lhs._nativeIndex == rhs._nativeIndex
}
switch (lhs._value, rhs._value) {
case (._native(let lhsNative), ._native(let rhsNative)):
return lhsNative == rhsNative
#if _runtime(_ObjC)
case (._cocoa(let lhsCocoa), ._cocoa(let rhsCocoa)):
return lhsCocoa == rhsCocoa
default:
_preconditionFailure("Comparing indexes from different sets")
#endif
}
}
@inlinable // FIXME(sil-serialize-all)
public static func < (
lhs: Dictionary<Key, Value>.Index,
rhs: Dictionary<Key, Value>.Index
) -> Bool {
if _fastPath(lhs._guaranteedNative) {
return lhs._nativeIndex < rhs._nativeIndex
}
switch (lhs._value, rhs._value) {
case (._native(let lhsNative), ._native(let rhsNative)):
return lhsNative < rhsNative
#if _runtime(_ObjC)
case (._cocoa(let lhsCocoa), ._cocoa(let rhsCocoa)):
return lhsCocoa < rhsCocoa
default:
_preconditionFailure("Comparing indexes from different sets")
#endif
}
}
@inlinable
public func hash(into hasher: inout Hasher) {
#if _runtime(_ObjC)
if _fastPath(_guaranteedNative) {
hasher.combine(0 as UInt8)
hasher.combine(_nativeIndex.offset)
return
}
switch _value {
case ._native(let nativeIndex):
hasher.combine(0 as UInt8)
hasher.combine(nativeIndex.offset)
case ._cocoa(let cocoaIndex):
hasher.combine(1 as UInt8)
hasher.combine(cocoaIndex.currentKeyIndex)
}
#else
hasher.combine(_nativeIndex.offset)
#endif
}
}
#if _runtime(_ObjC)
@_fixed_layout // FIXME(sil-serialize-all)
@usableFromInline
final internal class _CocoaDictionaryIterator: IteratorProtocol {
internal typealias Element = (AnyObject, AnyObject)
// Cocoa Dictionary iterator has to be a class, otherwise we cannot
// guarantee that the fast enumeration struct is pinned to a certain memory
// location.
// This stored property should be stored at offset zero. There's code below
// relying on this.
@usableFromInline // FIXME(sil-serialize-all)
internal var _fastEnumerationState: _SwiftNSFastEnumerationState =
_makeSwiftNSFastEnumerationState()
// This stored property should be stored right after `_fastEnumerationState`.
// There's code below relying on this.
@usableFromInline // FIXME(sil-serialize-all)
internal var _fastEnumerationStackBuf = _CocoaFastEnumerationStackBuf()
@usableFromInline // FIXME(sil-serialize-all)
internal let cocoaDictionary: _NSDictionary
@inlinable // FIXME(sil-serialize-all)
internal var _fastEnumerationStatePtr:
UnsafeMutablePointer<_SwiftNSFastEnumerationState> {
return _getUnsafePointerToStoredProperties(self).assumingMemoryBound(
to: _SwiftNSFastEnumerationState.self)
}
@inlinable // FIXME(sil-serialize-all)
internal var _fastEnumerationStackBufPtr:
UnsafeMutablePointer<_CocoaFastEnumerationStackBuf> {
return UnsafeMutableRawPointer(_fastEnumerationStatePtr + 1)
.assumingMemoryBound(to: _CocoaFastEnumerationStackBuf.self)
}
// These members have to be word-sized integers, they cannot be limited to
// Int8 just because our storage holds 16 elements: fast enumeration is
// allowed to return inner pointers to the container, which can be much
// larger.
@usableFromInline // FIXME(sil-serialize-all)
internal var itemIndex: Int = 0
@usableFromInline // FIXME(sil-serialize-all)
internal var itemCount: Int = 0
@inlinable // FIXME(sil-serialize-all)
internal init(_ cocoaDictionary: _NSDictionary) {
self.cocoaDictionary = cocoaDictionary
}
@inlinable // FIXME(sil-serialize-all)
internal func next() -> Element? {
if itemIndex < 0 {
return nil
}
let cocoaDictionary = self.cocoaDictionary
if itemIndex == itemCount {
let stackBufCount = _fastEnumerationStackBuf.count
// We can't use `withUnsafeMutablePointer` here to get pointers to
// properties, because doing so might introduce a writeback storage, but
// fast enumeration relies on the pointer identity of the enumeration
// state struct.
itemCount = cocoaDictionary.countByEnumerating(
with: _fastEnumerationStatePtr,
objects: UnsafeMutableRawPointer(_fastEnumerationStackBufPtr)
.assumingMemoryBound(to: AnyObject.self),
count: stackBufCount)
if itemCount == 0 {
itemIndex = -1
return nil
}
itemIndex = 0
}
let itemsPtrUP =
UnsafeMutableRawPointer(_fastEnumerationState.itemsPtr!)
.assumingMemoryBound(to: AnyObject.self)
let itemsPtr = _UnmanagedAnyObjectArray(itemsPtrUP)
let key: AnyObject = itemsPtr[itemIndex]
itemIndex += 1
let value: AnyObject = cocoaDictionary.objectFor(key)!
return (key, value)
}
}
#endif
@usableFromInline
@_frozen // FIXME(sil-serialize-all)
internal enum DictionaryIteratorRepresentation<Key: Hashable, Value> {
internal typealias _Iterator = DictionaryIterator<Key, Value>
internal typealias _NativeBuffer =
_NativeDictionaryBuffer<Key, Value>
internal typealias _NativeIndex = _Iterator._NativeIndex
// For native buffer, we keep two indices to keep track of the iteration
// progress and the buffer owner to make the buffer non-uniquely
// referenced.
//
// Iterator is iterating over a frozen view of the collection
// state, so it should keep its own reference to the buffer.
case _native(
start: _NativeIndex, end: _NativeIndex, buffer: _NativeBuffer)
#if _runtime(_ObjC)
case _cocoa(_CocoaDictionaryIterator)
#endif
}
/// An iterator over the members of a `Dictionary<Key, Value>`.
@_fixed_layout // FIXME(sil-serialize-all)
public struct DictionaryIterator<Key: Hashable, Value>: IteratorProtocol {
// Dictionary has a separate IteratorProtocol and Index because of efficiency
// and implementability reasons.
//
// Index for native buffer is efficient. Index for bridged NSDictionary is
// not.
//
// Even though fast enumeration is not suitable for implementing
// Index, which is multi-pass, it is suitable for implementing a
// IteratorProtocol, which is being consumed as iteration proceeds.
internal typealias _NativeBuffer =
_NativeDictionaryBuffer<Key, Value>
internal typealias _NativeIndex = _NativeDictionaryIndex<Key, Value>
@usableFromInline
internal var _state: DictionaryIteratorRepresentation<Key, Value>
@inlinable // FIXME(sil-serialize-all)
internal init(_state: DictionaryIteratorRepresentation<Key, Value>) {
self._state = _state
}
@inlinable // FIXME(sil-serialize-all)
internal static func _native(
start: _NativeIndex, end: _NativeIndex, buffer: _NativeBuffer
) -> DictionaryIterator {
return DictionaryIterator(
_state: ._native(start: start, end: end, buffer: buffer))
}
#if _runtime(_ObjC)
@inlinable // FIXME(sil-serialize-all)
internal static func _cocoa(
_ iterator: _CocoaDictionaryIterator
) -> DictionaryIterator{
return DictionaryIterator(_state: ._cocoa(iterator))
}
#endif
@inlinable // FIXME(sil-serialize-all)
@_transparent
internal var _guaranteedNative: Bool {
return _canBeClass(Key.self) == 0 || _canBeClass(Value.self) == 0
}
@inlinable // FIXME(sil-serialize-all)
internal mutating func _nativeNext() -> (key: Key, value: Value)? {
switch _state {
case ._native(let startIndex, let endIndex, let buffer):
if startIndex == endIndex {
return nil
}
let result = buffer.assertingGet(startIndex)
_state =
._native(start: buffer.index(after: startIndex), end: endIndex, buffer: buffer)
return result
#if _runtime(_ObjC)
case ._cocoa:
_sanityCheckFailure("internal error: not backed by NSDictionary")
#endif
}
}
/// Advances to the next element and returns it, or `nil` if no next element
/// exists.
///
/// Once `nil` has been returned, all subsequent calls return `nil`.
@inlinable // FIXME(sil-serialize-all)
@inline(__always)
public mutating func next() -> (key: Key, value: Value)? {
if _fastPath(_guaranteedNative) {
return _nativeNext()
}
switch _state {
case ._native:
return _nativeNext()
#if _runtime(_ObjC)
case ._cocoa(let cocoaIterator):
if let (anyObjectKey, anyObjectValue) = cocoaIterator.next() {
let nativeKey = _forceBridgeFromObjectiveC(anyObjectKey, Key.self)
let nativeValue = _forceBridgeFromObjectiveC(anyObjectValue, Value.self)
return (nativeKey, nativeValue)
}
return nil
#endif
}
}
}
extension DictionaryIterator: CustomReflectable {
/// A mirror that reflects the iterator.
@inlinable // FIXME(sil-serialize-all)
public var customMirror: Mirror {
return Mirror(
self,
children: EmptyCollection<(label: String?, value: Any)>())
}
}
extension Dictionary: CustomReflectable {
/// A mirror that reflects the dictionary.
@inlinable // FIXME(sil-serialize-all)
public var customMirror: Mirror {
let style = Mirror.DisplayStyle.dictionary
return Mirror(self, unlabeledChildren: self, displayStyle: style)
}
}
/// Initializes a `Dictionary` from unique members.
///
/// Using a builder can be faster than inserting members into an empty
/// `Dictionary`.
@_fixed_layout // FIXME(sil-serialize-all)
public struct _DictionaryBuilder<Key: Hashable, Value> {
@usableFromInline // FIXME(sil-serialize-all)
internal var _result: Dictionary<Key, Value>
@usableFromInline // FIXME(sil-serialize-all)
internal var _nativeBuffer: _NativeDictionaryBuffer<Key, Value>
@usableFromInline // FIXME(sil-serialize-all)
internal let _requestedCount: Int
@usableFromInline // FIXME(sil-serialize-all)
internal var _actualCount: Int
@inlinable // FIXME(sil-serialize-all)
public init(count: Int) {
_result = Dictionary<Key, Value>(minimumCapacity: count)
_nativeBuffer = _result._variantBuffer.asNative
_requestedCount = count
_actualCount = 0
}
@inlinable // FIXME(sil-serialize-all)
public mutating func add(key newKey: Key, value: Value) {
_nativeBuffer.unsafeAddNew(key: newKey, value: value)
_actualCount += 1
}
@inlinable // FIXME(sil-serialize-all)
public mutating func take() -> Dictionary<Key, Value> {
_precondition(_actualCount >= 0,
"Cannot take the result twice")
_precondition(_actualCount == _requestedCount,
"The number of members added does not match the promised count")
// Finish building the `Dictionary`.
_nativeBuffer.count = _requestedCount
// Prevent taking the result twice.
_actualCount = -1
return _result
}
}
extension Dictionary {
/// Removes and returns the first key-value pair of the dictionary if the
/// dictionary isn't empty.
///
/// The first element of the dictionary is not necessarily the first element
/// added. Don't expect any particular ordering of key-value pairs.
///
/// - Returns: The first key-value pair of the dictionary if the dictionary
/// is not empty; otherwise, `nil`.
///
/// - Complexity: Averages to O(1) over many calls to `popFirst()`.
@inlinable
public mutating func popFirst() -> Element? {
guard !isEmpty else { return nil }
return remove(at: startIndex)
}
@inlinable
@available(swift, obsoleted: 4.0)
public func filter(
_ isIncluded: (Element) throws -> Bool, obsoletedInSwift4: () = ()
) rethrows -> [Element] {
var result: [Element] = []
for x in self {
if try isIncluded(x) {
result.append(x)
}
}
return result
}
/// The total number of key-value pairs that the dictionary can contain without
/// allocating new storage.
@inlinable // FIXME(sil-serialize-all)
public var capacity: Int {
return _variantBuffer.capacity
}
/// Reserves enough space to store the specified number of key-value pairs.
///
/// If you are adding a known number of key-value pairs to a dictionary, use this
/// method to avoid multiple reallocations. This method ensures that the
/// dictionary has unique, mutable, contiguous storage, with space allocated
/// for at least the requested number of key-value pairs.
///
/// Calling the `reserveCapacity(_:)` method on a dictionary with bridged
/// storage triggers a copy to contiguous storage even if the existing
/// storage has room to store `minimumCapacity` key-value pairs.
///
/// - Parameter minimumCapacity: The requested number of key-value pairs to
/// store.
@inlinable // FIXME(sil-serialize-all)
public mutating func reserveCapacity(_ minimumCapacity: Int) {
_variantBuffer.reserveCapacity(minimumCapacity)
_sanityCheck(self.capacity >= minimumCapacity)
}
}
//===--- Bridging ---------------------------------------------------------===//
#if _runtime(_ObjC)
extension Dictionary {
@inlinable // FIXME(sil-serialize-all)
public func _bridgeToObjectiveCImpl() -> _NSDictionaryCore {
switch _variantBuffer {
case _VariantDictionaryBuffer.native(let buffer):
return buffer.bridged()
case _VariantDictionaryBuffer.cocoa(let cocoaBuffer):
return cocoaBuffer.cocoaDictionary
}
}
/// Returns the native Dictionary hidden inside this NSDictionary;
/// returns nil otherwise.
@inlinable // FIXME(sil-serialize-all)
public static func _bridgeFromObjectiveCAdoptingNativeStorageOf(
_ s: AnyObject
) -> Dictionary<Key, Value>? {
// Try all three NSDictionary impls that we currently provide.
if let deferredBuffer = s as? _SwiftDeferredNSDictionary<Key, Value> {
return Dictionary(_nativeBuffer: deferredBuffer.nativeBuffer)
}
if let nativeStorage = s as? _HashableTypedNativeDictionaryStorage<Key, Value> {
return Dictionary(_nativeBuffer:
_NativeDictionaryBuffer(_storage: nativeStorage))
}
if s === _RawNativeDictionaryStorage.empty {
return Dictionary()
}
// FIXME: what if `s` is native storage, but for different key/value type?
return nil
}
}
#endif
|
apache-2.0
|
4cb4c0d776446d7eb14d1b1bcb53def9
| 33.094152 | 126 | 0.668083 | 4.262894 | false | false | false | false |
msdgwzhy6/Just
|
JustTests/JustSpecs.swift
|
1
|
30709
|
//
// JustTests.swift
// JustTests
//
// Created by Daniel Duan on 4/21/15.
// Copyright (c) 2015 JustHTTP. All rights reserved.
//
import Just
import Nimble
import Quick
class JustSpec: QuickSpec {
override func spec() {
describe("URL query string") {
it("should download a photo ok") {
var count: Int = 0
let r = Just.get("http://www.math.mcgill.ca/triples/Barr-Wells-ctcs.pdf", asyncProgressHandler:{(p) in
count += 1
})
expect(r.ok).to(beTrue())
expect(count).toEventuallyNot(equal(0))
}
it("should sends simple query string specified for GET") {
let r = Just.get("http://httpbin.org/get", params:["a":1])
expect(r.json).toNot(beNil())
if let jsonData = r.json as? [String:AnyObject] {
expect(jsonData["args"]).toNot(beNil())
if let args = jsonData["args"] as? [String:String] {
expect(args).to(equal(["a":"1"]))
}
}
}
it("should sends compound query string specified for GET") {
let r = Just.get("http://httpbin.org/get", params:["a":[1,2]])
expect(r.json).toNot(beNil())
if let jsonData = r.json as? [String:AnyObject] {
expect(jsonData["args"]).toNot(beNil())
if let args = jsonData["args"] as? [String:String] {
expect(args).to(equal(["a":["1", "2"]]))
}
}
}
it("should sends simple query string specified for POST") {
let r = Just.post("http://httpbin.org/post", params:["a":1])
expect(r.json).toNot(beNil())
if let jsonData = r.json as? [String:AnyObject] {
expect(jsonData["args"]).toNot(beNil())
if let args = jsonData["args"] as? [String:String] {
expect(args).to(equal(["a":"1"]))
}
}
}
it("should sends compound query string specified for POST") {
let r = Just.post("http://httpbin.org/post", params:["a":[1,2]])
expect(r.json).toNot(beNil())
if let jsonData = r.json as? [String:AnyObject] {
expect(jsonData["args"]).toNot(beNil())
if let args = jsonData["args"] as? [String:String] {
expect(args).to(equal(["a":["1", "2"]]))
}
}
}
}
describe("sending url query as http body") {
it("should add x-www-form-urlencoded header automatically when body is in url format") {
let r = Just.post("http://httpbin.org/post", data:["a":1])
expect(r.json).toNot(beNil())
if let jsonData = r.json as? [String:AnyObject] {
expect(jsonData["headers"]).toNot(beNil())
if let headers = jsonData["headers"] as? [String:String] {
expect(headers["Content-Type"]).toNot(beNil())
if let contentType = headers["Content-Type"] {
expect(contentType).to(equal("application/x-www-form-urlencoded"))
}
}
}
}
// This is a case seemingly possible with python-requests but NSURLSession can not handle
//it("should add x-www-form-urlencoded header automatically when body is in url format, even for GET requests") {
//let r = Just.get("http://httpbin.org/get", data:["a":1])
//if let jsonData = r.json as? [String:AnyObject],
//let headers = jsonData["headers"] as? [String:String],
//let contentType = headers["Content-Type"] {
//expect(contentType).to(equal("application/x-www-form-urlencoded"))
//} else {
//fail("expected header was not sent")
//}
//}
it("should send simple form url query when asked so") {
let r = Just.post("http://httpbin.org/post", data:["a":1])
expect(r.json).toNot(beNil())
if let jsonData = r.json as? [String:AnyObject] {
expect(jsonData["form"]).toNot(beNil())
if let form = jsonData["form"] as? [String:String] {
expect(form).to(equal(["a":"1"]))
}
}
}
it("should send compound form url query when asked so") {
let r = Just.post("http://httpbin.org/post", data:["a":[1,2]])
expect(r.json).toNot(beNil())
if let jsonData = r.json as? [String:AnyObject] {
expect(jsonData["form"]).toNot(beNil())
if let form = jsonData["form"] as? [String:String] {
expect(form).to(equal(["a":["1","2"]]))
}
}
}
}
describe("redirect") {
it("should redirect by default") {
let r = Just.get("http://httpbin.org/redirect/2")
expect(r.statusCode).to(equal(200))
expect(r.statusCode).toNot(equal(302))
}
it("should redirect when asked to do so") {
let r = Just.get("http://httpbin.org/redirect/2", allowRedirects:true)
expect(r.statusCode).to(equal(200))
expect(r.statusCode).toNot(equal(302))
}
it("should not redircet when asked to do so") {
let r = Just.get("http://httpbin.org/redirect/2", allowRedirects:false)
expect(r.statusCode).toNot(equal(200))
expect(r.statusCode).to(equal(302))
}
it("should report isRedirect as false when it performs redirect") {
expect(Just.get("http://httpbin.org/redirect/2").isRedirect).to(beFalse())
}
it("should report isRedirect as true when it encounters redirect") {
expect(Just.get("http://httpbin.org/redirect/2", allowRedirects:false).isRedirect).to(beTrue())
}
it("should report isPermanentRedirect as false when it performs redirect") {
expect(Just.get("http://httpbin.org/redirect/2").isPermanentRedirect).to(beFalse())
}
it("should report isPermanentRedirect as false when it encounters non permanent redirect") {
let r = Just.get("http://httpbin.org/status/302", allowRedirects:false)
expect(r.isRedirect).to(beTrue())
expect(r.isPermanentRedirect).to(beFalse())
}
it("should report isPermanentRedirect as true when it encounters permanent redirect") {
let r = Just.get("http://httpbin.org/status/301", allowRedirects:false)
expect(r.isRedirect).to(beTrue())
expect(r.isPermanentRedirect).to(beTrue())
}
}
describe("JSON sending") {
it("should not add JSON header when no JSON is supplied") {
let r = Just.post("http://httpbin.org/post", data:["A":"a"])
expect(r.json).toNot(beNil())
if let jsonData = r.json as? [String:AnyObject] {
expect(jsonData["headers"]).toNot(beNil())
if let headers = jsonData["headers"] as? [String:String] {
expect(headers["Content-Type"]).toNot(beNil())
if let contentType = headers["Content-Type"] {
expect(contentType).toNot(equal("application/json"))
}
}
}
}
it("should add JSON header even if an empty argument is set") {
let r = Just.post("http://httpbin.org/post", json:[:])
expect(r.json).toNot(beNil())
if let jsonData = r.json as? [String:AnyObject] {
expect(jsonData["headers"]).toNot(beNil())
if let headers = jsonData["headers"] as? [String:String] {
expect(headers["Content-Type"]).toNot(beNil())
if let contentType = headers["Content-Type"] {
expect(contentType).to(equal("application/json"))
}
}
}
}
it("should send flat JSON data in JSON format") {
let r = Just.post("http://httpbin.org/post", json:["a":1])
expect(r.json).toNot(beNil())
if let data = r.json as? [String:AnyObject] {
expect(data["json"]).toNot(beNil())
if let JSONInData = data["json"] as? [String:Int] {
expect(JSONInData).to(equal(["a":1]))
}
}
}
it("should send compound JSON data in JSON format") {
let r = Just.post("http://httpbin.org/post", json:["a":[1, "b"]])
expect(r.json).toNot(beNil())
if let data = r.json as? [String:AnyObject] {
expect(data["json"]).toNot(beNil())
if let JSONInData = data["json"] as? [String:[AnyObject]] {
expect(JSONInData).to(equal(["a":[1,"b"]]))
}
}
}
it("JSON argument should override data directive") {
let r = Just.post("http://httpbin.org/post", data:["b":2], json:["a":1])
expect(r.json).toNot(beNil())
if let data = r.json as? [String:AnyObject] {
expect(data["json"]).toNot(beNil())
if let JSONInData = data["json"] as? [String:Int] {
expect(JSONInData).to(equal(["a":1]))
expect(JSONInData).toNot(equal(["b":2]))
}
expect(data["data"]).toNot(beNil())
if let dataInData = data["data"] as? [String:Int] {
expect(dataInData).to(equal(["a":1]))
expect(dataInData).toNot(equal(["b":2]))
}
expect(data["headers"]).toNot(beNil())
if let headersInData = data["headers"] as? [String:String] {
expect(headersInData["Content-Type"]).toNot(beNil())
if let contentType = headersInData["Content-Type"] {
expect(contentType).to(equal("application/json"))
}
}
}
}
}
describe("sending files") {
it("should not include a multipart header when empty files were specified") {
let r = Just.post("http://httpbin.org/post", files:[:])
expect(r.json).toNot(beNil())
if let data = r.json as? [String:AnyObject] {
expect(data["headers"]).toNot(beNil())
if let headersInData = data["headers"] as? [String:String] {
if let contentType = headersInData["Content-Type"] {
expect(contentType).toNot(beginWith("multipart/form-data; boundary="))
}
}
}
}
it("should be able to send a single file specified by URL without mimetype") {
if let elonPhotoURL = NSBundle(forClass: JustSpec.self).URLForResource("elon", withExtension:"jpg") {
let r = Just.post("http://httpbin.org/post", files:["elon":.URL(elonPhotoURL,nil)])
expect(r.json).toNot(beNil())
if let data = r.json as? [String:AnyObject] {
expect(data["files"]).toNot(beNil())
if let files = data["files"] as? [String:String] {
expect(files["elon"]).toNot(beNil())
}
}
} else {
fail("resource needed for this test can't be found")
}
}
it("should be able to send a single file specified by URL and mimetype") {
if let elonPhotoURL = NSBundle(forClass: JustSpec.self).URLForResource("elon", withExtension:"jpg") {
let r = Just.post("http://httpbin.org/post", files:["elon":.URL(elonPhotoURL, "image/jpeg")])
expect(r.json).toNot(beNil())
if let data = r.json as? [String:AnyObject] {
expect(data["files"]).toNot(beNil())
if let files = data["files"] as? [String:String] {
expect(files["elon"]).toNot(beNil())
}
}
} else {
fail("resource needed for this test can't be found")
}
}
it("should be able to send a single file specified by data without mimetype") {
if let dataToSend = "haha not really".dataUsingEncoding(NSUTF8StringEncoding) {
let r = Just.post("http://httpbin.org/post", files:["elon":.Data("JustTests.swift", dataToSend, nil)])
expect(r.json).toNot(beNil())
if let data = r.json as? [String:AnyObject] {
expect(data["files"]).toNot(beNil())
if let files = data["files"] as? [String:String] {
expect(files["elon"]).toNot(beNil())
}
}
} else {
fail("can't encode text as data")
}
}
it("should be able to send a single file specified by data and mimetype") {
if let dataToSend = "haha not really".dataUsingEncoding(NSUTF8StringEncoding) {
let r = Just.post("http://httpbin.org/post", files:["elon":.Data("JustTests.swift", dataToSend, "text/plain")])
expect(r.json).toNot(beNil())
if let data = r.json as? [String:AnyObject] {
expect(data["files"]).toNot(beNil())
if let files = data["files"] as? [String:String] {
expect(files["elon"]).toNot(beNil())
}
}
} else {
fail("can't encode text as data")
}
}
it("should be able to send a single file specified by text without mimetype") {
let r = Just.post("http://httpbin.org/post", files:["test":.Text("JustTests.swift", "haha not really", nil)])
expect(r.json).toNot(beNil())
if let data = r.json as? [String:AnyObject] {
expect(data["files"]).toNot(beNil())
if let files = data["files"] as? [String:String] {
expect(files["test"]).toNot(beNil())
}
}
}
it("should be able to send a single file specified by text and mimetype") {
let r = Just.post("http://httpbin.org/post", files:["test":.Text("JustTests.swift", "haha not really", "text/plain")])
expect(r.json).toNot(beNil())
if let data = r.json as? [String:AnyObject] {
expect(data["files"]).toNot(beNil())
if let files = data["files"] as? [String:String] {
expect(files["test"]).toNot(beNil())
}
}
}
it("should be able to send multiple files specified the same way") {
let r = Just.post(
"http://httpbin.org/post",
files:[
"elon1": .Text("JustTests.swift", "haha not really", nil),
"elon2": .Text("JustTests.swift", "haha not really", nil),
"elon3": .Text("JustTests.swift", "haha not really", nil),
]
)
expect(r.json).toNot(beNil())
if let data = r.json as? [String:AnyObject] {
expect(data["files"]).toNot(beNil())
if let files = data["files"] as? [String:String] {
expect(files["elon1"]).toNot(beNil())
expect(files["elon2"]).toNot(beNil())
expect(files["elon3"]).toNot(beNil())
}
}
}
it("should be able to send multiple files specified in different ways") {
if let dataToSend = "haha not really".dataUsingEncoding(NSUTF8StringEncoding) {
let r = Just.post(
"http://httpbin.org/post",
files: [
"elon1": .Text("JustTests.swift", "haha not really", nil),
"elon2": .Data("JustTests.swift", dataToSend, nil)
]
)
expect(r.json).toNot(beNil())
if let data = r.json as? [String:AnyObject] {
expect(data["files"]).toNot(beNil())
if let files = data["files"] as? [String:String] {
expect(files["elon1"]).toNot(beNil())
expect(files["elon2"]).toNot(beNil())
}
}
} else {
fail("can't encode text as data")
}
}
it("should be able to send a file along with some data") {
let r = Just.post(
"http://httpbin.org/post",
data:["a":1, "b":2],
files:[
"elon1": .Text("JustTests.swift", "haha not really", nil),
]
)
expect(r.json).toNot(beNil())
if let data = r.json as? [String:AnyObject] {
expect(data["files"]).toNot(beNil())
if let files = data["files"] as? [String:String] {
expect(files["elon1"]).toNot(beNil())
}
expect(data["form"]).toNot(beNil())
if let form = data["form"] as? [String:String] {
expect(form).to(equal(["a":"1", "b":"2"]))
}
}
}
it("should be able to send multiple files along with some data") {
if let dataToSend = "haha not really".dataUsingEncoding(NSUTF8StringEncoding) {
let r = Just.post(
"http://httpbin.org/post",
data:["a":1, "b":2],
files: [
"elon1": .Text("JustTests.swift", "haha not really", nil),
"elon2": .Data("JustTests.swift", dataToSend, nil)
]
)
expect(r.json).toNot(beNil())
if let data = r.json as? [String:AnyObject] {
expect(data["files"]).toNot(beNil())
if let files = data["files"] as? [String:String] {
expect(files["elon1"]).toNot(beNil())
expect(files["elon2"]).toNot(beNil())
}
expect(data["form"]).toNot(beNil())
if let form = data["form"] as? [String:String] {
expect(form).to(equal(["a":"1", "b":"2"]))
}
}
} else {
fail("can't encode text as data")
}
}
it("should override JSON when files are specified") {
if let dataToSend = "haha not really".dataUsingEncoding(NSUTF8StringEncoding) {
let r = Just.post(
"http://httpbin.org/post",
json:["a":1, "b":2],
files: [
"elon1": .Text("JustTests.swift", "haha not really", nil),
"elon2": .Data("JustTests.swift", dataToSend, nil)
]
)
expect(r.json).toNot(beNil())
if let data = r.json as? [String:AnyObject] {
expect(data["json"]).toNot(beNil())
if let json = data["json"] as? NSNull {
expect(json).to(beAnInstanceOf(NSNull))
}
expect(data["files"]).toNot(beNil())
if let files = data["files"] as? [String:String] {
expect(files["elon1"]).toNot(beNil())
expect(files["elon2"]).toNot(beNil())
}
expect(data["form"]).toNot(beNil())
if let form = data["form"] as? [String:String] {
expect(form).to(equal([:]))
}
}
} else {
fail("can't encode text as data")
}
}
}
describe("result url") {
it("should contain url from the response") {
let targetURLString = "http://httpbin.org/get"
let r = Just.get(targetURLString)
expect(r.url).toNot(beNil())
if let urlString = r.url?.absoluteString {
expect(urlString).to(equal(targetURLString))
}
}
}
describe("result ok-ness") {
it("should be ok with non-error status codes") {
expect(Just.get("http://httpbin.org/status/200").ok).to(beTrue())
expect(Just.get("http://httpbin.org/status/299").ok).to(beTrue())
expect(Just.get("http://httpbin.org/status/302", allowRedirects:false).ok).to(beTrue())
}
it("should not be ok with 4xx status codes") {
expect(Just.get("http://httpbin.org/status/400").ok).toNot(beTrue())
expect(Just.get("http://httpbin.org/status/401").ok).toNot(beTrue())
expect(Just.get("http://httpbin.org/status/404").ok).toNot(beTrue())
expect(Just.get("http://httpbin.org/status/499").ok).toNot(beTrue())
}
it("should not be ok with 5xx status codes") {
expect(Just.get("http://httpbin.org/status/500").ok).toNot(beTrue())
expect(Just.get("http://httpbin.org/status/501").ok).toNot(beTrue())
expect(Just.get("http://httpbin.org/status/599").ok).toNot(beTrue())
}
}
describe("result status code") {
expect(Just.get("http://httpbin.org/status/200").statusCode).to(equal(200))
expect(Just.get("http://httpbin.org/status/302", allowRedirects:false).statusCode).to(equal(302))
expect(Just.get("http://httpbin.org/status/404").statusCode).to(equal(404))
expect(Just.get("http://httpbin.org/status/501").statusCode).to(equal(501))
}
describe("sending headers") {
it("should accept empty header arguments") {
expect(Just.get("http://httpbin.org/get", headers:[:]).ok).to(beTrue())
}
it("should send single conventional header as provided") {
let r = Just.get("http://httpbin.org/get", headers:["Content-Type":"application/json"])
expect(r.json).toNot(beNil())
if let responseData = r.json as? [String:AnyObject] {
expect(responseData["headers"]).toNot(beNil())
if let receivedHeaders = responseData["headers"] as? [String:String] {
expect(receivedHeaders["Content-Type"]).to(equal("application/json"))
}
}
}
it("should send multiple conventional header as provided") {
let r = Just.get("http://httpbin.org/get", headers:["Accept-Language":"*", "Content-Type":"application/json"])
expect(r.json).toNot(beNil())
if let responseData = r.json as? [String:AnyObject] {
expect(responseData["headers"]).toNot(beNil())
if let receivedHeaders = responseData["headers"] as? [String:String] {
expect(receivedHeaders["Content-Type"]).to(equal("application/json"))
expect(receivedHeaders["Accept-Language"]).to(equal("*"))
}
}
}
it("should send multiple arbitrary header as provided") {
let r = Just.get("http://httpbin.org/get", headers:["Winter-is":"coming", "things-know-by-Jon-Snow":"Just42awesome"])
expect(r.json).toNot(beNil())
if let responseData = r.json as? [String:AnyObject] {
expect(responseData["headers"]).toNot(beNil())
if let receivedHeaders = responseData["headers"] as? [String:String] {
expect(receivedHeaders["Winter-Is"]).to(equal("coming"))
expect(receivedHeaders["Things-Know-By-Jon-Snow"]).to(equal("Just42awesome"))
}
}
}
}
describe("basic authentication") {
it("should fail at a challenge when auth is missing") {
let r = Just.get("http://httpbin.org/basic-auth/dan/pass")
expect(r.ok).to(beFalse())
}
it("should succeed at a challenge when auth info is correct") {
let username = "dan"
let password = "password"
let r = Just.get("http://httpbin.org/basic-auth/\(username)/\(password)", auth:(username, password))
expect(r.ok).to(beTrue())
}
it("should fail a challenge when auth contains wrong value") {
let username = "dan"
let password = "password"
let r = Just.get("http://httpbin.org/basic-auth/\(username)/\(password)x", auth:(username, password))
expect(r.ok).to(beFalse())
expect(r.statusCode).to(equal(401))
}
}
describe("digest authentication") {
it("should fail at a challenge when auth is missing") {
let r = Just.get("http://httpbin.org/digest-auth/auth/dan/pass")
expect(r.ok).to(beFalse())
}
it("should succeed at a challenge when auth info is correct") {
let username = "dan"
let password = "password"
let r = Just.get("http://httpbin.org/digest-auth/auth/\(username)/\(password)", auth:(username, password))
expect(r.ok).to(beTrue())
}
it("should fail a challenge when auth contains wrong value") {
let username = "dan"
let password = "password"
let r = Just.get("http://httpbin.org/digest-auth/auth/\(username)/\(password)x", auth:(username, password))
expect(r.ok).to(beFalse())
expect(r.statusCode).to(equal(401))
}
}
describe("cookies") {
it("should get cookies contained in responses") {
let r = Just.get("http://httpbin.org/cookies/set/test/just", allowRedirects:false)
expect(r.cookies).toNot(beEmpty())
expect(r.cookies.keys.array).to(contain("test"))
if let cookie = r.cookies["test"] {
expect(cookie.value).to(equal("just"))
}
}
it("sends cookies in specified in requests") {
Just.get("http://httpbin.org/cookies/delete?test")
let r = Just.get("http://httpbin.org/cookies", cookies:["test":"just"])
expect(r.json).toNot(beNil())
if let jsonData = r.json as? [String:AnyObject] {
expect((jsonData["cookies"] as? [String:String])?["test"]).toNot(beNil())
if let cookieValue = (jsonData["cookies"] as? [String:String])?["test"] {
expect(cookieValue).to(equal("just"))
}
}
}
}
describe("supported request types") {
it("should include OPTIONS") {
expect(Just.options("http://httpbin.org/get").ok).to(beTrue())
}
it("should include HEAD") {
expect(Just.head("http://httpbin.org/get").ok).to(beTrue())
}
it("should include GET") {
expect(Just.get("http://httpbin.org/get").ok).to(beTrue())
}
it("should include HEAD") {
expect(Just.head("http://httpbin.org/get").ok).to(beTrue())
}
it("should include POST") {
expect(Just.post("http://httpbin.org/post").ok).to(beTrue())
}
it("should include PUT") {
expect(Just.put("http://httpbin.org/put").ok).to(beTrue())
}
it("should include PATCH") {
expect(Just.patch("http://httpbin.org/patch").ok).to(beTrue())
}
it("should include DELETE") {
expect(Just.delete("http://httpbin.org/delete").ok).to(beTrue())
}
}
describe("timeout") {
it("should timeout when response is taking longer than specified") {
let r = Just.get("http://httpbin.org/delay/10", timeout:0.5)
expect(r.ok).to(beFalse())
}
it("should not timeout when response is taking shorter than specified") {
let r = Just.get("http://httpbin.org/delay/1", timeout:2)
expect(r.ok).to(beTrue())
}
}
}
}
|
mit
|
074de3ca9f9090c174aba36a6f035f68
| 46.684783 | 134 | 0.46628 | 4.67057 | false | false | false | false |
faimin/ZDOpenSourceDemo
|
ZDOpenSourceSwiftDemo/Pods/LayoutKit/Sources/Internal/CGSizeExtension.swift
|
2
|
1425
|
// Copyright 2016 LinkedIn Corp.
// 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.
import CoreGraphics
import Foundation
#if os(OSX)
public typealias EdgeInsets = NSEdgeInsets
#endif
extension CGSize {
func increased(by insets: EdgeInsets) -> CGSize {
return CGSize(
width: width + insets.left + insets.right,
height: height + insets.top + insets.bottom)
}
func decreased(by insets: EdgeInsets) -> CGSize {
return CGSize(
width: width - insets.left - insets.right,
height: height - insets.top - insets.bottom)
}
func decreasedToSize(_ maxSize: CGSize) -> CGSize {
let width = min(self.width, maxSize.width)
let height = min(self.height, maxSize.height)
return CGSize(width: width, height: height)
}
func increasedToSize(_ minSize: CGSize) -> CGSize {
let width = max(self.width, minSize.width)
let height = max(self.height, minSize.height)
return CGSize(width: width, height: height)
}
}
|
mit
|
f5a3fb86ebf01c1f594c7f292ffc23ed
| 34.625 | 131 | 0.672982 | 4.228487 | false | false | false | false |
soberman/ARSLineProgress
|
Source/ARSLineProgressConstants.swift
|
3
|
823
|
//
// ARSLineProgressConstants.swift
// ARSLineProgress
//
// Created by Yaroslav Arsenkin on 09/10/2016.
// Copyright © 2016 Iaroslav Arsenkin. All rights reserved.
//
// Website: http://arsenkin.com
//
import UIKit
let ARS_BACKGROUND_VIEW_SIDE_LENGTH: CGFloat = 125.0
let ARS_STATUS_PATH_SIDE_LENGTH: CGFloat = 125.0
let ARS_CIRCLE_ROTATION_TO_VALUE = 2 * CGFloat.pi
let ARS_CIRCLE_ROTATION_REPEAT_COUNT = Float(UINT64_MAX)
let ARS_CIRCLE_RADIUS_OUTER: CGFloat = 40.0
let ARS_CIRCLE_RADIUS_MIDDLE: CGFloat = 30.0
let ARS_CIRCLE_RADIUS_INNER: CGFloat = 20.0
let ARS_CIRCLE_LINE_WIDTH: CGFloat = 2.0
let ARS_CIRCLE_START_ANGLE: CGFloat = -CGFloat.pi / 2
let ARS_CIRCLE_END_ANGLE: CGFloat = 0.0
weak var ars_currentStatus: ARSLoader?
var ars_currentLoader: ARSLoader?
var ars_currentCompletionBlock: (() -> Void)?
|
mit
|
2bb1281a4b3c7cafbf0843bda64859e5
| 29.444444 | 60 | 0.739659 | 3.161538 | false | false | false | false |
EGF2/ios-client
|
TestSwift/TestSwift/MainController.swift
|
1
|
784
|
//
// MainController.swift
// TestSwift
//
// Created by LuzanovRoman on 10.11.16.
// Copyright © 2016 EigenGraph. All rights reserved.
//
import UIKit
class MainController: UIViewController {
@IBAction func logout(_ sender: AnyObject) {
Graph.logout { (_, error) in
if error == nil {
if let controller = self.navigationController as? InitController {
controller.performSegue(withIdentifier: "ShowLoginScreen", sender: nil)
}
}
}
}
override func viewDidDisappear(_ animated: Bool) {
guard let controller = self.navigationController as? InitController else { return }
if !Graph.isAuthorized {
controller.viewControllers = []
}
}
}
|
mit
|
fe36aceef895292f1aef65bf85d66b65
| 25.1 | 91 | 0.601533 | 4.745455 | false | false | false | false |
Caiflower/SwiftWeiBo
|
花菜微博/花菜微博/Classes/Tools(工具)/CFAddition(Swift)/UIKit/UIButton-Addition.swift
|
1
|
4292
|
//
// UIButton-Addition.swift
// 花菜微博
//
// Created by 花菜ChrisCai on 2016/12/4.
// Copyright © 2016年 花菜ChrisCai. All rights reserved.
//
import UIKit
extension UIButton {
/// 创建文本按钮
///
/// - Parameters:
/// - title: 按钮标题
/// - fontSize: 按钮字体大小
/// - color: 按钮普通状态颜色,默认为黑色
/// - highlighterColor: 按钮高亮状态颜色,默认为白色
/// - backgroundImage: 按钮背景图片
convenience init(title: String?, fontSize: CGFloat = 14,color: UIColor = UIColor.black, highlightedColor: UIColor = UIColor.black, imageName: String? = nil, backgroundImageName: String? = nil) {
self.init()
self.setTitle(title, for: .normal)
self.titleLabel?.font = UIFont.systemFont(ofSize: fontSize)
self.setTitleColor(color, for: .normal)
self.setTitleColor(highlightedColor, for: .highlighted)
self.setTitleColor(highlightedColor, for: .selected)
if let imageName = imageName {
self.setImage(UIImage(named:imageName), for: .normal)
self.setImage(UIImage(named:imageName + "_highlighted"), for: .highlighted)
self.setImage(UIImage(named:imageName + "_selected"), for: .selected)
}
if let backgroundImageName = backgroundImageName {
self.setBackgroundImage(UIImage(named:backgroundImageName), for: .normal)
}
self.sizeToFit()
}
/// 创建图片按钮,按钮图片的名字一定要闺房
///
/// - Parameters:
/// - imageName: 普通状态下图片名字
/// - backgroundImageName: 按钮背景图片
convenience init(title: String? = nil,titleColor: UIColor? = UIColor.darkGray,imageName: String, backgroundImageName: String) {
self.init()
self.setTitle(title, for: .normal)
self.setTitleColor(titleColor, for: .normal)
self.setImage(UIImage(named:imageName), for: .normal)
self.setImage(UIImage(named:imageName + "_highlighted"), for: .highlighted)
self.setImage(UIImage(named:imageName + "_selected"), for: .selected)
self.setBackgroundImage(UIImage(named:backgroundImageName), for: .normal)
self.sizeToFit()
}
}
// MARK: - 按钮排版
extension UIButton {
/// 快速排版并重新计算尺寸
///
/// - Parameters:
/// - isHorizontal: 是否是水平排版,默认为水平即文字在左边,图片在右边
/// - margin: 图片与文字之间的间距
func adjustContent(isHorizontal: Bool = true, margin: CGFloat) {
guard let imageSize = self.image(for: .normal)?.size,
let title = self.currentTitle
else {
return
}
// 计算文字尺寸
let titleSize = title.cf_size(font: self.titleLabel!.font)
var tmpRect = self.frame
if isHorizontal {
// 文字左边,图片右边
self.imageEdgeInsets = UIEdgeInsets(top: 0,
left: titleSize.width + margin,
bottom: 0,
right: -titleSize.width)
self.titleEdgeInsets = UIEdgeInsets(top: 0,
left: -imageSize.width,
bottom: -0,
right: imageSize.width + margin)
tmpRect.size.width += margin;
} else {
// 图片上面啊,文字下面
self.imageEdgeInsets = UIEdgeInsets(top: -(titleSize.height + margin),
left: 0,
bottom: 0,
right: -titleSize.width)
self.titleEdgeInsets = UIEdgeInsets(top: 0,
left: -imageSize.width,
bottom: -(imageSize.height + margin),
right: 0)
tmpRect.size.width = max(imageSize.width, titleSize.width);
}
self.frame = tmpRect
}
}
|
apache-2.0
|
533460acaa286ee25d4ae20c7d9637d3
| 37.533981 | 198 | 0.527841 | 4.680425 | false | false | false | false |
Sage-Bionetworks/MoleMapper
|
MoleMapper/Charts/Classes/Data/ChartData.swift
|
1
|
24900
|
//
// ChartData.swift
// Charts
//
// Created by Daniel Cohen Gindi on 23/2/15.
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/ios-charts
//
import Foundation
import UIKit
public class ChartData: NSObject
{
internal var _yMax = Double(0.0)
internal var _yMin = Double(0.0)
internal var _leftAxisMax = Double(0.0)
internal var _leftAxisMin = Double(0.0)
internal var _rightAxisMax = Double(0.0)
internal var _rightAxisMin = Double(0.0)
private var _yValueSum = Double(0.0)
private var _yValCount = Int(0)
/// the last start value used for calcMinMax
internal var _lastStart: Int = 0
/// the last end value used for calcMinMax
internal var _lastEnd: Int = 0
/// the average length (in characters) across all x-value strings
private var _xValAverageLength = Double(0.0)
internal var _xVals: [String?]!
internal var _dataSets: [ChartDataSet]!
public override init()
{
super.init()
_xVals = [String?]()
_dataSets = [ChartDataSet]()
}
public init(xVals: [String?]?, dataSets: [ChartDataSet]?)
{
super.init()
_xVals = xVals == nil ? [String?]() : xVals
_dataSets = dataSets == nil ? [ChartDataSet]() : dataSets
self.initialize(_dataSets)
}
public init(xVals: [NSObject]?, dataSets: [ChartDataSet]?)
{
super.init()
_xVals = xVals == nil ? [String?]() : ChartUtils.bridgedObjCGetStringArray(objc: xVals!)
_dataSets = dataSets == nil ? [ChartDataSet]() : dataSets
self.initialize(_dataSets)
}
public convenience init(xVals: [String?]?)
{
self.init(xVals: xVals, dataSets: [ChartDataSet]())
}
public convenience init(xVals: [NSObject]?)
{
self.init(xVals: xVals, dataSets: [ChartDataSet]())
}
public convenience init(xVals: [String?]?, dataSet: ChartDataSet?)
{
self.init(xVals: xVals, dataSets: dataSet === nil ? nil : [dataSet!])
}
public convenience init(xVals: [NSObject]?, dataSet: ChartDataSet?)
{
self.init(xVals: xVals, dataSets: dataSet === nil ? nil : [dataSet!])
}
internal func initialize(dataSets: [ChartDataSet])
{
checkIsLegal(dataSets)
calcMinMax(start: _lastStart, end: _lastEnd)
calcYValueSum()
calcYValueCount()
calcXValAverageLength()
}
// calculates the average length (in characters) across all x-value strings
internal func calcXValAverageLength()
{
if (_xVals.count == 0)
{
_xValAverageLength = 1
return
}
var sum = 1
for (var i = 0; i < _xVals.count; i++)
{
sum += _xVals[i] == nil ? 0 : (_xVals[i]!).characters.count
}
_xValAverageLength = Double(sum) / Double(_xVals.count)
}
// Checks if the combination of x-values array and DataSet array is legal or not.
// :param: dataSets
internal func checkIsLegal(dataSets: [ChartDataSet]!)
{
if (dataSets == nil)
{
return
}
for (var i = 0; i < dataSets.count; i++)
{
if (dataSets[i].yVals.count > _xVals.count)
{
//print("One or more of the DataSet Entry arrays are longer than the x-values array of this Data object.", appendNewline: true)
return
}
}
}
public func notifyDataChanged()
{
initialize(_dataSets)
}
/// calc minimum and maximum y value over all datasets
internal func calcMinMax(start start: Int, end: Int)
{
if (_dataSets == nil || _dataSets.count < 1)
{
_yMax = 0.0
_yMin = 0.0
}
else
{
_lastStart = start
_lastEnd = end
_yMin = DBL_MAX
_yMax = -DBL_MAX
for (var i = 0; i < _dataSets.count; i++)
{
_dataSets[i].calcMinMax(start: start, end: end)
if (_dataSets[i].yMin < _yMin)
{
_yMin = _dataSets[i].yMin
}
if (_dataSets[i].yMax > _yMax)
{
_yMax = _dataSets[i].yMax
}
}
if (_yMin == DBL_MAX)
{
_yMin = 0.0
_yMax = 0.0
}
// left axis
let firstLeft = getFirstLeft()
if (firstLeft !== nil)
{
_leftAxisMax = firstLeft!.yMax
_leftAxisMin = firstLeft!.yMin
for dataSet in _dataSets
{
if (dataSet.axisDependency == .Left)
{
if (dataSet.yMin < _leftAxisMin)
{
_leftAxisMin = dataSet.yMin
}
if (dataSet.yMax > _leftAxisMax)
{
_leftAxisMax = dataSet.yMax
}
}
}
}
// right axis
let firstRight = getFirstRight()
if (firstRight !== nil)
{
_rightAxisMax = firstRight!.yMax
_rightAxisMin = firstRight!.yMin
for dataSet in _dataSets
{
if (dataSet.axisDependency == .Right)
{
if (dataSet.yMin < _rightAxisMin)
{
_rightAxisMin = dataSet.yMin
}
if (dataSet.yMax > _rightAxisMax)
{
_rightAxisMax = dataSet.yMax
}
}
}
}
// in case there is only one axis, adjust the second axis
handleEmptyAxis(firstLeft, firstRight: firstRight)
}
}
/// calculates the sum of all y-values in all datasets
internal func calcYValueSum()
{
_yValueSum = 0
if (_dataSets == nil)
{
return
}
for (var i = 0; i < _dataSets.count; i++)
{
_yValueSum += fabs(_dataSets[i].yValueSum)
}
}
/// Calculates the total number of y-values across all ChartDataSets the ChartData represents.
internal func calcYValueCount()
{
_yValCount = 0
if (_dataSets == nil)
{
return
}
var count = 0
for (var i = 0; i < _dataSets.count; i++)
{
count += _dataSets[i].entryCount
}
_yValCount = count
}
/// - returns: the number of LineDataSets this object contains
public var dataSetCount: Int
{
if (_dataSets == nil)
{
return 0
}
return _dataSets.count
}
/// - returns: the smallest y-value the data object contains.
public var yMin: Double
{
return _yMin
}
public func getYMin() -> Double
{
return _yMin
}
public func getYMin(axis: ChartYAxis.AxisDependency) -> Double
{
if (axis == .Left)
{
return _leftAxisMin
}
else
{
return _rightAxisMin
}
}
/// - returns: the greatest y-value the data object contains.
public var yMax: Double
{
return _yMax
}
public func getYMax() -> Double
{
return _yMax
}
public func getYMax(axis: ChartYAxis.AxisDependency) -> Double
{
if (axis == .Left)
{
return _leftAxisMax
}
else
{
return _rightAxisMax
}
}
/// - returns: the average length (in characters) across all values in the x-vals array
public var xValAverageLength: Double
{
return _xValAverageLength
}
/// - returns: the total y-value sum across all DataSet objects the this object represents.
public var yValueSum: Double
{
return _yValueSum
}
/// - returns: the total number of y-values across all DataSet objects the this object represents.
public var yValCount: Int
{
return _yValCount
}
/// - returns: the x-values the chart represents
public var xVals: [String?]
{
return _xVals
}
///Adds a new x-value to the chart data.
public func addXValue(xVal: String?)
{
_xVals.append(xVal)
}
/// Removes the x-value at the specified index.
public func removeXValue(index: Int)
{
_xVals.removeAtIndex(index)
}
/// - returns: the array of ChartDataSets this object holds.
public var dataSets: [ChartDataSet]
{
get
{
return _dataSets
}
set
{
_dataSets = newValue
}
}
/// Retrieve the index of a ChartDataSet with a specific label from the ChartData. Search can be case sensitive or not.
///
/// **IMPORTANT: This method does calculations at runtime, do not over-use in performance critical situations.**
///
/// - parameter dataSets: the DataSet array to search
/// - parameter type:
/// - parameter ignorecase: if true, the search is not case-sensitive
/// - returns: the index of the DataSet Object with the given label. Sensitive or not.
internal func getDataSetIndexByLabel(label: String, ignorecase: Bool) -> Int
{
if (ignorecase)
{
for (var i = 0; i < dataSets.count; i++)
{
if (dataSets[i].label == nil)
{
continue
}
if (label.caseInsensitiveCompare(dataSets[i].label!) == NSComparisonResult.OrderedSame)
{
return i
}
}
}
else
{
for (var i = 0; i < dataSets.count; i++)
{
if (label == dataSets[i].label)
{
return i
}
}
}
return -1
}
/// - returns: the total number of x-values this ChartData object represents (the size of the x-values array)
public var xValCount: Int
{
return _xVals.count
}
/// - returns: the labels of all DataSets as a string array.
internal func dataSetLabels() -> [String]
{
var types = [String]()
for (var i = 0; i < _dataSets.count; i++)
{
if (dataSets[i].label == nil)
{
continue
}
types[i] = _dataSets[i].label!
}
return types
}
/// Get the Entry for a corresponding highlight object
///
/// - parameter highlight:
/// - returns: the entry that is highlighted
public func getEntryForHighlight(highlight: ChartHighlight) -> ChartDataEntry?
{
if highlight.dataSetIndex >= dataSets.count
{
return nil
}
else
{
return _dataSets[highlight.dataSetIndex].entryForXIndex(highlight.xIndex)
}
}
/// **IMPORTANT: This method does calculations at runtime. Use with care in performance critical situations.**
///
/// - parameter label:
/// - parameter ignorecase:
/// - returns: the DataSet Object with the given label. Sensitive or not.
public func getDataSetByLabel(label: String, ignorecase: Bool) -> ChartDataSet?
{
let index = getDataSetIndexByLabel(label, ignorecase: ignorecase)
if (index < 0 || index >= _dataSets.count)
{
return nil
}
else
{
return _dataSets[index]
}
}
public func getDataSetByIndex(index: Int) -> ChartDataSet!
{
if (_dataSets == nil || index < 0 || index >= _dataSets.count)
{
return nil
}
return _dataSets[index]
}
public func addDataSet(d: ChartDataSet!)
{
if (_dataSets == nil)
{
return
}
_yValCount += d.entryCount
_yValueSum += d.yValueSum
if (_dataSets.count == 0)
{
_yMax = d.yMax
_yMin = d.yMin
if (d.axisDependency == .Left)
{
_leftAxisMax = d.yMax
_leftAxisMin = d.yMin
}
else
{
_rightAxisMax = d.yMax
_rightAxisMin = d.yMin
}
}
else
{
if (_yMax < d.yMax)
{
_yMax = d.yMax
}
if (_yMin > d.yMin)
{
_yMin = d.yMin
}
if (d.axisDependency == .Left)
{
if (_leftAxisMax < d.yMax)
{
_leftAxisMax = d.yMax
}
if (_leftAxisMin > d.yMin)
{
_leftAxisMin = d.yMin
}
}
else
{
if (_rightAxisMax < d.yMax)
{
_rightAxisMax = d.yMax
}
if (_rightAxisMin > d.yMin)
{
_rightAxisMin = d.yMin
}
}
}
_dataSets.append(d)
handleEmptyAxis(getFirstLeft(), firstRight: getFirstRight())
}
public func handleEmptyAxis(firstLeft: ChartDataSet?, firstRight: ChartDataSet?)
{
// in case there is only one axis, adjust the second axis
if (firstLeft === nil)
{
_leftAxisMax = _rightAxisMax
_leftAxisMin = _rightAxisMin
}
else if (firstRight === nil)
{
_rightAxisMax = _leftAxisMax
_rightAxisMin = _leftAxisMin
}
}
/// Removes the given DataSet from this data object.
/// Also recalculates all minimum and maximum values.
///
/// - returns: true if a DataSet was removed, false if no DataSet could be removed.
public func removeDataSet(dataSet: ChartDataSet!) -> Bool
{
if (_dataSets == nil || dataSet === nil)
{
return false
}
for (var i = 0; i < _dataSets.count; i++)
{
if (_dataSets[i] === dataSet)
{
return removeDataSetByIndex(i)
}
}
return false
}
/// Removes the DataSet at the given index in the DataSet array from the data object.
/// Also recalculates all minimum and maximum values.
///
/// - returns: true if a DataSet was removed, false if no DataSet could be removed.
public func removeDataSetByIndex(index: Int) -> Bool
{
if (_dataSets == nil || index >= _dataSets.count || index < 0)
{
return false
}
let d = _dataSets.removeAtIndex(index)
_yValCount -= d.entryCount
_yValueSum -= d.yValueSum
calcMinMax(start: _lastStart, end: _lastEnd)
return true
}
/// Adds an Entry to the DataSet at the specified index. Entries are added to the end of the list.
public func addEntry(e: ChartDataEntry, dataSetIndex: Int)
{
if (_dataSets != nil && _dataSets.count > dataSetIndex && dataSetIndex >= 0)
{
let val = e.value
let set = _dataSets[dataSetIndex]
if (_yValCount == 0)
{
_yMin = val
_yMax = val
if (set.axisDependency == .Left)
{
_leftAxisMax = e.value
_leftAxisMin = e.value
}
else
{
_rightAxisMax = e.value
_rightAxisMin = e.value
}
}
else
{
if (_yMax < val)
{
_yMax = val
}
if (_yMin > val)
{
_yMin = val
}
if (set.axisDependency == .Left)
{
if (_leftAxisMax < e.value)
{
_leftAxisMax = e.value
}
if (_leftAxisMin > e.value)
{
_leftAxisMin = e.value
}
}
else
{
if (_rightAxisMax < e.value)
{
_rightAxisMax = e.value
}
if (_rightAxisMin > e.value)
{
_rightAxisMin = e.value
}
}
}
_yValCount += 1
_yValueSum += val
handleEmptyAxis(getFirstLeft(), firstRight: getFirstRight())
set.addEntry(e)
}
else
{
print("ChartData.addEntry() - dataSetIndex our of range.", terminator: "\n")
}
}
/// Removes the given Entry object from the DataSet at the specified index.
public func removeEntry(entry: ChartDataEntry!, dataSetIndex: Int) -> Bool
{
// entry null, outofbounds
if (entry === nil || dataSetIndex >= _dataSets.count)
{
return false
}
// remove the entry from the dataset
let removed = _dataSets[dataSetIndex].removeEntry(xIndex: entry.xIndex)
if (removed)
{
let val = entry.value
_yValCount -= 1
_yValueSum -= val
calcMinMax(start: _lastStart, end: _lastEnd)
}
return removed
}
/// Removes the Entry object at the given xIndex from the ChartDataSet at the
/// specified index.
/// - returns: true if an entry was removed, false if no Entry was found that meets the specified requirements.
public func removeEntryByXIndex(xIndex: Int, dataSetIndex: Int) -> Bool
{
if (dataSetIndex >= _dataSets.count)
{
return false
}
let entry = _dataSets[dataSetIndex].entryForXIndex(xIndex)
if (entry?.xIndex != xIndex)
{
return false
}
return removeEntry(entry, dataSetIndex: dataSetIndex)
}
/// - returns: the DataSet that contains the provided Entry, or null, if no DataSet contains this entry.
public func getDataSetForEntry(e: ChartDataEntry!) -> ChartDataSet?
{
if (e == nil)
{
return nil
}
for (var i = 0; i < _dataSets.count; i++)
{
let set = _dataSets[i]
for (var j = 0; j < set.entryCount; j++)
{
if (e === set.entryForXIndex(e.xIndex))
{
return set
}
}
}
return nil
}
/// - returns: the index of the provided DataSet inside the DataSets array of this data object. -1 if the DataSet was not found.
public func indexOfDataSet(dataSet: ChartDataSet) -> Int
{
for (var i = 0; i < _dataSets.count; i++)
{
if (_dataSets[i] === dataSet)
{
return i
}
}
return -1
}
public func getFirstLeft() -> ChartDataSet?
{
for dataSet in _dataSets
{
if (dataSet.axisDependency == .Left)
{
return dataSet
}
}
return nil
}
public func getFirstRight() -> ChartDataSet?
{
for dataSet in _dataSets
{
if (dataSet.axisDependency == .Right)
{
return dataSet
}
}
return nil
}
/// - returns: all colors used across all DataSet objects this object represents.
public func getColors() -> [UIColor]?
{
if (_dataSets == nil)
{
return nil
}
var clrcnt = 0
for (var i = 0; i < _dataSets.count; i++)
{
clrcnt += _dataSets[i].colors.count
}
var colors = [UIColor]()
for (var i = 0; i < _dataSets.count; i++)
{
let clrs = _dataSets[i].colors
for clr in clrs
{
colors.append(clr)
}
}
return colors
}
/// Generates an x-values array filled with numbers in range specified by the parameters. Can be used for convenience.
public func generateXVals(from: Int, to: Int) -> [String]
{
var xvals = [String]()
for (var i = from; i < to; i++)
{
xvals.append(String(i))
}
return xvals
}
/// Sets a custom ValueFormatter for all DataSets this data object contains.
public func setValueFormatter(formatter: NSNumberFormatter!)
{
for set in dataSets
{
set.valueFormatter = formatter
}
}
/// Sets the color of the value-text (color in which the value-labels are drawn) for all DataSets this data object contains.
public func setValueTextColor(color: UIColor!)
{
for set in dataSets
{
set.valueTextColor = color ?? set.valueTextColor
}
}
/// Sets the font for all value-labels for all DataSets this data object contains.
public func setValueFont(font: UIFont!)
{
for set in dataSets
{
set.valueFont = font ?? set.valueFont
}
}
/// Enables / disables drawing values (value-text) for all DataSets this data object contains.
public func setDrawValues(enabled: Bool)
{
for set in dataSets
{
set.drawValuesEnabled = enabled
}
}
/// Enables / disables highlighting values for all DataSets this data object contains.
public var highlightEnabled: Bool
{
get
{
for set in dataSets
{
if (!set.highlightEnabled)
{
return false
}
}
return true
}
set
{
for set in dataSets
{
set.highlightEnabled = newValue
}
}
}
/// if true, value highlightning is enabled
public var isHighlightEnabled: Bool { return highlightEnabled }
/// Clears this data object from all DataSets and removes all Entries.
/// Don't forget to invalidate the chart after this.
public func clearValues()
{
dataSets.removeAll(keepCapacity: false)
notifyDataChanged()
}
/// Checks if this data object contains the specified Entry.
/// - returns: true if so, false if not.
public func contains(entry entry: ChartDataEntry) -> Bool
{
for set in dataSets
{
if (set.contains(entry))
{
return true
}
}
return false
}
/// Checks if this data object contains the specified DataSet.
/// - returns: true if so, false if not.
public func contains(dataSet dataSet: ChartDataSet) -> Bool
{
for set in dataSets
{
if (set.isEqual(dataSet))
{
return true
}
}
return false
}
/// MARK: - ObjC compatibility
/// - returns: the average length (in characters) across all values in the x-vals array
public var xValsObjc: [NSObject] { return ChartUtils.bridgedObjCGetStringArray(swift: _xVals); }
}
|
bsd-3-clause
|
9cee79bad853ff295d51535282a93faa
| 25.602564 | 143 | 0.473012 | 5.197245 | false | false | false | false |
raymondshadow/SwiftDemo
|
SwiftApp/Pods/RxSwift/RxSwift/Observables/Create.swift
|
3
|
2498
|
//
// Create.swift
// RxSwift
//
// Created by Krunoslav Zaher on 2/8/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
extension ObservableType {
// MARK: create
/**
Creates an observable sequence from a specified subscribe method implementation.
- seealso: [create operator on reactivex.io](http://reactivex.io/documentation/operators/create.html)
- parameter subscribe: Implementation of the resulting observable sequence's `subscribe` method.
- returns: The observable sequence with the specified implementation for the `subscribe` method.
*/
public static func create(_ subscribe: @escaping (AnyObserver<E>) -> Disposable) -> Observable<E> {
return AnonymousObservable(subscribe)
}
}
final private class AnonymousObservableSink<O: ObserverType>: Sink<O>, ObserverType {
typealias E = O.E
typealias Parent = AnonymousObservable<E>
// state
private let _isStopped = AtomicInt(0)
#if DEBUG
fileprivate let _synchronizationTracker = SynchronizationTracker()
#endif
override init(observer: O, cancel: Cancelable) {
super.init(observer: observer, cancel: cancel)
}
func on(_ event: Event<E>) {
#if DEBUG
self._synchronizationTracker.register(synchronizationErrorMessage: .default)
defer { self._synchronizationTracker.unregister() }
#endif
switch event {
case .next:
if load(self._isStopped) == 1 {
return
}
self.forwardOn(event)
case .error, .completed:
if fetchOr(self._isStopped, 1) == 0 {
self.forwardOn(event)
self.dispose()
}
}
}
func run(_ parent: Parent) -> Disposable {
return parent._subscribeHandler(AnyObserver(self))
}
}
final private class AnonymousObservable<Element>: Producer<Element> {
typealias SubscribeHandler = (AnyObserver<Element>) -> Disposable
let _subscribeHandler: SubscribeHandler
init(_ subscribeHandler: @escaping SubscribeHandler) {
self._subscribeHandler = subscribeHandler
}
override func run<O : ObserverType>(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == Element {
let sink = AnonymousObservableSink(observer: observer, cancel: cancel)
let subscription = sink.run(self)
return (sink: sink, subscription: subscription)
}
}
|
apache-2.0
|
0148b290706e5643cf96c3dcfc06f1b7
| 31.012821 | 145 | 0.652783 | 4.73814 | false | false | false | false |
everald/JetPack
|
Sources/Extensions/CoreGraphics/CGAffineTransform.swift
|
1
|
3642
|
import CoreGraphics
public extension CGAffineTransform {
public init(horizontalScale: CGFloat, verticalScale: CGFloat = 1) {
self = CGAffineTransform(scaleX: horizontalScale, y: verticalScale)
}
public init(verticalScale: CGFloat) {
self = CGAffineTransform(scaleX: 1, y: verticalScale)
}
public init(horizontalTranslation: CGFloat, verticalTranslation: CGFloat = 0) {
self = CGAffineTransform(translationX: horizontalTranslation, y: verticalTranslation)
}
public init(verticalTranslation: CGFloat) {
self = CGAffineTransform(translationX: 0, y: verticalTranslation)
}
@available(*, unavailable, renamed: "init(rotationAngle:)")
public init(rotation angle: CGFloat) {
self = CGAffineTransform(rotationAngle: angle)
}
public init(scale: CGFloat) {
self = CGAffineTransform(scaleX: scale, y: scale)
}
public var horizontalScale: CGFloat {
return sqrt((a * a) + (c * c))
}
public var horizontalTranslation: CGFloat {
return tx
}
@available(*, unavailable, renamed: "rotationAngle")
public var rotation: CGFloat {
return atan2(b, a)
}
public var rotationAngle: CGFloat {
return atan2(b, a)
}
public func scaledBy(_ scale: CGFloat) -> CGAffineTransform {
return scaledBy(horizontally: scale, vertically: scale)
}
public func scaledBy(horizontally horizontal: CGFloat, vertically vertical: CGFloat = 1) -> CGAffineTransform {
return scaledBy(x: horizontal, y: vertical)
}
public func scaledBy(vertically vertical: CGFloat) -> CGAffineTransform {
return scaledBy(horizontally: 1, vertically: vertical)
}
public func translatedBy(horizontally horizontal: CGFloat, vertically vertical: CGFloat = 0) -> CGAffineTransform {
return self.translatedBy(x: horizontal, y: vertical)
}
public func translatedBy(vertically vertical: CGFloat) -> CGAffineTransform {
return translatedBy(horizontally: 0, vertically: vertical)
}
public var verticalScale: CGFloat {
return sqrt((b * b) + (d * d))
}
public var verticalTranslation: CGFloat {
return ty
}
}
extension CGAffineTransform: CustomStringConvertible {
public var description: String {
guard !isIdentity else {
return "CGAffineTransform.identity"
}
let horizontalScale = self.horizontalScale
let verticalScale = self.verticalScale
let horizontalTranslation = self.horizontalTranslation
let verticalTranslation = self.verticalTranslation
let rotationAngle = self.rotationAngle
var description = ""
if horizontalScale != 1 {
if !description.isEmpty { description += ", " }
description += "horizontalScale: "
description += String(describing: horizontalScale)
}
if verticalScale != 1 {
if !description.isEmpty { description += ", " }
description += "verticalScale: "
description += String(describing: verticalScale)
}
if rotationAngle != 0 {
if !description.isEmpty { description += ", " }
description += "rotationAngle: "
description += String(describing: rotationAngle / .pi)
description += " * .pi"
}
if horizontalTranslation != 0 {
if !description.isEmpty { description += ", " }
description += "horizontalTranslation: "
description += String(describing: horizontalTranslation)
}
if verticalTranslation != 0 {
if !description.isEmpty { description += ", " }
description += "verticalTranslation: "
description += String(describing: verticalTranslation)
}
guard !description.isEmpty else {
return "CGAffineTransform.identity"
}
return "CGAffineTransform(" + description + ")"
}
}
public func * (a: CGAffineTransform, b: CGAffineTransform) -> CGAffineTransform {
return a.concatenating(b)
}
|
mit
|
633746a898b36e459bd6e557a8fc9ba9
| 23.119205 | 116 | 0.721856 | 4.069274 | false | false | false | false |
jsslai/Action
|
Demo/DemoTests/AlertActionTests.swift
|
2
|
2547
|
import Quick
import Nimble
import RxSwift
import RxBlocking
import Action
class AlertActionTests: QuickSpec {
override func spec() {
it("is nil by default") {
let subject = UIAlertAction.Action("Hi", style: .Default)
expect(subject.rx_action).to( beNil() )
}
it("respects setter") {
let subject = UIAlertAction.Action("Hi", style: .Default)
let action = emptyAction()
subject.rx_action = action
expect(subject.rx_action) === action
}
it("disables the alert action while executing") {
let subject = UIAlertAction.Action("Hi", style: .Default)
var observer: AnyObserver<Void>!
let action = CocoaAction(workFactory: { _ in
return Observable.create { (obsv) -> Disposable in
observer = obsv
return NopDisposable.instance
}
})
subject.rx_action = action
action.execute()
expect(subject.enabled).toEventually( beFalse() )
observer.onCompleted()
expect(subject.enabled).toEventually( beTrue() )
}
it("disables the alert action if the Action is disabled") {
let subject = UIAlertAction.Action("Hi", style: .Default)
let disposeBag = DisposeBag()
subject.rx_action = emptyAction(.just(false))
waitUntil { done in
subject.rx_observe(Bool.self, "enabled")
.take(1)
.subscribeNext { _ in
done()
}
.addDisposableTo(disposeBag)
}
expect(subject.enabled) == false
}
it("disposes of old action subscriptions when re-set") {
let subject = UIAlertAction.Action("Hi", style: .Default)
var disposed = false
autoreleasepool {
let disposeBag = DisposeBag()
let action = emptyAction()
subject.rx_action = action
action
.elements
.subscribe(onNext: nil, onError: nil, onCompleted: nil, onDisposed: {
disposed = true
})
.addDisposableTo(disposeBag)
}
subject.rx_action = nil
expect(disposed) == true
}
}
}
|
mit
|
80d476f0db2196caa2ab6b23e45765e7
| 29.333333 | 89 | 0.493522 | 5.610132 | false | false | false | false |
yangchenghu/actor-platform
|
actor-apps/app-ios/ActorApp/Controllers Support/AANavigationController.swift
|
9
|
2075
|
//
// Copyright (c) 2014-2015 Actor LLC. <https://actor.im>
//
import UIKit
class AANavigationController: UINavigationController {
private let binder = Binder()
override func viewDidLoad() {
super.viewDidLoad()
navigationBar.hideBottomHairline()
view.backgroundColor = MainAppTheme.list.backyardColor
// Enabling app state sync progress
self.setPrimaryColor(MainAppTheme.navigation.progressPrimary)
self.setSecondaryColor(MainAppTheme.navigation.progressSecondary)
binder.bind(Actor.getAppState().getIsSyncing(), valueModel2: Actor.getAppState().getIsConnecting()) { (value1: JavaLangBoolean?, value2: JavaLangBoolean?) -> () in
if value1!.booleanValue() || value2!.booleanValue() {
self.showProgress()
self.setIndeterminate(true)
} else {
self.finishProgress()
}
}
}
func makeBarTransparent() {
navigationBar.setBackgroundImage(UIImage(), forBarMetrics: UIBarMetrics.Default)
navigationBar.shadowImage = UIImage()
}
override func preferredStatusBarStyle() -> UIStatusBarStyle {
return UIStatusBarStyle.LightContent
}
}
extension UINavigationBar {
func hideBottomHairline() {
let navigationBarImageView = hairlineImageViewInNavigationBar(self)
navigationBarImageView!.hidden = true
}
func showBottomHairline() {
let navigationBarImageView = hairlineImageViewInNavigationBar(self)
navigationBarImageView!.hidden = false
}
private func hairlineImageViewInNavigationBar(view: UIView) -> UIImageView? {
if view.isKindOfClass(UIImageView) && view.bounds.height <= 1.0 {
return (view as! UIImageView)
}
for subview: UIView in view.subviews {
if let imageView: UIImageView = hairlineImageViewInNavigationBar(subview) {
return imageView
}
}
return nil
}
}
|
mit
|
754adca26aa7ad92f6864c8506827d35
| 30.454545 | 171 | 0.637108 | 5.533333 | false | false | false | false |
tlax/looper
|
looper/Model/Loops/Main/MLoops.swift
|
1
|
1097
|
import Foundation
class MLoops
{
var items:[MLoopsItem]
init()
{
items = []
}
//MARK: public
func loadFromDb(completion:@escaping(() -> ()))
{
DManager.sharedInstance.fetchManagedObjects(
entityName:DLoop.entityName)
{ [weak self] (fetched) in
guard
let loops:[DLoop] = fetched as? [DLoop]
else
{
self?.items = []
completion()
return
}
var items:[MLoopsItem] = []
for loop:DLoop in loops
{
let item:MLoopsItem = MLoopsItem(loop:loop)
items.append(item)
}
items.sort
{ (itemA:MLoopsItem, itemB:MLoopsItem) -> Bool in
return itemA.loop.created > itemB.loop.created
}
self?.items = items
completion()
}
}
}
|
mit
|
7c6b11109ebb2357a6f1166df802f45a
| 20.94 | 62 | 0.395624 | 5.325243 | false | false | false | false |
zhuyihao/Top4Swift
|
Top4Swift/onlinePool.swift
|
2
|
6361
|
//
// ViewController.swift
// Top4Swift
//
// Created by james on 14-11-18.
// Copyright (c) 2014年 woowen. All rights reserved.
//
import UIKit
class onlinePool: UIViewController,HttpProtocol,UITableViewDataSource,UITableViewDelegate {
var timeLineUrl = "http://top.mogujie.com/top/zadmin/app/yituijian?_adid=99000537220553"
@IBOutlet weak var tableView: UITableView!
var eHttp: HttpController = HttpController()
var base: baseClass = baseClass()
var tmpListData: NSMutableArray = NSMutableArray()
var listData: NSMutableArray = NSMutableArray()
var page = 1 //page
var imageCache = Dictionary<String,UIImage>()
var tid: String = ""
var sign: String = ""
let cellImg = 1
let cellLbl1 = 2
let cellLbl2 = 3
let cellLbl3 = 4
let refreshControl = UIRefreshControl()
//Refresh func
func setupRefresh(){
self.tableView.addHeaderWithCallback({
let delayInSeconds:Int64 = 1000000000 * 2
var popTime:dispatch_time_t = dispatch_time(DISPATCH_TIME_NOW,delayInSeconds)
dispatch_after(popTime, dispatch_get_main_queue(), {
self.tableView.reloadData()
self.tableView.headerEndRefreshing()
})
})
self.tableView.addFooterWithCallback({
var nextPage = String(self.page + 1)
var tmpTimeLineUrl = self.timeLineUrl + "&page=" + nextPage as NSString
self.eHttp.delegate = self
self.eHttp.get(tmpTimeLineUrl)
let delayInSeconds:Int64 = 1000000000 * 2
var popTime:dispatch_time_t = dispatch_time(DISPATCH_TIME_NOW,delayInSeconds)
dispatch_after(popTime, dispatch_get_main_queue(), {
self.tableView.footerEndRefreshing()
if(self.tmpListData != self.listData){
if(self.tmpListData.count != 0){
var tmpListDataCount = self.tmpListData.count
for(var i:Int = 0; i < tmpListDataCount; i++){
self.listData.addObject(self.tmpListData[i])
}
}
self.tableView.reloadData()
self.tmpListData.removeAllObjects()
}
})
})
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
//获取sign
self.sign = base.cacheGetString("sign")
eHttp.delegate = self
self.timeLineUrl = self.timeLineUrl + "&sign=" + self.sign
eHttp.get(self.timeLineUrl)
self.setupRefresh()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int{
if(self.listData.count == 0){
if(self.tmpListData.count != 0){
self.listData = self.tmpListData
}
}
return listData.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell{
var cell: AnyObject? = tableView.dequeueReusableCellWithIdentifier("list", forIndexPath: indexPath)
var rowData: NSDictionary = self.listData[indexPath.row] as NSDictionary
let imgUrl = rowData["cover"]? as String
var img = cell?.viewWithTag(cellImg) as UIImageView
img.image = UIImage(named: "default.png")
if(imgUrl != ""){
let image = self.imageCache[imgUrl] as UIImage?
if(image == nil){
let imageUrl = NSURL(string: imgUrl)
let request: NSURLRequest = NSURLRequest(URL: imageUrl!)
//异步获取
NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue(), completionHandler: {(response: NSURLResponse!,data: NSData!,error: NSError!)-> Void in
let imgTmp = UIImage(data: data)
img.image = imgTmp
self.imageCache[imgUrl] = imgTmp
})
}else{
img.image = image
}
}
//标题
var label1 = cell?.viewWithTag(cellLbl1) as UILabel
//换行
label1.numberOfLines = 0
label1.lineBreakMode = NSLineBreakMode.ByWordWrapping
label1.text = rowData["content"]? as NSString
var label2 = cell?.viewWithTag(cellLbl2) as UILabel
label2.text = rowData["user"]?["uname"] as NSString
var label3 = cell?.viewWithTag(cellLbl3) as UILabel
//时间格式转换
var outputFormat = NSDateFormatter()
outputFormat.dateFormat = "yyyy/MM/dd HH:mm:ss"
outputFormat.locale = NSLocale(localeIdentifier: "shanghai")
//发布时间
let pubTime = NSDate(timeIntervalSince1970: rowData["pubTime"]? as NSTimeInterval)
label3.text = outputFormat.stringFromDate(pubTime)
return cell as UITableViewCell
}
//点击事件处理
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath){
let trueData: NSDictionary = self.listData[indexPath.row] as NSDictionary
self.tid = trueData["tid"] as NSString
self.performSegueWithIdentifier("detail", sender: self)
}
//跳转传参方法
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "detail" {
var instance = segue.destinationViewController as detailViewController
instance.tid = self.tid
}
}
func didRecieveResult(result: NSDictionary){
if(result["result"]?["list"] != nil && result["result"]?["isEnd"] as NSNumber != 1){
self.tmpListData = result["result"]?["list"] as NSMutableArray //list数据
self.page = result["result"]?["page"] as Int
self.tableView.reloadData()
}
}
//返回按钮
@IBAction func close(segue: UIStoryboardSegue){
}
@IBAction func toggleSideMenu(sender: AnyObject) {
toggleSideMenuView()
}
}
|
mit
|
5145a79f14b73634af0649791353db00
| 35.317919 | 188 | 0.592551 | 4.893302 | false | false | false | false |
xu6148152/binea_project_for_ios
|
SportDemo/SportDemo/Shared/view/popover/ZPDialogPopoverView.swift
|
1
|
3718
|
//
// ZPDialogPopoverView.swift
// SportDemo
//
// Created by Binea Xu on 9/20/15.
// Copyright © 2015 Binea Xu. All rights reserved.
//
import Foundation
import TTTAttributedLabel
import PureLayout
enum ZPPopoverButtonType{
case ZPPopoverButtonNone, ZPPopoverButtonNormal, ZPPopoverButtonNegative
}
class ZPDialogPopoverView: ZPPopoverView{
@IBOutlet weak var title: UILabel!
@IBOutlet weak var imageView: UIImageView!
@IBOutlet weak var actionButton: UIButton!
@IBOutlet weak var cancelButton: UIButton!
@IBOutlet weak var message: TTTAttributedLabel!
@IBOutlet weak var actionButtonHeightConstraint: NSLayoutConstraint!
@IBOutlet weak var cancelButtonHeightConstraint: NSLayoutConstraint!
var actionBlock: (() -> Void)?
var cancelBlock: (() -> Void)?
@IBOutlet weak var containerView: UIView!
static func _viewWithTitle(title: String, message: String, actionTitle: String, actionBlock: (()->Void), cancelTitle: String,
cancelBlock: (()->Void), buttonType: ZPPopoverButtonType) -> ZPDialogPopoverView{
let view = ZPDialogPopoverView().initFromNib() as! ZPDialogPopoverView
view.autoSetDimension(ALDimension.Width, toSize: 290)
view.title.text = title.uppercaseString
view.message.textInsets = UIEdgeInsetsMake(15, 0, 0, 0)
view.message.text = message
if buttonType == ZPPopoverButtonType.ZPPopoverButtonNone {
view.actionButtonHeightConstraint.constant = 0;
view.cancelButtonHeightConstraint.constant = 0;
view.actionButton.hidden = true;
view.cancelButton.hidden = true;
view.autoSetDimension(ALDimension.Height, toSize: 370)
}else {
if (!actionTitle.isEmpty) {
view.actionButton.setTitle(actionTitle.uppercaseString, forState: UIControlState.Normal)
view.actionButton.backgroundColor = buttonType == ZPPopoverButtonType.ZPPopoverButtonNormal ? UIGlobal.UIColorFromARGB(0x3C464D) : UIGlobal.UIColorFromARGB(0xFF2829)
view.actionBlock = actionBlock;
} else {
view.actionButton.hidden = true;
view.actionButtonHeightConstraint.constant = 0;
}
if (!cancelTitle.isEmpty) {
view.cancelButton.setTitle(cancelTitle.uppercaseString, forState: UIControlState.Normal)
view.cancelButton.backgroundColor = buttonType == ZPPopoverButtonType.ZPPopoverButtonNormal ? UIGlobal.UIColorFromARGB(0x30383D) : UIGlobal.UIColorFromARGB(0xD61111)
view.cancelBlock = cancelBlock;
} else {
view.cancelButton.hidden = true;
view.cancelButtonHeightConstraint.constant = 0;
}
}
return view
}
static func showDialog(title: String,
message: String,
customView: UIView?,
actionTitle: String,
actionBlock: () -> Void,
cancelTitle: String,
cancelBlock: () -> Void,
buttonType: ZPPopoverButtonType) {
let view = _viewWithTitle(title, message: message, actionTitle: actionTitle, actionBlock: actionBlock, cancelTitle: cancelTitle, cancelBlock: cancelBlock, buttonType: buttonType)
view.imageView.removeFromSuperview()
if customView != nil {
view.containerView.addSubview(customView!)
}
view.show()
}
}
|
mit
|
0b646b0a63541e0f09bfe80a2de4959c
| 37.71875 | 186 | 0.621738 | 5.257426 | false | false | false | false |
mitochrome/complex-gestures-demo
|
apps/GestureInput/Source/BrowseViewController.swift
|
1
|
11684
|
import UIKit
import RxCocoa
import RxSwift
import SnapKit
class BrowseViewController: UIViewController {
var disposeBag = DisposeBag()
private var imageView: UIImageView!
private var currentIndex = Variable<Int?>(nil)
private var currentDrawing: Observable<Drawing?> {
return currentIndex
.asObservable()
.map({ (index: Int?) -> Drawing? in
guard let index = index else {
return nil
}
let drawings = DataCache.shared.drawings
if index < 0 || index >= drawings.count {
return nil
}
return drawings[index]
})
}
private var currentLabel = Variable<Touches_Label?>(nil)
init() {
super.init(nibName: nil, bundle: nil)
title = "Browse"
navigationItem.backBarButtonItem = UIBarButtonItem(title: nil, style: .plain, target: self, action: #selector(closeMe))
currentIndex
.asObservable()
.map({ (index: Int?) -> Touches_Label? in
guard let index = index else {
return nil
}
let labels = DataCache.shared.labels
if index < 0 || index >= labels.count {
return nil
}
return labels[index]
})
.bind(to: currentLabel)
.disposed(by: disposeBag)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
@objc private func closeMe() {
navigationController?.popViewController(animated: true)
}
private func setIndex(_ index: Int) {
let count = min(DataCache.shared.drawings.count, DataCache.shared.labels.count)
if count == 0 {
currentIndex.value = nil
return
}
currentIndex.value = min(max(0, index), count - 1)
}
// MARK: UIViewController
override func viewDidLoad() {
super.viewDidLoad()
let _ = DataCache.shared.load()
setIndex(0)
view.backgroundColor = UIColor.white
imageView = UIImageView()
imageView.contentMode = .scaleAspectFit
view.addSubview(imageView)
imageView.snp.makeConstraints { (make) in
make.center.equalToSuperview()
make.size.equalToSuperview()
}
currentDrawing
.map { $0?.rasterized() }
.bind(to: imageView.rx.image)
.disposed(by: disposeBag)
let indexControl = UIControl()
view.addSubview(indexControl)
indexControl.snp.makeConstraints { (make) in
make.centerX.equalToSuperview()
make.top.equalTo(topLayoutGuide.snp.bottom).offset(5)
}
indexControl.rx.controlEvent(.touchUpInside)
.subscribe(onNext: { [weak self] in
let alert = UIAlertController(title: nil, message: nil, preferredStyle: .alert)
alert.addTextField(configurationHandler: { (textField) in
textField.text = String(self?.currentIndex.value ?? 0)
})
alert.addAction(UIAlertAction(title: "OK", style: .default, handler: { [weak self] _ in
guard let text = alert.textFields?.first?.text else {
return
}
self?.setIndex(Int(text) ?? 0)
}))
self?.present(alert, animated: true, completion: nil)
})
.disposed(by: disposeBag)
let indexLabel = UILabel()
indexControl.addSubview(indexLabel)
indexLabel.snp.makeConstraints { (make) in
make.center.equalToSuperview()
// Inset here makes the indexControl bigger so that it's easier to tap.
make.size.equalToSuperview().inset(5)
}
currentIndex
.asObservable()
.map { index -> String? in
return index != nil ? String(index!) : nil
}
.bind(to: indexLabel.rx.text)
.disposed(by: disposeBag)
let classControl = UIControl()
view.addSubview(classControl)
classControl.snp.makeConstraints { (make) in
make.centerX.equalToSuperview()
make.top.equalTo(indexLabel.snp.bottom).offset(5)
}
classControl.rx.controlEvent(.touchUpInside)
.subscribe(onNext: { [weak self] in
guard let me = self else {
return
}
let controller = ClassPicker()
controller.currentClass.value = me.currentLabel.value
controller.didDismiss
.withLatestFrom(controller.currentClass.asObservable())
.subscribe(onNext: { [weak self] newClass in
guard let newClass = newClass, let currentIndex = self?.currentIndex.value else {
return
}
DataCache.shared.labels[currentIndex] = newClass
// Trigger an update.
self?.currentIndex.value = self?.currentIndex.value
})
.disposed(by: me.disposeBag)
me.present(controller, animated: true, completion: nil)
})
.disposed(by: disposeBag)
let classLabel = UILabel()
classLabel.isUserInteractionEnabled = false
classLabel.textColor = UIColor.black
classControl.addSubview(classLabel)
classLabel.snp.makeConstraints { (make) in
make.center.equalToSuperview()
make.size.equalToSuperview()
}
currentLabel
.asObservable()
.map { $0?.name }
.bind(to: classLabel.rx.text)
.disposed(by: disposeBag)
let backButton = makeSimpleButton()
backButton.setTitle("Back", for: .normal)
view.addSubview(backButton)
backButton.snp.makeConstraints { (make) in
make.left.equalToSuperview().inset(20)
make.bottom.equalToSuperview().inset(20)
}
backButton.rx.controlEvent(.touchUpInside)
.subscribe(onNext: { [weak self] in
guard let me = self else {
return
}
me.setIndex((me.currentIndex.value ?? 0) - 1)
})
.disposed(by: disposeBag)
let nextButton = makeSimpleButton()
nextButton.setTitle("Next", for: .normal)
view.addSubview(nextButton)
nextButton.snp.makeConstraints { (make) in
make.right.equalToSuperview().inset(20)
make.bottom.equalToSuperview().inset(20)
}
nextButton.rx.controlEvent(.touchUpInside)
.subscribe(onNext: { [weak self] in
guard let me = self else {
return
}
me.setIndex((me.currentIndex.value ?? 0) + 1)
})
.disposed(by: disposeBag)
let saveButton = makeSimpleButton()
saveButton.setTitle("Save Cache", for: .normal)
view.addSubview(saveButton)
saveButton.snp.makeConstraints { (make) in
make.centerX.equalToSuperview()
make.bottom.equalToSuperview().inset(20)
}
saveButton.rx.controlEvent(.touchUpInside)
.subscribe(onNext: {
let _ = DataCache.shared.save()
})
.disposed(by: disposeBag)
let deleteButton = makeSimpleButton()
deleteButton.setTitle("Delete", for: .normal)
view.addSubview(deleteButton)
deleteButton.snp.makeConstraints { (make) in
make.right.equalToSuperview().inset(20)
make.bottom.equalTo(saveButton.snp.top).offset(-20)
}
deleteButton.rx.controlEvent(.touchUpInside)
.subscribe(onNext: { [weak self] in
guard let me = self, let index = me.currentIndex.value else {
return
}
DataCache.shared.drawings.remove(at: index)
DataCache.shared.labels.remove(at: index)
me.setIndex(index)
})
.disposed(by: disposeBag)
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
let _ = DataCache.shared.save()
}
}
fileprivate class ClassPicker: UINavigationController, UIPickerViewDelegate, UIPickerViewDataSource {
private(set) var disposeBag = DisposeBag()
var currentClass = Variable<Touches_Label?>(nil)
private var didDismissSubject = PublishSubject<Void>()
var didDismiss: Observable<Void> {
return didDismissSubject.asObservable()
}
@objc private func doneTapped() {
dismiss(animated: true, completion: nil)
didDismissSubject.onNext(())
}
// MARK: UIViewController
override func viewDidLoad() {
super.viewDidLoad()
let innerController = UIViewController()
innerController.title = "Set Label"
innerController.view.backgroundColor = UIColor.white
innerController.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Done", style: .done, target: self, action: #selector(doneTapped))
let picker = UIPickerView()
picker.delegate = self
picker.dataSource = self
innerController.view.addSubview(picker)
picker.snp.makeConstraints { (make) in
make.top.equalTo(innerController.topLayoutGuide.snp.bottom)
make.width.equalToSuperview()
make.height.equalTo(200)
}
currentClass
.asObservable()
.distinctUntilChanged(==)
.subscribe(onNext: { currentClass in
guard let currentClass = currentClass, let index = Touches_Label.all.index(of: currentClass) else {
return
}
picker.selectRow(index, inComponent: 0, animated: false)
})
.disposed(by: disposeBag)
picker.rx.itemSelected
.map { (row, _) in Touches_Label.all[row] }
.bind(to: currentClass)
.disposed(by: disposeBag)
pushViewController(innerController, animated: false)
}
// MARK: UIPickerViewDelegate
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
return Touches_Label.all[row].name
}
// MARK: UIPickerViewDataSource
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return Touches_Label.all.count
}
}
|
mit
|
1d822a1de28dcce649e1bc319109bee4
| 32.193182 | 149 | 0.52987 | 5.454715 | false | false | false | false |
stephentyrone/swift
|
test/IDE/print_ast_tc_decls.swift
|
3
|
56636
|
// RUN: %empty-directory(%t)
//
// Build swift modules this test depends on.
// RUN: %target-swift-frontend -emit-module -o %t %S/Inputs/foo_swift_module.swift -enable-objc-interop -disable-objc-attr-requires-foundation-module
//
// FIXME: BEGIN -enable-source-import hackaround
// RUN: %target-swift-frontend(mock-sdk: -sdk %S/../Inputs/clang-importer-sdk -I %t) -emit-module -o %t %S/../Inputs/clang-importer-sdk/swift-modules/ObjectiveC.swift -enable-objc-interop -disable-objc-attr-requires-foundation-module
// FIXME: END -enable-source-import hackaround
//
// This file should not have any syntax or type checker errors.
// RUN: %target-swift-frontend(mock-sdk: -sdk %S/../Inputs/clang-importer-sdk -I %t) -swift-version 4 -typecheck -verify %s -F %S/Inputs/mock-sdk -enable-objc-interop -disable-objc-attr-requires-foundation-module
//
// RUN: %target-swift-ide-test(mock-sdk: -sdk %S/../Inputs/clang-importer-sdk -I %t) -swift-version 4 -skip-deinit=false -print-ast-typechecked -source-filename %s -F %S/Inputs/mock-sdk -function-definitions=false -prefer-type-repr=false -print-implicit-attrs=true -enable-objc-interop -disable-objc-attr-requires-foundation-module > %t.printed.txt
// RUN: %FileCheck %s -check-prefix=PASS_COMMON -strict-whitespace < %t.printed.txt
// RUN: %FileCheck %s -check-prefix=PASS_PRINT_AST -strict-whitespace < %t.printed.txt
// RUN: %FileCheck %s -check-prefix=PASS_RW_PROP_GET_SET -strict-whitespace < %t.printed.txt
// RUN: %FileCheck %s -check-prefix=PASS_2200 -strict-whitespace < %t.printed.txt
// RUN: %FileCheck %s -check-prefix=PASS_2500 -strict-whitespace < %t.printed.txt
// RUN: %FileCheck %s -check-prefix=PASS_ONE_LINE -strict-whitespace < %t.printed.txt
// RUN: %FileCheck %s -check-prefix=PASS_ONE_LINE_TYPE -strict-whitespace < %t.printed.txt
// RUN: %FileCheck %s -check-prefix=PREFER_TYPE_PRINTING -strict-whitespace < %t.printed.txt
// RUN: %FileCheck %s -check-prefix=PASS_QUAL_UNQUAL -strict-whitespace < %t.printed.txt
//
// RUN: %target-swift-ide-test(mock-sdk: -sdk %S/../Inputs/clang-importer-sdk -I %t) -swift-version 4 -skip-deinit=false -print-ast-typechecked -source-filename %s -F %S/Inputs/mock-sdk -function-definitions=false -prefer-type-repr=true -print-implicit-attrs=true -enable-objc-interop -disable-objc-attr-requires-foundation-module > %t.printed.txt
// RUN: %FileCheck %s -check-prefix=PASS_COMMON -strict-whitespace < %t.printed.txt
// RUN: %FileCheck %s -check-prefix=PASS_PRINT_AST -strict-whitespace < %t.printed.txt
// RUN: %FileCheck %s -check-prefix=PASS_RW_PROP_GET_SET -strict-whitespace < %t.printed.txt
// RUN: %FileCheck %s -check-prefix=PASS_2200 -strict-whitespace < %t.printed.txt
// RUN: %FileCheck %s -check-prefix=PASS_2500 -strict-whitespace < %t.printed.txt
// RUN: %FileCheck %s -check-prefix=PASS_ONE_LINE -strict-whitespace < %t.printed.txt
// RUN: %FileCheck %s -check-prefix=PASS_ONE_LINE_TYPEREPR -strict-whitespace < %t.printed.txt
// RUN: %FileCheck %s -check-prefix=PREFER_TYPE_REPR_PRINTING -strict-whitespace < %t.printed.txt
// RUN: %FileCheck %s -check-prefix=PASS_QUAL_UNQUAL -strict-whitespace < %t.printed.txt
//
// RUN: %target-swift-frontend(mock-sdk: -sdk %S/../Inputs/clang-importer-sdk -I %t) -swift-version 4 -emit-module -o %t -F %S/Inputs/mock-sdk -enable-objc-interop -disable-objc-attr-requires-foundation-module %s
// RUN: %target-swift-ide-test(mock-sdk: -sdk %S/../Inputs/clang-importer-sdk -I %t) -swift-version 4 -skip-deinit=false -print-module -source-filename %s -F %S/Inputs/mock-sdk -module-to-print=print_ast_tc_decls -print-implicit-attrs=true -enable-objc-interop -disable-objc-attr-requires-foundation-module > %t.printed.txt
// RUN: %FileCheck %s -check-prefix=PASS_COMMON -strict-whitespace < %t.printed.txt
// RUN: %FileCheck %s -check-prefix=PASS_PRINT_MODULE_INTERFACE -strict-whitespace < %t.printed.txt
// RUN: %FileCheck %s -check-prefix=PASS_RW_PROP_NO_GET_SET -strict-whitespace < %t.printed.txt
// RUN: %FileCheck %s -check-prefix=PASS_2200_DESERIALIZED -strict-whitespace < %t.printed.txt
// FIXME: rdar://15167697
// FIXME: %FileCheck %s -check-prefix=PASS_2500 -strict-whitespace < %t.printed.txt
// RUN: %FileCheck %s -check-prefix=PASS_ONE_LINE -strict-whitespace < %t.printed.txt
// RUN: %FileCheck %s -check-prefix=PREFER_TYPE_REPR_PRINTING -strict-whitespace < %t.printed.txt
// RUN: %FileCheck %s -check-prefix=PASS_QUAL_UNQUAL -strict-whitespace < %t.printed.txt
// RUN: %FileCheck %s -check-prefix=PASS_EXPLODE_PATTERN -strict-whitespace < %t.printed.txt
//
// RUN: %target-swift-ide-test(mock-sdk: -sdk %S/../Inputs/clang-importer-sdk -I %t) -skip-deinit=false -print-module -source-filename %s -F %S/Inputs/mock-sdk -I %t -module-to-print=print_ast_tc_decls -synthesize-sugar-on-types=true -print-implicit-attrs=true -enable-objc-interop -disable-objc-attr-requires-foundation-module > %t.printed.txt
// RUN: %FileCheck %s -check-prefix=PASS_PRINT_MODULE_INTERFACE -strict-whitespace < %t.printed.txt
// RUN: %FileCheck %s -check-prefix=PASS_QUAL_UNQUAL -strict-whitespace < %t.printed.txt
// RUN: %FileCheck %s -check-prefix=SYNTHESIZE_SUGAR_ON_TYPES -strict-whitespace < %t.printed.txt
// RUN: %FileCheck %s -check-prefix=PASS_EXPLODE_PATTERN -strict-whitespace < %t.printed.txt
// RUN: %target-swift-ide-test(mock-sdk: -sdk %S/../Inputs/clang-importer-sdk -I %t) -skip-deinit=false -print-module -source-filename %s -F %S/Inputs/mock-sdk -I %t -module-to-print=print_ast_tc_decls -synthesize-sugar-on-types=true -fully-qualified-types-if-ambiguous=true -print-implicit-attrs=true -enable-objc-interop -disable-objc-attr-requires-foundation-module > %t.printed.txt
// RUN: %FileCheck %s -check-prefix=PASS_PRINT_MODULE_INTERFACE -strict-whitespace < %t.printed.txt
// RUN: %FileCheck %s -check-prefix=PASS_QUAL_IF_AMBIGUOUS -strict-whitespace < %t.printed.txt
// RUN: %FileCheck %s -check-prefix=SYNTHESIZE_SUGAR_ON_TYPES -strict-whitespace < %t.printed.txt
// FIXME: %FileCheck %s -check-prefix=PASS_EXPLODE_PATTERN -strict-whitespace < %t.printed.txt
// FIXME: rdar://problem/19648117 Needs splitting objc parts out
// REQUIRES: objc_interop
import Bar
import ObjectiveC
import class Foo.FooClassBase
import struct Foo.FooStruct1
import func Foo.fooFunc1
@_exported import FooHelper
import foo_swift_module
// FIXME: enum tests
//import enum FooClangModule.FooEnum1
// PASS_COMMON: {{^}}import Bar{{$}}
// PASS_COMMON: {{^}}import class Foo.FooClassBase{{$}}
// PASS_COMMON: {{^}}import struct Foo.FooStruct1{{$}}
// PASS_COMMON: {{^}}import func Foo.fooFunc1{{$}}
// PASS_COMMON: {{^}}@_exported import FooHelper{{$}}
// PASS_COMMON: {{^}}import foo_swift_module{{$}}
//===---
//===--- Helper types.
//===---
struct FooStruct {}
class FooClass {}
class BarClass {}
protocol FooProtocol {}
protocol BarProtocol {}
protocol BazProtocol { func baz() }
protocol QuxProtocol {
associatedtype Qux
}
protocol SubFooProtocol : FooProtocol { }
class FooProtocolImpl : FooProtocol {}
class FooBarProtocolImpl : FooProtocol, BarProtocol {}
class BazProtocolImpl : BazProtocol { func baz() {} }
//===---
//===--- Basic smoketest.
//===---
struct d0100_FooStruct {
// PASS_COMMON-LABEL: {{^}}struct d0100_FooStruct {{{$}}
var instanceVar1: Int = 0
// PASS_COMMON-NEXT: {{^}} @_hasInitialValue var instanceVar1: Int{{$}}
var computedProp1: Int {
get {
return 42
}
}
// PASS_COMMON-NEXT: {{^}} var computedProp1: Int { get }{{$}}
func instanceFunc0() {}
// PASS_COMMON-NEXT: {{^}} func instanceFunc0(){{$}}
func instanceFunc1(a: Int) {}
// PASS_COMMON-NEXT: {{^}} func instanceFunc1(a: Int){{$}}
func instanceFunc2(a: Int, b: inout Double) {}
// PASS_COMMON-NEXT: {{^}} func instanceFunc2(a: Int, b: inout Double){{$}}
func instanceFunc3(a: Int, b: Double) { var a = a; a = 1; _ = a }
// PASS_COMMON-NEXT: {{^}} func instanceFunc3(a: Int, b: Double){{$}}
func instanceFuncWithDefaultArg1(a: Int = 0) {}
// PASS_COMMON-NEXT: {{^}} func instanceFuncWithDefaultArg1(a: Int = 0){{$}}
func instanceFuncWithDefaultArg2(a: Int = 0, b: Double = 0) {}
// PASS_COMMON-NEXT: {{^}} func instanceFuncWithDefaultArg2(a: Int = 0, b: Double = 0){{$}}
func varargInstanceFunc0(v: Int...) {}
// PASS_COMMON-NEXT: {{^}} func varargInstanceFunc0(v: Int...){{$}}
func varargInstanceFunc1(a: Float, v: Int...) {}
// PASS_COMMON-NEXT: {{^}} func varargInstanceFunc1(a: Float, v: Int...){{$}}
func varargInstanceFunc2(a: Float, b: Double, v: Int...) {}
// PASS_COMMON-NEXT: {{^}} func varargInstanceFunc2(a: Float, b: Double, v: Int...){{$}}
func overloadedInstanceFunc1() -> Int { return 0; }
// PASS_COMMON-NEXT: {{^}} func overloadedInstanceFunc1() -> Int{{$}}
func overloadedInstanceFunc1() -> Double { return 0.0; }
// PASS_COMMON-NEXT: {{^}} func overloadedInstanceFunc1() -> Double{{$}}
func overloadedInstanceFunc2(x: Int) -> Int { return 0; }
// PASS_COMMON-NEXT: {{^}} func overloadedInstanceFunc2(x: Int) -> Int{{$}}
func overloadedInstanceFunc2(x: Double) -> Int { return 0; }
// PASS_COMMON-NEXT: {{^}} func overloadedInstanceFunc2(x: Double) -> Int{{$}}
func builderFunc1(a: Int) -> d0100_FooStruct { return d0100_FooStruct(); }
// PASS_COMMON-NEXT: {{^}} func builderFunc1(a: Int) -> d0100_FooStruct{{$}}
subscript(i: Int) -> Double {
get {
return Double(i)
}
}
// PASS_COMMON-NEXT: {{^}} subscript(i: Int) -> Double { get }{{$}}
subscript(i: Int, j: Int) -> Double {
get {
return Double(i + j)
}
}
// PASS_COMMON-NEXT: {{^}} subscript(i: Int, j: Int) -> Double { get }{{$}}
static subscript(i: Int) -> Double {
get {
return Double(i)
}
}
// PASS_COMMON-NEXT: {{^}} static subscript(i: Int) -> Double { get }{{$}}
func bodyNameVoidFunc1(a: Int, b x: Float) {}
// PASS_COMMON-NEXT: {{^}} func bodyNameVoidFunc1(a: Int, b x: Float){{$}}
func bodyNameVoidFunc2(a: Int, b x: Float, c y: Double) {}
// PASS_COMMON-NEXT: {{^}} func bodyNameVoidFunc2(a: Int, b x: Float, c y: Double){{$}}
func bodyNameStringFunc1(a: Int, b x: Float) -> String { return "" }
// PASS_COMMON-NEXT: {{^}} func bodyNameStringFunc1(a: Int, b x: Float) -> String{{$}}
func bodyNameStringFunc2(a: Int, b x: Float, c y: Double) -> String { return "" }
// PASS_COMMON-NEXT: {{^}} func bodyNameStringFunc2(a: Int, b x: Float, c y: Double) -> String{{$}}
struct NestedStruct {}
// PASS_COMMON-NEXT: {{^}} struct NestedStruct {{{$}}
// PASS_COMMON-NEXT: {{^}} init(){{$}}
// PASS_COMMON-NEXT: {{^}} }{{$}}
class NestedClass {}
// PASS_COMMON-NEXT: {{^}} class NestedClass {{{$}}
// PASS_COMMON-NEXT: {{^}} @objc deinit{{$}}
// PASS_COMMON-NEXT: {{^}} init(){{$}}
// PASS_COMMON-NEXT: {{^}} }{{$}}
enum NestedEnum {}
// PASS_COMMON-NEXT: {{^}} enum NestedEnum {{{$}}
// PASS_COMMON-NEXT: {{^}} }{{$}}
// Cannot declare a nested protocol.
// protocol NestedProtocol {}
typealias NestedTypealias = Int
// PASS_COMMON-NEXT: {{^}} typealias NestedTypealias = Int{{$}}
static var staticVar1: Int = 42
// PASS_COMMON-NEXT: {{^}} @_hasInitialValue static var staticVar1: Int{{$}}
static var computedStaticProp1: Int {
get {
return 42
}
}
// PASS_COMMON-NEXT: {{^}} static var computedStaticProp1: Int { get }{{$}}
static func staticFunc0() {}
// PASS_COMMON-NEXT: {{^}} static func staticFunc0(){{$}}
static func staticFunc1(a: Int) {}
// PASS_COMMON-NEXT: {{^}} static func staticFunc1(a: Int){{$}}
static func overloadedStaticFunc1() -> Int { return 0 }
// PASS_COMMON-NEXT: {{^}} static func overloadedStaticFunc1() -> Int{{$}}
static func overloadedStaticFunc1() -> Double { return 0.0 }
// PASS_COMMON-NEXT: {{^}} static func overloadedStaticFunc1() -> Double{{$}}
static func overloadedStaticFunc2(x: Int) -> Int { return 0 }
// PASS_COMMON-NEXT: {{^}} static func overloadedStaticFunc2(x: Int) -> Int{{$}}
static func overloadedStaticFunc2(x: Double) -> Int { return 0 }
// PASS_COMMON-NEXT: {{^}} static func overloadedStaticFunc2(x: Double) -> Int{{$}}
}
// PASS_COMMON-NEXT: {{^}} init(instanceVar1: Int = 0){{$}}
// PASS_COMMON-NEXT: {{^}} init(){{$}}
// PASS_COMMON-NEXT: {{^}}}{{$}}
extension d0100_FooStruct {
// PASS_COMMON-LABEL: {{^}}extension d0100_FooStruct {{{$}}
var extProp: Int {
get {
return 42
}
}
// PASS_COMMON-NEXT: {{^}} var extProp: Int { get }{{$}}
func extFunc0() {}
// PASS_COMMON-NEXT: {{^}} func extFunc0(){{$}}
static var extStaticProp: Int {
get {
return 42
}
}
// PASS_COMMON-NEXT: {{^}} static var extStaticProp: Int { get }{{$}}
static func extStaticFunc0() {}
// PASS_COMMON-NEXT: {{^}} static func extStaticFunc0(){{$}}
struct ExtNestedStruct {}
// PASS_COMMON-NEXT: {{^}} struct ExtNestedStruct {{{$}}
// PASS_COMMON-NEXT: {{^}} init(){{$}}
// PASS_COMMON-NEXT: {{^}} }{{$}}
class ExtNestedClass {}
// PASS_COMMON-NEXT: {{^}} class ExtNestedClass {{{$}}
// PASS_COMMON-NEXT: {{^}} @objc deinit{{$}}
// PASS_COMMON-NEXT: {{^}} init(){{$}}
// PASS_COMMON-NEXT: {{^}} }{{$}}
enum ExtNestedEnum {
case ExtEnumX(Int)
}
// PASS_COMMON-NEXT: {{^}} enum ExtNestedEnum {{{$}}
// PASS_COMMON-NEXT: {{^}} case ExtEnumX(Int){{$}}
// PASS_COMMON-NEXT: {{^}} }{{$}}
typealias ExtNestedTypealias = Int
// PASS_COMMON-NEXT: {{^}} typealias ExtNestedTypealias = Int{{$}}
}
// PASS_COMMON-NEXT: {{^}}}{{$}}
extension d0100_FooStruct.NestedStruct {
// PASS_COMMON-LABEL: {{^}}extension d0100_FooStruct.NestedStruct {{{$}}
struct ExtNestedStruct2 {}
// PASS_COMMON-NEXT: {{^}} struct ExtNestedStruct2 {{{$}}
// PASS_COMMON-NEXT: {{^}} init(){{$}}
// PASS_COMMON-NEXT: {{^}} }{{$}}
}
extension d0100_FooStruct.ExtNestedStruct {
// PASS_COMMON-LABEL: {{^}}extension d0100_FooStruct.ExtNestedStruct {{{$}}
struct ExtNestedStruct3 {}
// PASS_COMMON-NEXT: {{^}} struct ExtNestedStruct3 {{{$}}
// PASS_COMMON-NEXT: {{^}} init(){{$}}
// PASS_COMMON-NEXT: {{^}} }{{$}}
}
// PASS_COMMON-NEXT: {{^}}}{{$}}
var fooObject: d0100_FooStruct = d0100_FooStruct()
// PASS_ONE_LINE-DAG: {{^}}@_hasInitialValue var fooObject: d0100_FooStruct{{$}}
struct d0110_ReadWriteProperties {
// PASS_RW_PROP_GET_SET-LABEL: {{^}}struct d0110_ReadWriteProperties {{{$}}
// PASS_RW_PROP_NO_GET_SET-LABEL: {{^}}struct d0110_ReadWriteProperties {{{$}}
var computedProp1: Int {
get {
return 42
}
set {}
}
// PASS_RW_PROP_GET_SET-NEXT: {{^}} var computedProp1: Int { get set }{{$}}
// PASS_RW_PROP_NO_GET_SET-NEXT: {{^}} var computedProp1: Int{{$}}
subscript(i: Int) -> Int {
get {
return 42
}
set {}
}
// PASS_RW_PROP_GET_SET-NEXT: {{^}} subscript(i: Int) -> Int { get set }{{$}}
// PASS_RW_PROP_NO_GET_SET-NEXT: {{^}} subscript(i: Int) -> Int{{$}}
static var computedStaticProp1: Int {
get {
return 42
}
set {}
}
// PASS_RW_PROP_GET_SET-NEXT: {{^}} static var computedStaticProp1: Int { get set }{{$}}
// PASS_RW_PROP_NO_GET_SET-NEXT: {{^}} static var computedStaticProp1: Int{{$}}
var computedProp2: Int {
mutating get {
return 42
}
set {}
}
// PASS_RW_PROP_GET_SET-NEXT: {{^}} var computedProp2: Int { mutating get set }{{$}}
// PASS_RW_PROP_NO_GET_SET-NEXT: {{^}} var computedProp2: Int { mutating get set }{{$}}
var computedProp3: Int {
get {
return 42
}
nonmutating set {}
}
// PASS_RW_PROP_GET_SET-NEXT: {{^}} var computedProp3: Int { get nonmutating set }{{$}}
// PASS_RW_PROP_NO_GET_SET-NEXT: {{^}} var computedProp3: Int { get nonmutating set }{{$}}
var computedProp4: Int {
mutating get {
return 42
}
nonmutating set {}
}
// PASS_RW_PROP_GET_SET-NEXT: {{^}} var computedProp4: Int { mutating get nonmutating set }{{$}}
// PASS_RW_PROP_NO_GET_SET-NEXT: {{^}} var computedProp4: Int { mutating get nonmutating set }{{$}}
subscript(i: Float) -> Int {
get {
return 42
}
nonmutating set {}
}
// PASS_RW_PROP_GET_SET-NEXT: {{^}} subscript(i: Float) -> Int { get nonmutating set }{{$}}
// PASS_RW_PROP_NO_GET_SET-NEXT: {{^}} subscript(i: Float) -> Int { get nonmutating set }{{$}}
}
// PASS_RW_PROP_GET_SET-NEXT: {{^}} init(){{$}}
// PASS_RW_PROP_GET_SET-NEXT: {{^}}}{{$}}
// PASS_RW_PROP_NO_GET_SET-NEXT: {{^}} init(){{$}}
// PASS_RW_PROP_NO_GET_SET-NEXT: {{^}}}{{$}}
extension d0110_ReadWriteProperties {
// PASS_RW_PROP_GET_SET-LABEL: {{^}}extension d0110_ReadWriteProperties {{{$}}
// PASS_RW_PROP_NO_GET_SET-LABEL: {{^}}extension d0110_ReadWriteProperties {{{$}}
var extProp: Int {
get {
return 42
}
set(v) {}
}
// PASS_RW_PROP_GET_SET-NEXT: {{^}} var extProp: Int { get set }{{$}}
// PASS_RW_PROP_NO_GET_SET-NEXT: {{^}} var extProp: Int{{$}}
static var extStaticProp: Int {
get {
return 42
}
set(v) {}
}
// PASS_RW_PROP_GET_SET-NEXT: {{^}} static var extStaticProp: Int { get set }{{$}}
// PASS_RW_PROP_NO_GET_SET-NEXT: {{^}} static var extStaticProp: Int{{$}}
}
// PASS_RW_PROP_GET_SET-NEXT: {{^}}}{{$}}
// PASS_RW_PROP_NO_GET_SET-NEXT: {{^}}}{{$}}
class d0120_TestClassBase {
// PASS_COMMON-LABEL: {{^}}class d0120_TestClassBase {{{$}}
required init() {}
// PASS_COMMON-NEXT: {{^}} required init(){{$}}
// FIXME: Add these once we can SILGen them reasonable.
// init?(fail: String) { }
// init!(iuoFail: String) { }
final func baseFunc1() {}
// PASS_COMMON-NEXT: {{^}} final func baseFunc1(){{$}}
func baseFunc2() {}
// PASS_COMMON-NEXT: {{^}} func baseFunc2(){{$}}
subscript(i: Int) -> Int {
return 0
}
// PASS_COMMON-NEXT: {{^}} subscript(i: Int) -> Int { get }{{$}}
class var baseClassVar1: Int { return 0 }
// PASS_COMMON-NEXT: {{^}} class var baseClassVar1: Int { get }{{$}}
// FIXME: final class var not allowed to have storage, but static is?
// final class var baseClassVar2: Int = 0
final class var baseClassVar3: Int { return 0 }
// PASS_COMMON-NEXT: {{^}} final class var baseClassVar3: Int { get }{{$}}
static var baseClassVar4: Int = 0
// PASS_COMMON-NEXT: {{^}} @_hasInitialValue static var baseClassVar4: Int{{$}}
static var baseClassVar5: Int { return 0 }
// PASS_COMMON-NEXT: {{^}} static var baseClassVar5: Int { get }{{$}}
class func baseClassFunc1() {}
// PASS_COMMON-NEXT: {{^}} class func baseClassFunc1(){{$}}
final class func baseClassFunc2() {}
// PASS_COMMON-NEXT: {{^}} final class func baseClassFunc2(){{$}}
static func baseClassFunc3() {}
// PASS_COMMON-NEXT: {{^}} static func baseClassFunc3(){{$}}
}
class d0121_TestClassDerived : d0120_TestClassBase {
// PASS_COMMON-LABEL: {{^}}@_inheritsConvenienceInitializers {{()?}}class d0121_TestClassDerived : d0120_TestClassBase {{{$}}
required init() { super.init() }
// PASS_COMMON-NEXT: {{^}} required init(){{$}}
final override func baseFunc2() {}
// PASS_COMMON-NEXT: {{^}} {{(override |final )+}}func baseFunc2(){{$}}
override final subscript(i: Int) -> Int {
return 0
}
// PASS_COMMON-NEXT: {{^}} override final subscript(i: Int) -> Int { get }{{$}}
}
protocol d0130_TestProtocol {
// PASS_COMMON-LABEL: {{^}}protocol d0130_TestProtocol {{{$}}
associatedtype NestedTypealias
// PASS_COMMON-NEXT: {{^}} associatedtype NestedTypealias{{$}}
var property1: Int { get }
// PASS_COMMON-NEXT: {{^}} var property1: Int { get }{{$}}
var property2: Int { get set }
// PASS_COMMON-NEXT: {{^}} var property2: Int { get set }{{$}}
func protocolFunc1()
// PASS_COMMON-NEXT: {{^}} func protocolFunc1(){{$}}
}
@objc protocol d0140_TestObjCProtocol {
// PASS_COMMON-LABEL: {{^}}@objc protocol d0140_TestObjCProtocol {{{$}}
@objc optional var property1: Int { get }
// PASS_COMMON-NEXT: {{^}} @objc optional var property1: Int { get }{{$}}
@objc optional func protocolFunc1()
// PASS_COMMON-NEXT: {{^}} @objc optional func protocolFunc1(){{$}}
}
protocol d0150_TestClassProtocol : class {}
// PASS_COMMON-LABEL: {{^}}protocol d0150_TestClassProtocol : AnyObject {{{$}}
@objc protocol d0151_TestClassProtocol {}
// PASS_COMMON-LABEL: {{^}}@objc protocol d0151_TestClassProtocol {{{$}}
class d0170_TestAvailability {
// PASS_COMMON-LABEL: {{^}}class d0170_TestAvailability {{{$}}
@available(*, unavailable)
func f1() {}
// PASS_COMMON-NEXT: {{^}} @available(*, unavailable){{$}}
// PASS_COMMON-NEXT: {{^}} func f1(){{$}}
@available(*, unavailable, message: "aaa \"bbb\" ccc\nddd\0eee")
func f2() {}
// PASS_COMMON-NEXT: {{^}} @available(*, unavailable, message: "aaa \"bbb\" ccc\nddd\0eee"){{$}}
// PASS_COMMON-NEXT: {{^}} func f2(){{$}}
@available(iOS, unavailable)
@available(OSX, unavailable)
func f3() {}
// PASS_COMMON-NEXT: {{^}} @available(iOS, unavailable){{$}}
// PASS_COMMON-NEXT: {{^}} @available(OSX, unavailable){{$}}
// PASS_COMMON-NEXT: {{^}} func f3(){{$}}
@available(iOS 8.0, OSX 10.10, *)
func f4() {}
// PASS_COMMON-NEXT: {{^}} @available(iOS 8.0, OSX 10.10, *){{$}}
// PASS_COMMON-NEXT: {{^}} func f4(){{$}}
// Convert long-form @available() to short form when possible.
@available(iOS, introduced: 8.0)
@available(OSX, introduced: 10.10)
func f5() {}
// PASS_COMMON-NEXT: {{^}} @available(iOS 8.0, OSX 10.10, *){{$}}
// PASS_COMMON-NEXT: {{^}} func f5(){{$}}
}
@objc class d0180_TestIBAttrs {
// PASS_COMMON-LABEL: {{^}}@objc class d0180_TestIBAttrs {{{$}}
@IBAction func anAction(_: AnyObject) {}
// PASS_COMMON-NEXT: {{^}} @objc @IBAction func anAction(_: AnyObject){{$}}
@IBSegueAction func aSegueAction(_ coder: AnyObject, sender: AnyObject, identifier: AnyObject?) -> Any? { fatalError() }
// PASS_COMMON-NEXT: {{^}} @objc @IBSegueAction func aSegueAction(_ coder: AnyObject, sender: AnyObject, identifier: AnyObject?) -> Any?{{$}}
@IBDesignable
class ADesignableClass {}
// PASS_COMMON-NEXT: {{^}} @IBDesignable class ADesignableClass {{{$}}
}
@objc class d0181_TestIBAttrs {
// PASS_EXPLODE_PATTERN-LABEL: {{^}}@objc class d0181_TestIBAttrs {{{$}}
@IBOutlet weak var anOutlet: d0181_TestIBAttrs!
// PASS_EXPLODE_PATTERN-NEXT: {{^}} @objc @IBOutlet @_hasInitialValue weak var anOutlet: @sil_weak d0181_TestIBAttrs!{{$}}
@IBInspectable var inspectableProp: Int = 0
// PASS_EXPLODE_PATTERN-NEXT: {{^}} @objc @IBInspectable @_hasInitialValue var inspectableProp: Int{{$}}
@GKInspectable var inspectableProp2: Int = 0
// PASS_EXPLODE_PATTERN-NEXT: {{^}} @objc @GKInspectable @_hasInitialValue var inspectableProp2: Int{{$}}
}
struct d0190_LetVarDecls {
// PASS_PRINT_AST-LABEL: {{^}}struct d0190_LetVarDecls {{{$}}
// PASS_PRINT_MODULE_INTERFACE-LABEL: {{^}}struct d0190_LetVarDecls {{{$}}
let instanceVar1: Int = 0
// PASS_PRINT_AST-NEXT: {{^}} @_hasInitialValue let instanceVar1: Int{{$}}
// PASS_PRINT_MODULE_INTERFACE-NEXT: {{^}} @_hasInitialValue let instanceVar1: Int{{$}}
let instanceVar2 = 0
// PASS_PRINT_AST-NEXT: {{^}} @_hasInitialValue let instanceVar2: Int{{$}}
// PASS_PRINT_MODULE_INTERFACE-NEXT: {{^}} @_hasInitialValue let instanceVar2: Int{{$}}
static let staticVar1: Int = 42
// PASS_PRINT_AST-NEXT: {{^}} @_hasInitialValue static let staticVar1: Int{{$}}
// PASS_PRINT_MODULE_INTERFACE-NEXT: {{^}} @_hasInitialValue static let staticVar1: Int{{$}}
static let staticVar2 = 42
// FIXME: PRINTED_WITHOUT_TYPE
// PASS_PRINT_AST-NEXT: {{^}} @_hasInitialValue static let staticVar2: Int{{$}}
// PASS_PRINT_MODULE_INTERFACE-NEXT: {{^}} @_hasInitialValue static let staticVar2: Int{{$}}
}
struct d0200_EscapedIdentifiers {
// PASS_COMMON-LABEL: {{^}}struct d0200_EscapedIdentifiers {{{$}}
struct `struct` {}
// PASS_COMMON-NEXT: {{^}} struct `struct` {{{$}}
// PASS_COMMON-NEXT: {{^}} init(){{$}}
// PASS_COMMON-NEXT: {{^}} }{{$}}
enum `enum` {
case `case`
}
// PASS_COMMON-NEXT: {{^}} enum `enum` {{{$}}
// PASS_COMMON-NEXT: {{^}} case `case`{{$}}
// PASS_COMMON-NEXT: {{^}} {{.*}}static func __derived_enum_equals(_ a: d0200_EscapedIdentifiers.`enum`, _ b: d0200_EscapedIdentifiers.`enum`) -> Bool
// PASS_COMMON-NEXT: {{^}} var hashValue: Int { get }{{$}}
// PASS_COMMON-NEXT: {{^}} func hash(into hasher: inout Hasher)
// PASS_COMMON-NEXT: {{^}} }{{$}}
class `class` {}
// PASS_COMMON-NEXT: {{^}} class `class` {{{$}}
// PASS_COMMON-NEXT: {{^}} @objc deinit{{$}}
// PASS_COMMON-NEXT: {{^}} init(){{$}}
// PASS_COMMON-NEXT: {{^}} }{{$}}
typealias `protocol` = `class`
// PASS_ONE_LINE_TYPE-DAG: {{^}} typealias `protocol` = d0200_EscapedIdentifiers.`class`{{$}}
// PASS_ONE_LINE_TYPEREPR-DAG: {{^}} typealias `protocol` = `class`{{$}}
class `extension` : `class` {}
// PASS_ONE_LINE_TYPE-DAG: {{^}} @_inheritsConvenienceInitializers class `extension` : d0200_EscapedIdentifiers.`class` {{{$}}
// PASS_ONE_LINE_TYPEREPR-DAG: {{^}} @_inheritsConvenienceInitializers class `extension` : `class` {{{$}}
// PASS_COMMON: {{^}} @objc deinit{{$}}
// PASS_COMMON-NEXT: {{^}} {{(override )?}}init(){{$}}
// PASS_COMMON-NEXT: {{^}} }{{$}}
func `func`<`let`: `protocol`, `where`>(
class: Int, struct: `protocol`, foo: `let`, bar: `where`) where `where` : `protocol` {}
// PASS_COMMON-NEXT: {{^}} func `func`<`let`, `where`>(class: Int, struct: {{(d0200_EscapedIdentifiers.)?}}`protocol`, foo: `let`, bar: `where`) where `let` : {{(d0200_EscapedIdentifiers.)?}}`protocol`, `where` : {{(d0200_EscapedIdentifiers.)?}}`protocol`{{$}}
var `var`: `struct` = `struct`()
// PASS_COMMON-NEXT: {{^}} @_hasInitialValue var `var`: {{(d0200_EscapedIdentifiers.)?}}`struct`{{$}}
var tupleType: (`var`: Int, `let`: `struct`)
// PASS_COMMON-NEXT: {{^}} var tupleType: (var: Int, let: {{(d0200_EscapedIdentifiers.)?}}`struct`){{$}}
var accessors1: Int {
get { return 0 }
set(`let`) {}
}
// PASS_COMMON-NEXT: {{^}} var accessors1: Int{{( { get set })?}}{{$}}
static func `static`(protocol: Int) {}
// PASS_COMMON-NEXT: {{^}} static func `static`(protocol: Int){{$}}
// PASS_COMMON-NEXT: {{^}} init(var: {{(d0200_EscapedIdentifiers.)?}}`struct` = {{(d0200_EscapedIdentifiers.)?}}`struct`(), tupleType: (var: Int, let: {{(d0200_EscapedIdentifiers.)?}}`struct`)){{$}}
// PASS_COMMON-NEXT: {{^}}}{{$}}
}
struct d0210_Qualifications {
// PASS_QUAL_UNQUAL: {{^}}struct d0210_Qualifications {{{$}}
// PASS_QUAL_IF_AMBIGUOUS: {{^}}struct d0210_Qualifications {{{$}}
var propFromStdlib1: Int = 0
// PASS_QUAL_UNQUAL-NEXT: {{^}} @_hasInitialValue var propFromStdlib1: Int{{$}}
// PASS_QUAL_IF_AMBIGUOUS-NEXT: {{^}} @_hasInitialValue var propFromStdlib1: Int{{$}}
var propFromSwift1: FooSwiftStruct = FooSwiftStruct()
// PASS_QUAL_UNQUAL-NEXT: {{^}} @_hasInitialValue var propFromSwift1: FooSwiftStruct{{$}}
// PASS_QUAL_IF_AMBIGUOUS-NEXT: {{^}} @_hasInitialValue var propFromSwift1: foo_swift_module.FooSwiftStruct{{$}}
var propFromClang1: FooStruct1 = FooStruct1(x: 0, y: 0.0)
// PASS_QUAL_UNQUAL-NEXT: {{^}} @_hasInitialValue var propFromClang1: FooStruct1{{$}}
// PASS_QUAL_IF_AMBIGUOUS-NEXT: {{^}} @_hasInitialValue var propFromClang1: FooStruct1{{$}}
func instanceFuncFromStdlib1(a: Int) -> Float {
return 0.0
}
// PASS_QUAL_UNQUAL-NEXT: {{^}} func instanceFuncFromStdlib1(a: Int) -> Float{{$}}
// PASS_QUAL_IF_AMBIGUOUS-NEXT: {{^}} func instanceFuncFromStdlib1(a: Int) -> Float{{$}}
func instanceFuncFromStdlib2(a: ObjCBool) {}
// PASS_QUAL_UNQUAL-NEXT: {{^}} func instanceFuncFromStdlib2(a: ObjCBool){{$}}
// PASS_QUAL_IF_AMBIGUOUS-NEXT: {{^}} func instanceFuncFromStdlib2(a: ObjCBool){{$}}
func instanceFuncFromSwift1(a: FooSwiftStruct) -> FooSwiftStruct {
return FooSwiftStruct()
}
// PASS_QUAL_UNQUAL-NEXT: {{^}} func instanceFuncFromSwift1(a: FooSwiftStruct) -> FooSwiftStruct{{$}}
// PASS_QUAL_IF_AMBIGUOUS-NEXT: {{^}} func instanceFuncFromSwift1(a: foo_swift_module.FooSwiftStruct) -> foo_swift_module.FooSwiftStruct{{$}}
func instanceFuncFromClang1(a: FooStruct1) -> FooStruct1 {
return FooStruct1(x: 0, y: 0.0)
}
// PASS_QUAL_UNQUAL-NEXT: {{^}} func instanceFuncFromClang1(a: FooStruct1) -> FooStruct1{{$}}
// PASS_QUAL_IF_AMBIGUOUS-NEXT: {{^}} func instanceFuncFromClang1(a: FooStruct1) -> FooStruct1{{$}}
}
// FIXME: this should be printed reasonably in case we use
// -prefer-type-repr=true. Either we should print the types we inferred, or we
// should print the initializers.
class d0250_ExplodePattern {
// PASS_EXPLODE_PATTERN-LABEL: {{^}}class d0250_ExplodePattern {{{$}}
var instanceVar1 = 0
var instanceVar2 = 0.0
var instanceVar3 = ""
// PASS_EXPLODE_PATTERN: {{^}} @_hasInitialValue var instanceVar1: Int{{$}}
// PASS_EXPLODE_PATTERN: {{^}} @_hasInitialValue var instanceVar2: Double{{$}}
// PASS_EXPLODE_PATTERN: {{^}} @_hasInitialValue var instanceVar3: String{{$}}
var instanceVar4 = FooStruct()
var (instanceVar5, instanceVar6) = (FooStruct(), FooStruct())
var (instanceVar7, instanceVar8) = (FooStruct(), FooStruct())
var (instanceVar9, instanceVar10) : (FooStruct, FooStruct) = (FooStruct(), FooStruct())
final var (instanceVar11, instanceVar12) = (FooStruct(), FooStruct())
// PASS_EXPLODE_PATTERN: {{^}} @_hasInitialValue var instanceVar4: FooStruct{{$}}
// PASS_EXPLODE_PATTERN: {{^}} @_hasInitialValue var instanceVar5: FooStruct{{$}}
// PASS_EXPLODE_PATTERN: {{^}} @_hasInitialValue var instanceVar6: FooStruct{{$}}
// PASS_EXPLODE_PATTERN: {{^}} @_hasInitialValue var instanceVar7: FooStruct{{$}}
// PASS_EXPLODE_PATTERN: {{^}} @_hasInitialValue var instanceVar8: FooStruct{{$}}
// PASS_EXPLODE_PATTERN: {{^}} @_hasInitialValue var instanceVar9: FooStruct{{$}}
// PASS_EXPLODE_PATTERN: {{^}} @_hasInitialValue var instanceVar10: FooStruct{{$}}
// PASS_EXPLODE_PATTERN: {{^}} @_hasInitialValue final var instanceVar11: FooStruct{{$}}
// PASS_EXPLODE_PATTERN: {{^}} @_hasInitialValue final var instanceVar12: FooStruct{{$}}
let instanceLet1 = 0
let instanceLet2 = 0.0
let instanceLet3 = ""
// PASS_EXPLODE_PATTERN: {{^}} @_hasInitialValue final let instanceLet1: Int{{$}}
// PASS_EXPLODE_PATTERN: {{^}} @_hasInitialValue final let instanceLet2: Double{{$}}
// PASS_EXPLODE_PATTERN: {{^}} @_hasInitialValue final let instanceLet3: String{{$}}
let instanceLet4 = FooStruct()
let (instanceLet5, instanceLet6) = (FooStruct(), FooStruct())
let (instanceLet7, instanceLet8) = (FooStruct(), FooStruct())
let (instanceLet9, instanceLet10) : (FooStruct, FooStruct) = (FooStruct(), FooStruct())
// PASS_EXPLODE_PATTERN: {{^}} @_hasInitialValue final let instanceLet4: FooStruct{{$}}
// PASS_EXPLODE_PATTERN: {{^}} @_hasInitialValue final let instanceLet5: FooStruct{{$}}
// PASS_EXPLODE_PATTERN: {{^}} @_hasInitialValue final let instanceLet6: FooStruct{{$}}
// PASS_EXPLODE_PATTERN: {{^}} @_hasInitialValue final let instanceLet7: FooStruct{{$}}
// PASS_EXPLODE_PATTERN: {{^}} @_hasInitialValue final let instanceLet8: FooStruct{{$}}
// PASS_EXPLODE_PATTERN: {{^}} @_hasInitialValue final let instanceLet9: FooStruct{{$}}
// PASS_EXPLODE_PATTERN: {{^}} @_hasInitialValue final let instanceLet10: FooStruct{{$}}
}
class d0260_ExplodePattern_TestClassBase {
// PASS_EXPLODE_PATTERN-LABEL: {{^}}class d0260_ExplodePattern_TestClassBase {{{$}}
init() {
baseProp1 = 0
}
// PASS_EXPLODE_PATTERN-NEXT: {{^}} init(){{$}}
final var baseProp1: Int
// PASS_EXPLODE_PATTERN-NEXT: {{^}} final var baseProp1: Int{{$}}
var baseProp2: Int {
get {
return 0
}
set {}
}
// PASS_EXPLODE_PATTERN-NEXT: {{^}} var baseProp2: Int{{$}}
}
class d0261_ExplodePattern_TestClassDerived : d0260_ExplodePattern_TestClassBase {
// PASS_EXPLODE_PATTERN-LABEL: {{^}}@_inheritsConvenienceInitializers class d0261_ExplodePattern_TestClassDerived : d0260_ExplodePattern_TestClassBase {{{$}}
override final var baseProp2: Int {
get {
return 0
}
set {}
}
// PASS_EXPLODE_PATTERN-NEXT: {{^}} override final var baseProp2: Int{{$}}
}
//===---
//===--- Inheritance list in structs.
//===---
struct StructWithoutInheritance1 {}
// PASS_ONE_LINE-DAG: {{^}}struct StructWithoutInheritance1 {{{$}}
struct StructWithInheritance1 : FooProtocol {}
// PASS_ONE_LINE-DAG: {{^}}struct StructWithInheritance1 : FooProtocol {{{$}}
struct StructWithInheritance2 : FooProtocol, BarProtocol {}
// PASS_ONE_LINE-DAG: {{^}}struct StructWithInheritance2 : FooProtocol, BarProtocol {{{$}}
struct StructWithInheritance3 : QuxProtocol, SubFooProtocol {
typealias Qux = Int
}
// PASS_ONE_LINE-DAG: {{^}}struct StructWithInheritance3 : QuxProtocol, SubFooProtocol {{{$}}
//===---
//===--- Inheritance list in classes.
//===---
class ClassWithoutInheritance1 {}
// PASS_ONE_LINE-DAG: {{^}}class ClassWithoutInheritance1 {{{$}}
class ClassWithInheritance1 : FooProtocol {}
// PASS_ONE_LINE-DAG: {{^}}class ClassWithInheritance1 : FooProtocol {{{$}}
class ClassWithInheritance2 : FooProtocol, BarProtocol {}
// PASS_ONE_LINE-DAG: {{^}}class ClassWithInheritance2 : FooProtocol, BarProtocol {{{$}}
class ClassWithInheritance3 : FooClass {}
// PASS_ONE_LINE-DAG: {{^}}@_inheritsConvenienceInitializers class ClassWithInheritance3 : FooClass {{{$}}
class ClassWithInheritance4 : FooClass, FooProtocol {}
// PASS_ONE_LINE-DAG: {{^}}@_inheritsConvenienceInitializers class ClassWithInheritance4 : FooClass, FooProtocol {{{$}}
class ClassWithInheritance5 : FooClass, FooProtocol, BarProtocol {}
// PASS_ONE_LINE-DAG: {{^}}@_inheritsConvenienceInitializers class ClassWithInheritance5 : FooClass, FooProtocol, BarProtocol {{{$}}
class ClassWithInheritance6 : QuxProtocol, SubFooProtocol {
typealias Qux = Int
}
// PASS_ONE_LINE-DAG: {{^}}class ClassWithInheritance6 : QuxProtocol, SubFooProtocol {{{$}}
//===---
//===--- Inheritance list in enums.
//===---
enum EnumWithoutInheritance1 {}
// PASS_ONE_LINE-DAG: {{^}}enum EnumWithoutInheritance1 {{{$}}
enum EnumWithInheritance1 : FooProtocol {}
// PASS_ONE_LINE-DAG: {{^}}enum EnumWithInheritance1 : FooProtocol {{{$}}
enum EnumWithInheritance2 : FooProtocol, BarProtocol {}
// PASS_ONE_LINE-DAG: {{^}}enum EnumWithInheritance2 : FooProtocol, BarProtocol {{{$}}
enum EnumDeclWithUnderlyingType1 : Int { case X }
// PASS_ONE_LINE-DAG: {{^}}enum EnumDeclWithUnderlyingType1 : Int {{{$}}
enum EnumDeclWithUnderlyingType2 : Int, FooProtocol { case X }
// PASS_ONE_LINE-DAG: {{^}}enum EnumDeclWithUnderlyingType2 : Int, FooProtocol {{{$}}
enum EnumWithInheritance3 : QuxProtocol, SubFooProtocol {
typealias Qux = Int
}
// PASS_ONE_LINE-DAG: {{^}}enum EnumWithInheritance3 : QuxProtocol, SubFooProtocol {{{$}}
//===---
//===--- Inheritance list in protocols.
//===---
protocol ProtocolWithoutInheritance1 {}
// PASS_ONE_LINE-DAG: {{^}}protocol ProtocolWithoutInheritance1 {{{$}}
protocol ProtocolWithInheritance1 : FooProtocol {}
// PASS_ONE_LINE-DAG: {{^}}protocol ProtocolWithInheritance1 : FooProtocol {{{$}}
protocol ProtocolWithInheritance2 : FooProtocol, BarProtocol { }
// PASS_ONE_LINE-DAG: {{^}}protocol ProtocolWithInheritance2 : BarProtocol, FooProtocol {{{$}}
protocol ProtocolWithInheritance3 : QuxProtocol, SubFooProtocol {
}
// PASS_ONE_LINE-DAG: {{^}}protocol ProtocolWithInheritance3 : QuxProtocol, SubFooProtocol {{{$}}
//===---
//===--- Inheritance list in extensions
//===---
struct StructInherited { }
// PASS_ONE_LINE-DAG: {{.*}}extension StructInherited : QuxProtocol, SubFooProtocol {{{$}}
extension StructInherited : QuxProtocol, SubFooProtocol {
typealias Qux = Int
}
//===---
//===--- Typealias printing.
//===---
// Normal typealiases.
typealias SimpleTypealias1 = FooProtocol
// PASS_ONE_LINE-DAG: {{^}}typealias SimpleTypealias1 = FooProtocol{{$}}
// Associated types.
protocol AssociatedType1 {
associatedtype AssociatedTypeDecl1 = Int
// PASS_ONE_LINE-DAG: {{^}} associatedtype AssociatedTypeDecl1 = Int{{$}}
associatedtype AssociatedTypeDecl2 : FooProtocol
// PASS_ONE_LINE-DAG: {{^}} associatedtype AssociatedTypeDecl2 : FooProtocol{{$}}
associatedtype AssociatedTypeDecl3 : FooProtocol, BarProtocol
// PASS_ONE_LINE_TYPEREPR-DAG: {{^}} associatedtype AssociatedTypeDecl3 : BarProtocol, FooProtocol{{$}}
associatedtype AssociatedTypeDecl4 where AssociatedTypeDecl4 : QuxProtocol, AssociatedTypeDecl4.Qux == Int
// PASS_ONE_LINE_TYPEREPR-DAG: {{^}} associatedtype AssociatedTypeDecl4 : QuxProtocol where Self.AssociatedTypeDecl4.Qux == Int{{$}}
associatedtype AssociatedTypeDecl5: FooClass
// PASS_ONE_LINE_TYPEREPR-DAG: {{^}} associatedtype AssociatedTypeDecl5 : FooClass{{$}}
}
//===---
//===--- Variable declaration printing.
//===---
var d0300_topLevelVar1: Int = 42
// PASS_COMMON: {{^}}@_hasInitialValue var d0300_topLevelVar1: Int{{$}}
// PASS_COMMON-NOT: d0300_topLevelVar1
var d0400_topLevelVar2: Int = 42
// PASS_COMMON: {{^}}@_hasInitialValue var d0400_topLevelVar2: Int{{$}}
// PASS_COMMON-NOT: d0400_topLevelVar2
var d0500_topLevelVar2: Int {
get {
return 42
}
}
// PASS_COMMON: {{^}}var d0500_topLevelVar2: Int { get }{{$}}
// PASS_COMMON-NOT: d0500_topLevelVar2
class d0600_InClassVar1 {
// PASS_O600-LABEL: d0600_InClassVar1
var instanceVar1: Int
// PASS_COMMON: {{^}} var instanceVar1: Int{{$}}
// PASS_COMMON-NOT: instanceVar1
var instanceVar2: Int = 42
// PASS_COMMON: {{^}} @_hasInitialValue var instanceVar2: Int{{$}}
// PASS_COMMON-NOT: instanceVar2
// FIXME: this is sometimes printed without a type, see PASS_EXPLODE_PATTERN.
// FIXME: PRINTED_WITHOUT_TYPE
var instanceVar3 = 42
// PASS_COMMON: {{^}} @_hasInitialValue var instanceVar3
// PASS_COMMON-NOT: instanceVar3
var instanceVar4: Int {
get {
return 42
}
}
// PASS_COMMON: {{^}} var instanceVar4: Int { get }{{$}}
// PASS_COMMON-NOT: instanceVar4
// FIXME: uncomment when we have static vars.
// static var staticVar1: Int
init() {
instanceVar1 = 10
}
}
//===---
//===--- Subscript declaration printing.
//===---
class d0700_InClassSubscript1 {
// PASS_COMMON-LABEL: d0700_InClassSubscript1
subscript(i: Int) -> Int {
get {
return 42
}
}
subscript(index i: Float) -> Int { return 42 }
class `class` {}
subscript(x: Float) -> `class` { return `class`() }
// PASS_COMMON: {{^}} subscript(i: Int) -> Int { get }{{$}}
// PASS_COMMON: {{^}} subscript(index i: Float) -> Int { get }{{$}}
// PASS_COMMON: {{^}} subscript(x: Float) -> {{.*}} { get }{{$}}
// PASS_COMMON-NOT: subscript
// PASS_ONE_LINE_TYPE: {{^}} subscript(x: Float) -> d0700_InClassSubscript1.`class` { get }{{$}}
// PASS_ONE_LINE_TYPEREPR: {{^}} subscript(x: Float) -> `class` { get }{{$}}
}
// PASS_COMMON: {{^}}}{{$}}
//===---
//===--- Constructor declaration printing.
//===---
struct d0800_ExplicitConstructors1 {
// PASS_COMMON-LABEL: d0800_ExplicitConstructors1
init() {}
// PASS_COMMON: {{^}} init(){{$}}
init(a: Int) {}
// PASS_COMMON: {{^}} init(a: Int){{$}}
}
struct d0900_ExplicitConstructorsSelector1 {
// PASS_COMMON-LABEL: d0900_ExplicitConstructorsSelector1
init(int a: Int) {}
// PASS_COMMON: {{^}} init(int a: Int){{$}}
init(int a: Int, andFloat b: Float) {}
// PASS_COMMON: {{^}} init(int a: Int, andFloat b: Float){{$}}
}
struct d1000_ExplicitConstructorsSelector2 {
// PASS_COMMON-LABEL: d1000_ExplicitConstructorsSelector2
init(noArgs _: ()) {}
// PASS_COMMON: {{^}} init(noArgs _: ()){{$}}
init(_ a: Int) {}
// PASS_COMMON: {{^}} init(_ a: Int){{$}}
init(_ a: Int, withFloat b: Float) {}
// PASS_COMMON: {{^}} init(_ a: Int, withFloat b: Float){{$}}
init(int a: Int, _ b: Float) {}
// PASS_COMMON: {{^}} init(int a: Int, _ b: Float){{$}}
}
//===---
//===--- Destructor declaration printing.
//===---
class d1100_ExplicitDestructor1 {
// PASS_COMMON-LABEL: d1100_ExplicitDestructor1
deinit {}
// PASS_COMMON: {{^}} @objc deinit{{$}}
}
//===---
//===--- Enum declaration printing.
//===---
enum d2000_EnumDecl1 {
case ED1_First
case ED1_Second
}
// PASS_COMMON: {{^}}enum d2000_EnumDecl1 {{{$}}
// PASS_COMMON-NEXT: {{^}} case ED1_First{{$}}
// PASS_COMMON-NEXT: {{^}} case ED1_Second{{$}}
// PASS_COMMON-NEXT: {{^}} {{.*}}static func __derived_enum_equals(_ a: d2000_EnumDecl1, _ b: d2000_EnumDecl1) -> Bool
// PASS_COMMON-NEXT: {{^}} var hashValue: Int { get }{{$}}
// PASS_COMMON-NEXT: {{^}} func hash(into hasher: inout Hasher)
// PASS_COMMON-NEXT: {{^}}}{{$}}
enum d2100_EnumDecl2 {
case ED2_A(Int)
case ED2_B(Float)
case ED2_C(Int, Float)
case ED2_D(x: Int, y: Float)
case ED2_E(x: Int, y: (Float, Double))
case ED2_F(x: Int, (y: Float, z: Double))
}
// PASS_COMMON: {{^}}enum d2100_EnumDecl2 {{{$}}
// PASS_COMMON-NEXT: {{^}} case ED2_A(Int){{$}}
// PASS_COMMON-NEXT: {{^}} case ED2_B(Float){{$}}
// PASS_COMMON-NEXT: {{^}} case ED2_C(Int, Float){{$}}
// PASS_COMMON-NEXT: {{^}} case ED2_D(x: Int, y: Float){{$}}
// PASS_COMMON-NEXT: {{^}} case ED2_E(x: Int, y: (Float, Double)){{$}}
// PASS_COMMON-NEXT: {{^}} case ED2_F(x: Int, (y: Float, z: Double)){{$}}
// PASS_COMMON-NEXT: {{^}}}{{$}}
enum d2200_EnumDecl3 {
case ED3_A, ED3_B
case ED3_C(Int), ED3_D
case ED3_E, ED3_F(Int)
case ED3_G(Int), ED3_H(Int)
case ED3_I(Int), ED3_J(Int), ED3_K
}
// PASS_2200: {{^}}enum d2200_EnumDecl3 {{{$}}
// PASS_2200-NEXT: {{^}} case ED3_A, ED3_B{{$}}
// PASS_2200-NEXT: {{^}} case ED3_C(Int), ED3_D{{$}}
// PASS_2200-NEXT: {{^}} case ED3_E, ED3_F(Int){{$}}
// PASS_2200-NEXT: {{^}} case ED3_G(Int), ED3_H(Int){{$}}
// PASS_2200-NEXT: {{^}} case ED3_I(Int), ED3_J(Int), ED3_K{{$}}
// PASS_2200-NEXT: {{^}}}{{$}}
// PASS_2200_DESERIALIZED: {{^}}enum d2200_EnumDecl3 {{{$}}
// PASS_2200_DESERIALIZED-NEXT: {{^}} case ED3_A{{$}}
// PASS_2200_DESERIALIZED-NEXT: {{^}} case ED3_B{{$}}
// PASS_2200_DESERIALIZED-NEXT: {{^}} case ED3_C(Int){{$}}
// PASS_2200_DESERIALIZED-NEXT: {{^}} case ED3_D{{$}}
// PASS_2200_DESERIALIZED-NEXT: {{^}} case ED3_E{{$}}
// PASS_2200_DESERIALIZED-NEXT: {{^}} case ED3_F(Int){{$}}
// PASS_2200_DESERIALIZED-NEXT: {{^}} case ED3_G(Int){{$}}
// PASS_2200_DESERIALIZED-NEXT: {{^}} case ED3_H(Int){{$}}
// PASS_2200_DESERIALIZED-NEXT: {{^}} case ED3_I(Int){{$}}
// PASS_2200_DESERIALIZED-NEXT: {{^}} case ED3_J(Int){{$}}
// PASS_2200_DESERIALIZED-NEXT: {{^}} case ED3_K{{$}}
// PASS_2200_DESERIALIZED-NEXT: {{^}}}{{$}}
enum d2300_EnumDeclWithValues1 : Int {
case EDV2_First = 10
case EDV2_Second
}
// PASS_COMMON: {{^}}enum d2300_EnumDeclWithValues1 : Int {{{$}}
// PASS_COMMON-NEXT: {{^}} case EDV2_First{{$}}
// PASS_COMMON-NEXT: {{^}} case EDV2_Second{{$}}
// PASS_COMMON-DAG: {{^}} typealias RawValue = Int
// PASS_COMMON-DAG: {{^}} init?(rawValue: Int){{$}}
// PASS_COMMON-DAG: {{^}} var rawValue: Int { get }{{$}}
// PASS_COMMON: {{^}}}{{$}}
enum d2400_EnumDeclWithValues2 : Double {
case EDV3_First = 10
case EDV3_Second
}
// PASS_COMMON: {{^}}enum d2400_EnumDeclWithValues2 : Double {{{$}}
// PASS_COMMON-NEXT: {{^}} case EDV3_First{{$}}
// PASS_COMMON-NEXT: {{^}} case EDV3_Second{{$}}
// PASS_COMMON-DAG: {{^}} typealias RawValue = Double
// PASS_COMMON-DAG: {{^}} init?(rawValue: Double){{$}}
// PASS_COMMON-DAG: {{^}} var rawValue: Double { get }{{$}}
// PASS_COMMON: {{^}}}{{$}}
//===---
//===--- Custom operator printing.
//===---
postfix operator <*>
// PASS_2500-LABEL: {{^}}postfix operator <*>{{$}}
protocol d2600_ProtocolWithOperator1 {
static postfix func <*>(_: Self)
}
// PASS_2500: {{^}}protocol d2600_ProtocolWithOperator1 {{{$}}
// PASS_2500-NEXT: {{^}} postfix static func <*> (_: Self){{$}}
// PASS_2500-NEXT: {{^}}}{{$}}
struct d2601_TestAssignment {}
infix operator %%%
func %%%(lhs: inout d2601_TestAssignment, rhs: d2601_TestAssignment) -> Int {
return 0
}
// PASS_2500-LABEL: {{^}}infix operator %%% : DefaultPrecedence{{$}}
// PASS_2500: {{^}}func %%% (lhs: inout d2601_TestAssignment, rhs: d2601_TestAssignment) -> Int{{$}}
precedencegroup BoringPrecedence {
// PASS_2500-LABEL: {{^}}precedencegroup BoringPrecedence {{{$}}
associativity: left
// PASS_2500-NEXT: {{^}} associativity: left{{$}}
higherThan: AssignmentPrecedence
// PASS_2500-NEXT: {{^}} higherThan: AssignmentPrecedence{{$}}
// PASS_2500-NOT: assignment
// PASS_2500-NOT: lowerThan
}
precedencegroup ReallyBoringPrecedence {
// PASS_2500-LABEL: {{^}}precedencegroup ReallyBoringPrecedence {{{$}}
associativity: right
// PASS_2500-NEXT: {{^}} associativity: right{{$}}
// PASS_2500-NOT: higherThan
// PASS_2500-NOT: lowerThan
// PASS_2500-NOT: assignment
}
precedencegroup BoringAssignmentPrecedence {
// PASS_2500-LABEL: {{^}}precedencegroup BoringAssignmentPrecedence {{{$}}
lowerThan: AssignmentPrecedence
assignment: true
// PASS_2500-NEXT: {{^}} assignment: true{{$}}
// PASS_2500-NEXT: {{^}} lowerThan: AssignmentPrecedence{{$}}
// PASS_2500-NOT: associativity
// PASS_2500-NOT: higherThan
}
// PASS_2500: {{^}}}{{$}}
//===---
//===--- Printing of deduced associated types.
//===---
protocol d2700_ProtocolWithAssociatedType1 {
associatedtype TA1
func returnsTA1() -> TA1
}
// PREFER_TYPE_PRINTING: {{^}}protocol d2700_ProtocolWithAssociatedType1 {{{$}}
// PREFER_TYPE_PRINTING-NEXT: {{^}} associatedtype TA1{{$}}
// PREFER_TYPE_PRINTING-NEXT: {{^}} func returnsTA1() -> Self.TA1{{$}}
// PREFER_TYPE_PRINTING-NEXT: {{^}}}{{$}}
// PREFER_TYPEREPR_PRINTING: {{^}}protocol d2700_ProtocolWithAssociatedType1 {{{$}}
// PREFER_TYPEREPR_PRINTING-NEXT: {{^}} associatedtype TA1{{$}}
// PREFER_TYPEREPR_PRINTING-NEXT: {{^}} func returnsTA1() -> TA1{{$}}
// PREFER_TYPEREPR_PRINTING-NEXT: {{^}}}{{$}}
struct d2800_ProtocolWithAssociatedType1Impl : d2700_ProtocolWithAssociatedType1 {
func returnsTA1() -> Int {
return 42
}
}
// PASS_COMMON: {{^}}struct d2800_ProtocolWithAssociatedType1Impl : d2700_ProtocolWithAssociatedType1 {{{$}}
// PASS_COMMON-NEXT: {{^}} func returnsTA1() -> Int{{$}}
// PASS_COMMON-NEXT: {{^}} init(){{$}}
// PASS_COMMON-NEXT: {{^}} typealias TA1 = Int
// PASS_COMMON-NEXT: {{^}}}{{$}}
//===---
//===--- Generic parameter list printing.
//===---
struct GenericParams1<
StructGenericFoo : FooProtocol,
StructGenericFooX : FooClass,
StructGenericBar : FooProtocol & BarProtocol,
StructGenericBaz> {
// PASS_ONE_LINE_TYPE-DAG: {{^}}struct GenericParams1<StructGenericFoo, StructGenericFooX, StructGenericBar, StructGenericBaz> where StructGenericFoo : FooProtocol, StructGenericFooX : FooClass, StructGenericBar : BarProtocol, StructGenericBar : FooProtocol {{{$}}
// PASS_ONE_LINE_TYPEREPR-DAG: {{^}}struct GenericParams1<StructGenericFoo, StructGenericFooX, StructGenericBar, StructGenericBaz> where StructGenericFoo : FooProtocol, StructGenericFooX : FooClass, StructGenericBar : BarProtocol, StructGenericBar : FooProtocol {{{$}}
init<
GenericFoo : FooProtocol,
GenericFooX : FooClass,
GenericBar : FooProtocol & BarProtocol,
GenericBaz>(a: StructGenericFoo, b: StructGenericBar, c: StructGenericBaz,
d: GenericFoo, e: GenericFooX, f: GenericBar, g: GenericBaz)
{}
// PASS_ONE_LINE_TYPE-DAG: {{^}} init<GenericFoo, GenericFooX, GenericBar, GenericBaz>(a: StructGenericFoo, b: StructGenericBar, c: StructGenericBaz, d: GenericFoo, e: GenericFooX, f: GenericBar, g: GenericBaz) where GenericFoo : FooProtocol, GenericFooX : FooClass, GenericBar : BarProtocol, GenericBar : FooProtocol{{$}}
// FIXME: in protocol compositions protocols are listed in reverse order.
//
// PASS_ONE_LINE_TYPEREPR-DAG: {{^}} init<GenericFoo, GenericFooX, GenericBar, GenericBaz>(a: StructGenericFoo, b: StructGenericBar, c: StructGenericBaz, d: GenericFoo, e: GenericFooX, f: GenericBar, g: GenericBaz) where GenericFoo : FooProtocol, GenericFooX : FooClass, GenericBar : BarProtocol, GenericBar : FooProtocol{{$}}
func genericParams1<
GenericFoo : FooProtocol,
GenericFooX : FooClass,
GenericBar : FooProtocol & BarProtocol,
GenericBaz>(a: StructGenericFoo, b: StructGenericBar, c: StructGenericBaz,
d: GenericFoo, e: GenericFooX, f: GenericBar, g: GenericBaz)
{}
// PASS_ONE_LINE_TYPE-DAG: {{^}} func genericParams1<GenericFoo, GenericFooX, GenericBar, GenericBaz>(a: StructGenericFoo, b: StructGenericBar, c: StructGenericBaz, d: GenericFoo, e: GenericFooX, f: GenericBar, g: GenericBaz) where GenericFoo : FooProtocol, GenericFooX : FooClass, GenericBar : BarProtocol, GenericBar : FooProtocol{{$}}
// FIXME: in protocol compositions protocols are listed in reverse order.
//
// PASS_ONE_LINE_TYPEREPR-DAG: {{^}} func genericParams1<GenericFoo, GenericFooX, GenericBar, GenericBaz>(a: StructGenericFoo, b: StructGenericBar, c: StructGenericBaz, d: GenericFoo, e: GenericFooX, f: GenericBar, g: GenericBaz) where GenericFoo : FooProtocol, GenericFooX : FooClass, GenericBar : BarProtocol, GenericBar : FooProtocol{{$}}
func contextualWhereClause1() where StructGenericBaz == Never {}
// PASS_PRINT_AST: func contextualWhereClause1() where StructGenericBaz == Never{{$}}
subscript(index: Int) -> Never where StructGenericBaz: FooProtocol {
return fatalError()
}
// PASS_PRINT_AST: subscript(index: Int) -> Never where StructGenericBaz : FooProtocol { get }{{$}}
}
extension GenericParams1 where StructGenericBaz: FooProtocol {
static func contextualWhereClause2() where StructGenericBaz: FooClass {}
// PASS_PRINT_AST: static func contextualWhereClause2() where StructGenericBaz : FooClass{{$}}
typealias ContextualWhereClause3 = Never where StructGenericBaz: QuxProtocol, StructGenericBaz.Qux == Void
// PASS_PRINT_AST: typealias ContextualWhereClause3 = Never where StructGenericBaz : QuxProtocol, StructGenericBaz.Qux == Void{{$}}
}
struct GenericParams2<T : FooProtocol> where T : BarProtocol {}
// PASS_ONE_LINE-DAG: {{^}}struct GenericParams2<T> where T : BarProtocol, T : FooProtocol {{{$}}
struct GenericParams3<T : FooProtocol> where T : BarProtocol, T : QuxProtocol {}
// PASS_ONE_LINE-DAG: {{^}}struct GenericParams3<T> where T : BarProtocol, T : FooProtocol, T : QuxProtocol {{{$}}
struct GenericParams4<T : QuxProtocol> where T.Qux : FooProtocol {}
// PASS_ONE_LINE-DAG: {{^}}struct GenericParams4<T> where T : QuxProtocol, T.Qux : FooProtocol {{{$}}
struct GenericParams5<T : QuxProtocol> where T.Qux : FooProtocol & BarProtocol {}
// PREFER_TYPE_PRINTING: {{^}}struct GenericParams5<T> where T : QuxProtocol, T.Qux : BarProtocol, T.Qux : FooProtocol {{{$}}
// PREFER_TYPE_REPR_PRINTING: {{^}}struct GenericParams5<T> where T : QuxProtocol, T.Qux : BarProtocol, T.Qux : FooProtocol {{{$}}
struct GenericParams6<T : QuxProtocol, U : QuxProtocol> where T.Qux == U.Qux {}
// PREFER_TYPE_PRINTING: {{^}}struct GenericParams6<T, U> where T : QuxProtocol, U : QuxProtocol, T.Qux == U.Qux {{{$}}
// PREFER_TYPE_REPR_PRINTING: {{^}}struct GenericParams6<T, U> where T : QuxProtocol, U : QuxProtocol, T.Qux == U.Qux {{{$}}
struct GenericParams7<T : QuxProtocol, U : QuxProtocol> where T.Qux : QuxProtocol, U.Qux : QuxProtocol, T.Qux.Qux == U.Qux.Qux {}
// PREFER_TYPE_PRINTING: {{^}}struct GenericParams7<T, U> where T : QuxProtocol, U : QuxProtocol, T.Qux : QuxProtocol, U.Qux : QuxProtocol, T.Qux.Qux == U.Qux.Qux {{{$}}
// PREFER_TYPE_REPR_PRINTING: {{^}}struct GenericParams7<T, U> where T : QuxProtocol, U : QuxProtocol, T.Qux : QuxProtocol, U.Qux : QuxProtocol, T.Qux.Qux == U.Qux.Qux {{{$}}
//===---
//===--- Tupe sugar for library types.
//===---
struct d2900_TypeSugar1 {
// PASS_COMMON-LABEL: {{^}}struct d2900_TypeSugar1 {{{$}}
// SYNTHESIZE_SUGAR_ON_TYPES-LABEL: {{^}}struct d2900_TypeSugar1 {{{$}}
func f1(x: [Int]) {}
// PASS_COMMON-NEXT: {{^}} func f1(x: [Int]){{$}}
// SYNTHESIZE_SUGAR_ON_TYPES-NEXT: {{^}} func f1(x: [Int]){{$}}
func f2(x: Array<Int>) {}
// PASS_COMMON-NEXT: {{^}} func f2(x: Array<Int>){{$}}
// SYNTHESIZE_SUGAR_ON_TYPES-NEXT: {{^}} func f2(x: [Int]){{$}}
func f3(x: Int?) {}
// PASS_COMMON-NEXT: {{^}} func f3(x: Int?){{$}}
// SYNTHESIZE_SUGAR_ON_TYPES-NEXT: {{^}} func f3(x: Int?){{$}}
func f4(x: Optional<Int>) {}
// PASS_COMMON-NEXT: {{^}} func f4(x: Optional<Int>){{$}}
// SYNTHESIZE_SUGAR_ON_TYPES-NEXT: {{^}} func f4(x: Int?){{$}}
func f5(x: [Int]...) {}
// PASS_COMMON-NEXT: {{^}} func f5(x: [Int]...){{$}}
// SYNTHESIZE_SUGAR_ON_TYPES-NEXT: {{^}} func f5(x: [Int]...){{$}}
func f6(x: Array<Int>...) {}
// PASS_COMMON-NEXT: {{^}} func f6(x: Array<Int>...){{$}}
// SYNTHESIZE_SUGAR_ON_TYPES-NEXT: {{^}} func f6(x: [Int]...){{$}}
func f7(x: [Int : Int]...) {}
// PASS_COMMON-NEXT: {{^}} func f7(x: [Int : Int]...){{$}}
// SYNTHESIZE_SUGAR_ON_TYPES-NEXT: {{^}} func f7(x: [Int : Int]...){{$}}
func f8(x: Dictionary<String, Int>...) {}
// PASS_COMMON-NEXT: {{^}} func f8(x: Dictionary<String, Int>...){{$}}
// SYNTHESIZE_SUGAR_ON_TYPES-NEXT: {{^}} func f8(x: [String : Int]...){{$}}
}
// PASS_COMMON-NEXT: {{^}} init(){{$}}
// PASS_COMMON-NEXT: {{^}}}{{$}}
// @discardableResult attribute
public struct DiscardableThingy {
// PASS_PRINT_AST: @discardableResult
// PASS_PRINT_AST-NEXT: public init()
@discardableResult
public init() {}
// PASS_PRINT_AST: @discardableResult
// PASS_PRINT_AST-NEXT: public func useless() -> Int
@discardableResult
public func useless() -> Int { return 0 }
}
// Parameter Attributes.
// <rdar://problem/19775868> Swift 1.2b1: Header gen puts @autoclosure in the wrong place
// PASS_PRINT_AST: public func ParamAttrs1(a: @autoclosure () -> ())
public func ParamAttrs1(a : @autoclosure () -> ()) {
a()
}
// PASS_PRINT_AST: public func ParamAttrs2(a: @autoclosure @escaping () -> ())
public func ParamAttrs2(a : @autoclosure @escaping () -> ()) {
a()
}
// PASS_PRINT_AST: public func ParamAttrs3(a: () -> ())
public func ParamAttrs3(a : () -> ()) {
a()
}
// PASS_PRINT_AST: public func ParamAttrs4(a: @escaping () -> ())
public func ParamAttrs4(a : @escaping () -> ()) {
a()
}
// PASS_PRINT_AST: public func ParamAttrs5(a: (@escaping () -> ()) -> ())
public func ParamAttrs5(a : (@escaping () -> ()) -> ()) {
}
// PASS_PRINT_AST: public typealias ParamAttrs6 = (@autoclosure () -> ()) -> ()
public typealias ParamAttrs6 = (@autoclosure () -> ()) -> ()
// PASS_PRINT_AST: public var ParamAttrs7: (@escaping () -> ()) -> ()
public var ParamAttrs7: (@escaping () -> ()) -> () = { f in f() }
// Setter
// PASS_PRINT_AST: class FooClassComputed {
class FooClassComputed {
// PASS_PRINT_AST: var stored: (((Int) -> Int) -> Int)?
var stored : (((Int) -> Int) -> Int)? = nil
// PASS_PRINT_AST: var computed: ((Int) -> Int) -> Int { get set }
var computed : ((Int) -> Int) -> Int {
get { return stored! }
set { stored = newValue }
}
// PASS_PRINT_AST: }
}
// PASS_PRINT_AST: struct HasDefaultTupleOfNils {
// PASS_PRINT_AST: var x: (Int?, Int?)
// PASS_PRINT_AST: var y: Int?
// PASS_PRINT_AST: var z: Int
// PASS_PRINT_AST: var w: ((Int?, (), Int?), (Int?, Int?))
// PASS_PRINT_AST: init(x: (Int?, Int?) = (nil, nil), y: Int? = nil, z: Int, w: ((Int?, (), Int?), (Int?, Int?)) = ((nil, (), nil), (nil, nil)))
// PASS_PRINT_AST: }
struct HasDefaultTupleOfNils {
var x: (Int?, Int?)
var y: Int?
var z: Int
var w: ((Int?, (), Int?), (Int?, Int?))
}
// Protocol extensions
protocol ProtocolToExtend {
associatedtype Assoc
}
extension ProtocolToExtend where Self.Assoc == Int {}
// PREFER_TYPE_REPR_PRINTING: extension ProtocolToExtend where Self.Assoc == Int {
// Protocol with where clauses
protocol ProtocolWithWhereClause : QuxProtocol where Qux == Int {}
// PREFER_TYPE_REPR_PRINTING: protocol ProtocolWithWhereClause : QuxProtocol where Self.Qux == Int {
protocol ProtocolWithWhereClauseAndAssoc : QuxProtocol where Qux == Int {
// PREFER_TYPE_REPR_PRINTING-DAG: protocol ProtocolWithWhereClauseAndAssoc : QuxProtocol where Self.Qux == Int {
associatedtype A1 : QuxProtocol where A1 : FooProtocol, A1.Qux : QuxProtocol, Int == A1.Qux.Qux
// PREFER_TYPE_REPR_PRINTING-DAG: {{^}} associatedtype A1 : FooProtocol, QuxProtocol where Self.A1.Qux : QuxProtocol, Self.A1.Qux.Qux == Int{{$}}
// FIXME: this same type requirement with Self should be printed here
associatedtype A2 : QuxProtocol where A2.Qux == Self
// PREFER_TYPE_REPR_PRINTING-DAG: {{^}} associatedtype A2 : QuxProtocol where Self == Self.A2.Qux{{$}}
}
#if true
#elseif false
#else
#endif
// PASS_PRINT_AST: #if
// PASS_PRINT_AST: #elseif
// PASS_PRINT_AST: #else
// PASS_PRINT_AST: #endif
public struct MyPair<A, B> { var a: A, b: B }
public typealias MyPairI<B> = MyPair<Int, B>
// PASS_PRINT_AST: public typealias MyPairI<B> = MyPair<Int, B>
public typealias MyPairAlias<T, U> = MyPair<T, U>
// PASS_PRINT_AST: public typealias MyPairAlias<T, U> = MyPair<T, U>
typealias MyPairAlias2<T: FooProtocol, U> = MyPair<T, U> where U: BarProtocol
// PASS_PRINT_AST: typealias MyPairAlias2<T, U> = MyPair<T, U> where T : FooProtocol, U : BarProtocol
|
apache-2.0
|
92eb711c3bc827d543534b6802fdcd04
| 38.940762 | 385 | 0.651052 | 3.708001 | false | false | false | false |
lorentey/Attabench
|
BenchmarkModel/Task.swift
|
2
|
2895
|
// Copyright © 2017 Károly Lőrentey.
// This file is part of Attabench: https://github.com/attaswift/Attabench
// For licensing information, see the file LICENSE.md in the Git repository above.
import Foundation
import GlueKit
public final class Task: Codable, Hashable {
public typealias Bounds = BenchmarkModel.Bounds
public typealias Band = TimeSample.Band
public let name: String
public internal(set) var samples: [Int: TimeSample] = [:]
public let checked: BoolVariable = true
public let isRunnable: BoolVariable = false // transient
public let sampleCount: IntVariable = 0 // transient
enum CodingKey: String, Swift.CodingKey {
case name
case samples
case checked
}
public let newMeasurements = Signal<(size: Int, time: Time)>()
public init(name: String) {
self.name = name
}
public required init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKey.self)
self.name = try container.decode(String.self, forKey: .name)
self.samples = try container.decode([Int: TimeSample].self, forKey: .samples)
self.sampleCount.value = self.samples.values.reduce(0) { $0 + $1.count }
if let checked = try container.decodeIfPresent(Bool.self, forKey: .checked) {
self.checked.value = checked
}
}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKey.self)
try container.encode(self.name, forKey: .name)
try container.encode(self.samples, forKey: .samples)
try container.encode(self.checked.value, forKey: .checked)
}
public func addMeasurement(_ time: Time, forSize size: Int) {
samples.value(for: size, default: TimeSample()).addMeasurement(time)
newMeasurements.send((size, time))
self.sampleCount.value += 1
}
public func bounds(for band: Band, amortized: Bool) -> (size: Bounds<Int>, time: Bounds<Time>) {
var sizeBounds = Bounds<Int>()
var timeBounds = Bounds<Time>()
for (size, sample) in samples {
guard let t = sample[band] else { continue }
let time = amortized ? t / size : t
sizeBounds.insert(size)
timeBounds.insert(time)
}
return (sizeBounds, timeBounds)
}
public var hashValue: Int {
return name.hashValue
}
public static func ==(left: Task, right: Task) -> Bool {
return left.name == right.name
}
public func deleteResults(in range: ClosedRange<Int>? = nil) {
if let range = range {
samples = samples.filter { !range.contains($0.key) }
sampleCount.value = samples.values.reduce(0) { $0 + $1.count }
}
else {
samples = [:]
sampleCount.value = 0
}
}
}
|
mit
|
b9e41bcdcde81dbbacb6cc6aaeb4a12d
| 33.428571 | 100 | 0.628631 | 4.234261 | false | false | false | false |
dreamsxin/swift
|
benchmark/utils/DriverUtils.swift
|
4
|
10758
|
//===--- DriverUtils.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
//
//===----------------------------------------------------------------------===//
import Darwin
struct BenchResults {
var delim: String = ","
var sampleCount: UInt64 = 0
var min: UInt64 = 0
var max: UInt64 = 0
var mean: UInt64 = 0
var sd: UInt64 = 0
var median: UInt64 = 0
init() {}
init(delim: String, sampleCount: UInt64, min: UInt64, max: UInt64, mean: UInt64, sd: UInt64, median: UInt64) {
self.delim = delim
self.sampleCount = sampleCount
self.min = min
self.max = max
self.mean = mean
self.sd = sd
self.median = median
// Sanity the bounds of our results
precondition(self.min <= self.max, "min should always be <= max")
precondition(self.min <= self.mean, "min should always be <= mean")
precondition(self.min <= self.median, "min should always be <= median")
precondition(self.max >= self.mean, "max should always be >= mean")
precondition(self.max >= self.median, "max should always be >= median")
}
}
extension BenchResults : CustomStringConvertible {
var description: String {
return "\(sampleCount)\(delim)\(min)\(delim)\(max)\(delim)\(mean)\(delim)\(sd)\(delim)\(median)"
}
}
struct Test {
let name: String
let index: Int
let f: (Int) -> ()
var run: Bool
init(name: String, n: Int, f: (Int) -> ()) {
self.name = name
self.index = n
self.f = f
run = true
}
}
public var precommitTests: [String : (Int) -> ()] = [:]
public var otherTests: [String : (Int) -> ()] = [:]
enum TestAction {
case Run
case ListTests
case Fail(String)
}
struct TestConfig {
/// The delimiter to use when printing output.
var delim: String = ","
/// The filters applied to our test names.
var filters = [String]()
/// The scalar multiple of the amount of times a test should be run. This
/// enables one to cause tests to run for N iterations longer than they
/// normally would. This is useful when one wishes for a test to run for a
/// longer amount of time to perform performance analysis on the test in
/// instruments.
var iterationScale: Int = 1
/// If we are asked to have a fixed number of iterations, the number of fixed
/// iterations.
var fixedNumIters: UInt = 0
/// The number of samples we should take of each test.
var numSamples: Int = 1
/// Is verbose output enabled?
var verbose: Bool = false
/// Should we only run the "pre-commit" tests?
var onlyPrecommit: Bool = true
/// After we run the tests, should the harness sleep to allow for utilities
/// like leaks that require a PID to run on the test harness.
var afterRunSleep: Int? = nil
/// The list of tests to run.
var tests = [Test]()
mutating func processArguments() -> TestAction {
let validOptions=["--iter-scale", "--num-samples", "--num-iters",
"--verbose", "--delim", "--run-all", "--list", "--sleep"]
let maybeBenchArgs: Arguments? = parseArgs(validOptions)
if maybeBenchArgs == nil {
return .Fail("Failed to parse arguments")
}
let benchArgs = maybeBenchArgs!
if let _ = benchArgs.optionalArgsMap["--list"] {
return .ListTests
}
if let x = benchArgs.optionalArgsMap["--iter-scale"] {
if x.isEmpty { return .Fail("--iter-scale requires a value") }
iterationScale = Int(x)!
}
if let x = benchArgs.optionalArgsMap["--num-iters"] {
if x.isEmpty { return .Fail("--num-iters requires a value") }
fixedNumIters = numericCast(Int(x)!)
}
if let x = benchArgs.optionalArgsMap["--num-samples"] {
if x.isEmpty { return .Fail("--num-samples requires a value") }
numSamples = Int(x)!
}
if let _ = benchArgs.optionalArgsMap["--verbose"] {
verbose = true
print("Verbose")
}
if let x = benchArgs.optionalArgsMap["--delim"] {
if x.isEmpty { return .Fail("--delim requires a value") }
delim = x
}
if let _ = benchArgs.optionalArgsMap["--run-all"] {
onlyPrecommit = false
}
if let x = benchArgs.optionalArgsMap["--sleep"] {
if x.isEmpty {
return .Fail("--sleep requires a non-empty integer value")
}
let v: Int? = Int(x)
if v == nil {
return .Fail("--sleep requires a non-empty integer value")
}
afterRunSleep = v!
}
filters = benchArgs.positionalArgs
return .Run
}
mutating func findTestsToRun() {
var i = 1
for benchName in precommitTests.keys.sorted() {
tests.append(Test(name: benchName, n: i, f: precommitTests[benchName]!))
i += 1
}
for benchName in otherTests.keys.sorted() {
tests.append(Test(name: benchName, n: i, f: otherTests[benchName]!))
i += 1
}
for i in 0..<tests.count {
if onlyPrecommit && precommitTests[tests[i].name] == nil {
tests[i].run = false
}
if !filters.isEmpty &&
!filters.contains(String(tests[i].index)) &&
!filters.contains(tests[i].name) {
tests[i].run = false
}
}
}
}
func internalMeanSD(_ inputs: [UInt64]) -> (UInt64, UInt64) {
// If we are empty, return 0, 0.
if inputs.isEmpty {
return (0, 0)
}
// If we have one element, return elt, 0.
if inputs.count == 1 {
return (inputs[0], 0)
}
// Ok, we have 2 elements.
var sum1: UInt64 = 0
var sum2: UInt64 = 0
for i in inputs {
sum1 += i
}
let mean: UInt64 = sum1 / UInt64(inputs.count)
for i in inputs {
sum2 = sum2 &+ UInt64((Int64(i) &- Int64(mean))&*(Int64(i) &- Int64(mean)))
}
return (mean, UInt64(sqrt(Double(sum2)/(Double(inputs.count) - 1))))
}
func internalMedian(_ inputs: [UInt64]) -> UInt64 {
return inputs.sorted()[inputs.count / 2]
}
#if SWIFT_RUNTIME_ENABLE_LEAK_CHECKER
@_silgen_name("swift_leaks_startTrackingObjects")
func startTrackingObjects(_: UnsafeMutablePointer<Void>) -> ()
@_silgen_name("swift_leaks_stopTrackingObjects")
func stopTrackingObjects(_: UnsafeMutablePointer<Void>) -> Int
#endif
class SampleRunner {
var info = mach_timebase_info_data_t(numer: 0, denom: 0)
init() {
mach_timebase_info(&info)
}
func run(_ name: String, fn: (Int) -> Void, num_iters: UInt) -> UInt64 {
// Start the timer.
#if SWIFT_RUNTIME_ENABLE_LEAK_CHECKER
var str = name
startTrackingObjects(UnsafeMutablePointer<Void>(str._core.startASCII))
#endif
let start_ticks = mach_absolute_time()
fn(Int(num_iters))
// Stop the timer.
let end_ticks = mach_absolute_time()
#if SWIFT_RUNTIME_ENABLE_LEAK_CHECKER
stopTrackingObjects(UnsafeMutablePointer<Void>(str._core.startASCII))
#endif
// Compute the spent time and the scaling factor.
let elapsed_ticks = end_ticks - start_ticks
return elapsed_ticks * UInt64(info.numer) / UInt64(info.denom)
}
}
/// Invoke the benchmark entry point and return the run time in milliseconds.
func runBench(_ name: String, _ fn: (Int) -> Void, _ c: TestConfig) -> BenchResults {
var samples = [UInt64](repeating: 0, count: c.numSamples)
if c.verbose {
print("Running \(name) for \(c.numSamples) samples.")
}
let sampler = SampleRunner()
for s in 0..<c.numSamples {
let time_per_sample: UInt64 = 1_000_000_000 * UInt64(c.iterationScale)
var scale : UInt
var elapsed_time : UInt64 = 0
if c.fixedNumIters == 0 {
elapsed_time = sampler.run(name, fn: fn, num_iters: 1)
scale = UInt(time_per_sample / elapsed_time)
} else {
// Compute the scaling factor if a fixed c.fixedNumIters is not specified.
scale = c.fixedNumIters
}
// Rerun the test with the computed scale factor.
if scale > 1 {
if c.verbose {
print(" Measuring with scale \(scale).")
}
elapsed_time = sampler.run(name, fn: fn, num_iters: scale)
} else {
scale = 1
}
// save result in microseconds or k-ticks
samples[s] = elapsed_time / UInt64(scale) / 1000
if c.verbose {
print(" Sample \(s),\(samples[s])")
}
}
let (mean, sd) = internalMeanSD(samples)
// Return our benchmark results.
return BenchResults(delim: c.delim, sampleCount: UInt64(samples.count),
min: samples.min()!, max: samples.max()!,
mean: mean, sd: sd, median: internalMedian(samples))
}
func printRunInfo(_ c: TestConfig) {
if c.verbose {
print("--- CONFIG ---")
print("NumSamples: \(c.numSamples)")
print("Verbose: \(c.verbose)")
print("IterScale: \(c.iterationScale)")
if c.fixedNumIters != 0 {
print("FixedIters: \(c.fixedNumIters)")
}
print("Tests Filter: \(c.filters)")
print("Tests to run: ", terminator: "")
for t in c.tests {
if t.run {
print("\(t.name), ", terminator: "")
}
}
print("")
print("")
print("--- DATA ---")
}
}
func runBenchmarks(_ c: TestConfig) {
let units = "us"
print("#\(c.delim)TEST\(c.delim)SAMPLES\(c.delim)MIN(\(units))\(c.delim)MAX(\(units))\(c.delim)MEAN(\(units))\(c.delim)SD(\(units))\(c.delim)MEDIAN(\(units))")
var SumBenchResults = BenchResults()
SumBenchResults.sampleCount = 0
for t in c.tests {
if !t.run {
continue
}
let BenchIndex = t.index
let BenchName = t.name
let BenchFunc = t.f
let results = runBench(BenchName, BenchFunc, c)
print("\(BenchIndex)\(c.delim)\(BenchName)\(c.delim)\(results.description)")
fflush(stdout)
SumBenchResults.min += results.min
SumBenchResults.max += results.max
SumBenchResults.mean += results.mean
SumBenchResults.sampleCount += 1
// Don't accumulate SD and Median, as simple sum isn't valid for them.
// TODO: Compute SD and Median for total results as well.
// SumBenchResults.sd += results.sd
// SumBenchResults.median += results.median
}
print("")
print("Totals\(c.delim)\(SumBenchResults.description)")
}
public func main() {
var config = TestConfig()
switch (config.processArguments()) {
case let .Fail(msg):
// We do this since we need an autoclosure...
fatalError("\(msg)")
case .ListTests:
config.findTestsToRun()
print("Enabled Tests:")
for t in config.tests {
print(" \(t.name)")
}
case .Run:
config.findTestsToRun()
printRunInfo(config)
runBenchmarks(config)
if let x = config.afterRunSleep {
sleep(UInt32(x))
}
}
}
|
apache-2.0
|
193cead6f331a2caf72c0c830db2fd55
| 27.841823 | 161 | 0.618795 | 3.777388 | false | true | false | false |
mozilla-mobile/firefox-ios
|
Client/Application/WebServer.swift
|
2
|
4108
|
// 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 GCDWebServers
import Shared
protocol WebServerProtocol {
var server: GCDWebServer { get }
@discardableResult func start() throws -> Bool
}
class WebServer: WebServerProtocol {
private let log = Logger.browserLogger
static let WebServerSharedInstance = WebServer()
class var sharedInstance: WebServer {
return WebServerSharedInstance
}
let server: GCDWebServer = GCDWebServer()
var base: String {
return "http://localhost:\(server.port)"
}
/// The private credentials for accessing resources on this Web server.
let credentials: URLCredential
/// A random, transient token used for authenticating requests.
/// Other apps are able to make requests to our local Web server,
/// so this prevents them from accessing any resources.
fileprivate let sessionToken = UUID().uuidString
init() {
credentials = URLCredential(user: sessionToken, password: "", persistence: .forSession)
}
@discardableResult func start() throws -> Bool {
if !server.isRunning {
try server.start(options: [
GCDWebServerOption_Port: AppInfo.webserverPort,
GCDWebServerOption_BindToLocalhost: true,
GCDWebServerOption_AutomaticallySuspendInBackground: false, // done by the app in AppDelegate
GCDWebServerOption_AuthenticationMethod: GCDWebServerAuthenticationMethod_Basic,
GCDWebServerOption_AuthenticationAccounts: [sessionToken: ""]
])
}
return server.isRunning
}
/// Convenience method to register a dynamic handler. Will be mounted at $base/$module/$resource
func registerHandlerForMethod(_ method: String, module: String, resource: String, handler: @escaping (_ request: GCDWebServerRequest?) -> GCDWebServerResponse?) {
// Prevent serving content if the requested host isn't a safelisted local host.
let wrappedHandler = {(request: GCDWebServerRequest?) -> GCDWebServerResponse? in
guard let request = request,
InternalURL.isValid(url: request.url)
else { return GCDWebServerResponse(statusCode: 403) }
return handler(request)
}
server.addHandler(forMethod: method, path: "/\(module)/\(resource)", request: GCDWebServerRequest.self, processBlock: wrappedHandler)
}
/// Convenience method to register a resource in the main bundle. Will be mounted at $base/$module/$resource
func registerMainBundleResource(_ resource: String, module: String) {
if let path = Bundle.main.path(forResource: resource, ofType: nil) {
server.addGETHandler(forPath: "/\(module)/\(resource)", filePath: path, isAttachment: false, cacheAge: UInt.max, allowRangeRequests: true)
}
}
/// Convenience method to register all resources in the main bundle of a specific type. Will be mounted at $base/$module/$resource
func registerMainBundleResourcesOfType(_ type: String, module: String) {
for path: String in Bundle.paths(forResourcesOfType: type, inDirectory: Bundle.main.bundlePath) {
if let resource = NSURL(string: path)?.lastPathComponent {
server.addGETHandler(forPath: "/\(module)/\(resource)", filePath: path as String, isAttachment: false, cacheAge: UInt.max, allowRangeRequests: true)
} else {
log.warning("Unable to locate resource at path: '\(path)'")
}
}
}
/// Return a full url, as a string, for a resource in a module. No check is done to find out if the resource actually exist.
func URLForResource(_ resource: String, module: String) -> String {
return "\(base)/\(module)/\(resource)"
}
func baseReaderModeURL() -> String {
return WebServer.sharedInstance.URLForResource("page", module: "reader-mode")
}
}
|
mpl-2.0
|
573bc6b5af68ba59e060faad584d5c10
| 43.172043 | 166 | 0.677945 | 5.022005 | false | false | false | false |
javierlopeza/VerboAppiOS
|
Verbo Tabs/HorarioWebViewController.swift
|
1
|
1482
|
//
// HorarioWebViewController.swift
// Verbo Tabs
//
// Created by Javier López Achondo on 04-01-16.
// Copyright © 2016 Javier López Achondo. All rights reserved.
//
import UIKit
class HorarioWebViewController: UIViewController {
@IBOutlet weak var HorarioWebView: UIWebView!
var url_string = String()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
// Colores y estilo
navigationController?.navigationBar.barTintColor = UIColor(red: 3/255.0, green: 120/255.0, blue: 63/255.0, alpha: 1.0)
navigationController?.navigationBar.tintColor = UIColor.whiteColor()
navigationController?.navigationBar.barStyle = .BlackTranslucent
// Mostrar horario
let url = NSURL(string: url_string)
let request = NSURLRequest(URL: url!)
HorarioWebView.loadRequest(request)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
|
cc0-1.0
|
c878cfb8c0c6aad653fb6f95bdb999b5
| 29.8125 | 126 | 0.672076 | 4.740385 | false | false | false | false |
akring/PathDynamicModal
|
PathDynamicModal-Demo/ImageModalView.swift
|
2
|
1552
|
//
// ImageModalView.swift
// PathDynamicModal-Demo
//
// Created by Ryo Aoyama on 2/12/15.
// Copyright (c) 2015 Ryo Aoyama. All rights reserved.
//
import UIKit
class ImageModalView: UIView {
var bottomButtonHandler: (() -> Void)?
var closeButtonHandler: (() -> Void)?
var image: UIImage? {
set {
self.imageView.image = newValue
}
get {
return self.imageView.image
}
}
@IBOutlet private var imageView: UIImageView!
@IBOutlet private var closeButton: UIButton!
@IBOutlet private var contentView: UIView!
override func awakeFromNib() {
super.awakeFromNib()
self.configure()
}
private func configure() {
self.contentView.layer.cornerRadius = 5.0
self.closeButton.layer.cornerRadius = CGRectGetHeight(self.closeButton.bounds) / 2.0
self.closeButton.layer.shadowColor = UIColor.blackColor().CGColor
self.closeButton.layer.shadowOffset = CGSizeZero
self.closeButton.layer.shadowOpacity = 0.3
self.closeButton.layer.shadowRadius = 2.0
}
class func instantiateFromNib() -> ImageModalView {
let view = UINib(nibName: "ImageModalView", bundle: nil).instantiateWithOwner(nil, options: nil).first as! ImageModalView
return view
}
@IBAction func handleCloseButton(sender: UIButton) {
self.closeButtonHandler?()
}
@IBAction func handleBottomButton(sender: UIButton) {
self.bottomButtonHandler?()
}
}
|
mit
|
10a52b70d07b4f2fbfaf7bdd32a3e7f6
| 27.759259 | 129 | 0.641108 | 4.646707 | false | false | false | false |
mflint/ios-tldr-viewer
|
tldr-viewer/Preferences.swift
|
1
|
2465
|
//
// Preferences.swift
// tldr-viewer
//
// Created by Matthew Flint on 22/01/2017.
// Copyright © 2017 Green Light. All rights reserved.
//
import Foundation
class Preferences {
static let sharedInstance = Preferences()
private let userDefaults = UserDefaults.standard
private init() {
let latest = userDefaults.stringArray(forKey: Constant.PreferenceKey.latest)
if latest == nil {
let empty: [String] = []
userDefaults.set(empty, forKey: Constant.PreferenceKey.latest)
}
}
func latest() -> [String] {
return userDefaults.stringArray(forKey: Constant.PreferenceKey.latest)!
}
func addLatest(_ newEntry: String) {
var latest = userDefaults.stringArray(forKey: Constant.PreferenceKey.latest)!
let indexOfExistingEntry = latest.firstIndex(of: newEntry)
if let indexOfExistingEntry = indexOfExistingEntry {
latest.remove(at: indexOfExistingEntry)
}
latest.append(newEntry)
if latest.count > Constant.Shortcut.count {
latest.removeFirst()
}
userDefaults.set(latest, forKey: Constant.PreferenceKey.latest)
}
func currentDataSource() -> DataSourceType {
guard let rawValue = userDefaults.string(forKey: Constant.PreferenceKey.selectedDataSource) else { return .all }
guard let result = DataSourceType(rawValue: rawValue) else { return .all }
return result
}
func setCurrentDataSource(_ dataSource: DataSourceType) {
userDefaults.set(dataSource.rawValue, forKey: Constant.PreferenceKey.selectedDataSource)
userDefaults.synchronize()
}
func favouriteCommandNames() -> [String] {
switch userDefaults.value(forKey: Constant.PreferenceKey.favouriteCommandNames) {
case let stringArray as [String]:
return stringArray
case let string as String:
// when XCUITests run, for creating screenshots, favourites are passed into
// the argument domain as a comma separated string
return string.components(separatedBy: ",")
default:
return []
}
}
func setFavouriteCommandNames(_ favouriteCommandNames: [String]) {
userDefaults.set(favouriteCommandNames, forKey:Constant.PreferenceKey.favouriteCommandNames)
userDefaults.synchronize()
}
}
|
mit
|
7e089da2a491ea6f6d6278feed12a4b3
| 32.753425 | 120 | 0.650162 | 5.122661 | false | true | false | false |
finn-no/Finjinon
|
Demo/ViewController.swift
|
1
|
4002
|
//
// Copyright (c) 2017 FINN.no AS. All rights reserved.
//
import UIKit
import Finjinon
class ViewController: UITableViewController {
var assets: [Asset] = []
let captureController = PhotoCaptureViewController()
override func viewDidLoad() {
super.viewDidLoad()
navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(addPhotosTapped(_:)))
tableView.register(UITableViewCell.self, forCellReuseIdentifier: "ItemCell")
captureController.delegate = self
for i in 0 ..< 6 {
captureController.createAssetFromImage(UIImage(named: "hoff.jpeg")!) { asset in
self.assets.append(asset)
self.tableView.insertRows(at: [IndexPath(row: i, section: 0)], with: .automatic)
}
}
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
tableView.reloadData()
}
@objc func addPhotosTapped(_: AnyObject) {
present(captureController, animated: true, completion: nil)
}
override func tableView(_: UITableView, numberOfRowsInSection _: Int) -> Int {
return assets.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "ItemCell", for: indexPath)
let asset = assets[indexPath.row]
cell.textLabel?.text = asset.UUID
cell.imageView?.image = nil
asset.imageWithWidth(64, result: { image in
cell.imageView?.image = image
cell.setNeedsLayout()
})
return cell
}
}
extension ViewController: PhotoCaptureViewControllerDelegate {
func photoCaptureViewController(_ controller: PhotoCaptureViewController, cellForItemAtIndexPath indexPath: IndexPath) -> PhotoCollectionViewCell? {
return controller.dequeuedReusableCellForClass(PhotoCollectionViewCell.self, indexPath: indexPath) { cell in
let asset = self.assets[indexPath.item]
// Set a thumbnail form the source image, or add your own network fetch code etc
if let _ = asset.imageURL {
} else {
asset.imageWithWidth(cell.imageView.bounds.width) { image in
cell.imageView.image = image
}
}
}
}
func photoCaptureViewControllerDidFinish(_: PhotoCaptureViewController) {
}
func photoCaptureViewController(_: PhotoCaptureViewController, didSelectAssetAtIndexPath indexPath: IndexPath) {
NSLog("tapped in \(indexPath.row)")
}
func photoCaptureViewController(_: PhotoCaptureViewController, didFailWithError error: NSError) {
NSLog("failure: \(error)")
}
func photoCaptureViewController(_: PhotoCaptureViewController, didMoveItemFromIndexPath fromIndexPath: IndexPath, toIndexPath: IndexPath) {
NSLog("moved from #\(fromIndexPath.item) to #\(toIndexPath.item)")
tableView.moveRow(at: fromIndexPath, to: toIndexPath)
}
func photoCaptureViewControllerNumberOfAssets(_: PhotoCaptureViewController) -> Int {
return assets.count
}
func photoCaptureViewController(_: PhotoCaptureViewController, assetForIndexPath indexPath: IndexPath) -> Asset {
return assets[indexPath.item]
}
func photoCaptureViewController(_: PhotoCaptureViewController, didAddAsset asset: Asset) {
assets.append(asset)
tableView.insertRows(at: [IndexPath(row: 0, section: 0)], with: .automatic)
}
func photoCaptureViewController(_: PhotoCaptureViewController, deleteAssetAtIndexPath indexPath: IndexPath) {
assets.remove(at: indexPath.item)
tableView.deleteRows(at: [IndexPath(row: 0, section: 0)], with: .automatic)
}
func photoCaptureViewController(_: PhotoCaptureViewController, canMoveItemAtIndexPath _: IndexPath) -> Bool {
return true
}
}
|
mit
|
972c7b26a96b7eaf2f163cd20f02584e
| 36.401869 | 152 | 0.68066 | 5.224543 | false | false | false | false |
RxSugar/RxSugar
|
RxSugar/Animator.swift
|
1
|
1977
|
import UIKit
import RxSwift
/// Respresents an animator.
public protocol Animator {
/// Called when observing events.
///
/// - parameter animations: A closure called when performing the animation
func animate(_ animations: @escaping ()->())
}
/// Default animator.
public struct DefaultAnimator: Animator {
public init() {}
/// Default implementation of an animated observer
///
/// - parameter animations: A closure called when performing the default animation
public func animate(_ animations: @escaping ()->()) {
UIView.animate(withDuration: 0.25,
delay: 0,
options: UIView.AnimationOptions.beginFromCurrentState,
animations: animations,
completion: nil)
}
}
/// Animates changes on an observer with an optional Animator type
///
/// - parameter observer: observer whose changes are animated
/// - parameter animator: an optional custom Animator to perform the animations
///
/// - returns: an animated observer
public func animated<T>(_ observer: AnyObserver<T>, animator: Animator = DefaultAnimator()) -> AnyObserver<T> {
let subject = PublishSubject<T>()
_ = subject.subscribe(onError: observer.onError, onCompleted: observer.onCompleted)
_ = subject.subscribe(onNext: { value in
animator.animate { observer.onNext(value) }
})
return subject.asObserver()
}
/// Animates changes within a closure with an optional Animator type
///
/// - parameter animator: an optional custom Animator to perform the animations
/// - parameter closure: a closure that is called when the animations are performed
///
/// - returns: a closure that animates the closure argument
public func animated<T>(_ animator: Animator = DefaultAnimator(), closure: @escaping (T)->()) -> (T) -> () {
return { value in
animator.animate { closure(value) }
}
}
|
mit
|
b3f205dfd2527914bb77dc7c36681679
| 34.945455 | 111 | 0.649469 | 5.056266 | false | false | false | false |
ArnavChawla/InteliChat
|
Carthage/Checkouts/swift-sdk/Source/DiscoveryV1/Models/Nested.swift
|
1
|
1429
|
/**
* 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
/** Nested. */
public struct Nested: Decodable {
/// The type of aggregation command used. For example: term, filter, max, min, etc.
public var type: String?
public var results: [AggregationResult]?
/// Number of matching results.
public var matchingResults: Int?
/// Aggregations returned by the Discovery service.
public var aggregations: [QueryAggregation]?
/// The area of the results the aggregation was restricted to.
public var path: String?
// Map each property name to the key that shall be used for encoding/decoding.
private enum CodingKeys: String, CodingKey {
case type = "type"
case results = "results"
case matchingResults = "matching_results"
case aggregations = "aggregations"
case path = "path"
}
}
|
mit
|
9684598504e3fc6d5dfe0bf336464120
| 30.755556 | 87 | 0.69979 | 4.479624 | false | false | false | false |
adrfer/swift
|
test/expr/cast/array_downcast.swift
|
12
|
1446
|
// RUN: %target-parse-verify-swift
// XFAIL: linux
class V {}
class U : V {}
class T : U {}
var v = V()
var u = U()
var t = T()
var va = [v]
var ua = [u]
var ta = [t]
va = ta
var va2: ([V])? = va as [V]
var v2: V = va2![0]
var ua2: ([U])? = va as? [U]
var u2: U = ua2![0]
var ta2: ([T])? = va as? [T]
var t2: T = ta2![0]
// Check downcasts that require bridging.
class A {
var x = 0
}
struct B : _ObjectiveCBridgeable {
static func _isBridgedToObjectiveC() -> Bool {
return true
}
static func _getObjectiveCType() -> Any.Type {
return A.self
}
func _bridgeToObjectiveC() -> A {
return A()
}
static func _forceBridgeFromObjectiveC(
x: A,
inout result: B?
) {
}
static func _conditionallyBridgeFromObjectiveC(
x: A,
inout result: B?
) -> Bool {
return true
}
}
func testBridgedDowncastAnyObject(arr: [AnyObject], arrOpt: [AnyObject]?,
arrIUO: [AnyObject]!) {
var b = B()
if let bArr = arr as? [B] {
b = bArr[0]
}
if let bArr = arrOpt as? [B] {
b = bArr[0]
}
if let bArr = arrIUO as? [B] {
b = bArr[0]
}
_ = b
}
func testBridgedIsAnyObject(arr: [AnyObject], arrOpt: [AnyObject]?,
arrIUO: [AnyObject]!) -> Bool {
let b = B()
if arr is [B] { return arr is [B] }
if arrOpt is [B] { return arrOpt is [B] }
if arrIUO is [B] { return arrIUO is [B] }
_ = b
return false
}
|
apache-2.0
|
13cdbcb753b1169416d2f4aef44d4456
| 15.813953 | 74 | 0.538728 | 2.933063 | false | false | false | false |
vitormesquita/Malert
|
Example/Malert/util/Colors.swift
|
1
|
1071
|
//
// Colors.swift
// Malert_Example
//
// Created by Vitor Mesquita on 15/07/2018.
// Copyright © 2018 CocoaPods. All rights reserved.
//
import UIKit
extension UIColor {
static let primary = UIColor(red: 0.16, green: 0.71, blue: 0.96, alpha: 1.0)
static let imageExample = UIColor(red:0.46, green:0.46, blue:0.46, alpha:1.0)
static let formExample = UIColor(red:0.96, green:0.32, blue:0.12, alpha:1.0)
static let customizableExample = UIColor(red:0.75, green:0.79, blue:0.20, alpha:1.0)
static let expandableExample = UIColor(red:0.49, green:0.30, blue:1.00, alpha:1.0)
}
// MARK: - UIImage
extension UIImage {
static func fromColor(color: UIColor) -> UIImage {
let rect = CGRect(x: 0, y: 0, width: 1, height: 1)
UIGraphicsBeginImageContext(rect.size)
let context = UIGraphicsGetCurrentContext()!
context.setFillColor(color.cgColor)
context.fill(rect)
let img = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
return img
}
}
|
mit
|
ab657e0b9309d7efb1ec89c4f8b42d5f
| 30.470588 | 88 | 0.656075 | 3.519737 | false | false | false | false |
esttorhe/MammutAPI
|
Sources/MammutAPI/Models/Application.swift
|
1
|
452
|
//
// Created by Esteban Torres on 09/04/2017.
// Copyright (c) 2017 Esteban Torres. All rights reserved.
//
import Foundation
public struct Application {
let name: String
let website: String?
}
// MARK: - Equatable
extension Application: Equatable {
public static func ==(lhs: Application, rhs: Application) -> Bool {
return (
lhs.name == rhs.name &&
lhs.website == rhs.website
)
}
}
|
mit
|
7af343b5b2e85f1c1e3fa8492cc64d6d
| 19.590909 | 71 | 0.606195 | 4.072072 | false | false | false | false |
FindGF/_BiliBili
|
WTBilibili/Home-首页/Live-直播/Controller/WTLiveDetailVerticalPlayerViewController.swift
|
1
|
5822
|
//
// WTLiveDetailVerticalPlayerViewController.swift
// WTBilibili
//
// Created by 无头骑士 GJ on 16/5/29.
// Copyright © 2016年 无头骑士 GJ. All rights reserved.
//
import UIKit
class WTLiveDetailVerticalPlayerViewController: UIViewController {
// MARK: - 属性
/// 播放器
var player: IJKMediaPlayback?
var timer: NSTimer?
// MARK: - 控件
/// 工具栏占位的View
@IBOutlet weak var touchView: UIView!
/// liveLogoImageView
@IBOutlet weak var liveLogoImageV: UIImageView!
/// 在加载中展示的View
@IBOutlet weak var playBeforeView: UIView!
/// 播放的View
@IBOutlet weak var contentView: UIView!
/// 竖屏播放器工具栏
var playerControlPanelV2 = WTPlayerControlPanelV2.playerControlPanelV2()
var url: NSURL?{
didSet{
guard let urlTemp = url else
{
return
}
player = IJKFFMoviePlayerController(contentURL: urlTemp, withOptions: nil)
let playerView = player?.view
playerView!.frame = view.bounds
contentView.addSubview(playerView!)
player?.scalingMode = IJKMPMovieScalingMode.AspectFit
if self.player?.isPlaying() == false
{
self.player?.prepareToPlay()
}
}
}
// MARK: 系统回调函数
override func viewDidLoad()
{
super.viewDidLoad()
installMovieNotificationObservers()
setupUI()
// 2、开启定时器
startTimer()
}
override func viewDidLayoutSubviews()
{
super.viewDidLayoutSubviews()
playerControlPanelV2.frame = self.view.bounds
}
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
if playerControlPanelV2.hidden == true
{
// 1、开启定时,过3秒隐藏工具栏
startTimer()
}
else
{
// 1、停止定时器
stopTimer()
}
}
deinit{
player?.shutdown()
stopTimer()
}
}
// MARK: - 自定义函数
extension WTLiveDetailVerticalPlayerViewController
{
private func setupUI()
{
// 1、添加子控件
touchView.addSubview(playerControlPanelV2)
}
private func installMovieNotificationObservers()
{
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(loadStateDidChange(_:)), name: IJKMPMoviePlayerLoadStateDidChangeNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(moviePlayBackFinish(_:)), name: IJKMPMoviePlayerPlaybackDidFinishNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(mediaIsPreparedToPlayDidChange(_:)), name: IJKMPMediaPlaybackIsPreparedToPlayDidChangeNotification, object: nil)
}
// MARK: 重启定时器
func restartTimer()
{
stopTimer()
startTimer()
}
// MARK: 开启定时器
private func startTimer()
{
// 1、开启定时,过3秒隐藏工具栏
timer = NSTimer(timeInterval: 3, target: self, selector: #selector(hiddenPlayerControlPanelV2), userInfo: nil, repeats: false)
NSRunLoop.currentRunLoop().addTimer(timer!, forMode: NSRunLoopCommonModes)
// 2、显示工具栏
if playerControlPanelV2.hidden == true
{
UIView.animateWithDuration(0.5) {
self.playerControlPanelV2.hidden = false
}
}
}
// MARK: 关闭定时器
private func stopTimer()
{
timer!.invalidate()
timer = nil
// 2、隐藏工具栏
hiddenPlayerControlPanelV2()
}
}
// MARK: - 事件
extension WTLiveDetailVerticalPlayerViewController
{
@objc private func loadStateDidChange(noti: NSNotification)
{
let loadState = player?.loadState
if loadState!.contains(IJKMPMovieLoadState.PlaythroughOK)
{
WTLog("LoadStateDidChange: IJKMovieLoadStatePlayThroughOK: \(loadState)")
playBeforeView.hidden = true
}
else if loadState!.contains(IJKMPMovieLoadState.Stalled)
{
WTLog("LoadStateDidChange: IJKMPMovieLoadState: \(loadState)")
}
else
{
WTLog("LoadStateDidChange: ??? :\(loadState)")
}
}
@objc private func moviePlayBackFinish(noti: NSNotification)
{
let reason = noti.userInfo![IJKMPMoviePlayerPlaybackDidFinishReasonUserInfoKey] as! IJKMPMovieFinishReason
switch reason {
case IJKMPMovieFinishReason.PlaybackEnded:
WTLog("playbackStateDidChange: IJKMPMovieFinishReasonPlaybackEnded: \(reason)\n")
case IJKMPMovieFinishReason.UserExited:
WTLog("playbackStateDidChange: IJKMPMovieFinishReasonUserExited: \(reason)\n");
case IJKMPMovieFinishReason.PlaybackError:
WTLog("playbackStateDidChange: IJKMPMovieFinishReasonPlaybackError: \(reason)\n");
}
}
@objc private func mediaIsPreparedToPlayDidChange(noti: NSNotification)
{
WTLog("mediaIsPrepareToPlayDidChange\n");
}
// MARK: 隐藏palyerControlPanelV2的View
func hiddenPlayerControlPanelV2()
{
UIView.animateWithDuration(0.5) {
self.playerControlPanelV2.hidden = true
}
}
}
|
apache-2.0
|
bddcb4eed856bae2285b4ec3b921e588
| 25.383886 | 195 | 0.591521 | 4.966102 | false | false | false | false |
doushiDev/ds_ios
|
TouTiao/MyMainTableViewController.swift
|
1
|
19021
|
//
// MyMainTableViewController.swift
// ds-ios My页面
//
// Created by 宋立君 on 15/10/30.
// Copyright © 2015年 Songlijun. All rights reserved.
//
import UIKit
import SnapKit
import HandyJSON
class MyMainTableViewController: UITableViewController {
@IBOutlet var myImage: UIImageView!
@IBOutlet weak var myBackImageView: UIImageView!
@IBOutlet weak var headerView: UIView!
let userCircle = UIImageView(frame: CGRect(x: 0,y: 0,width: 80,height: 80))
let loginButton = UIButton(frame: CGRect(x: 0, y: 200, width: 80, height: 20))
@IBOutlet weak var loginStatusLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
self.navigationController?.navigationBar.tintColor = UIColor(rgba:"#f0a22a")
// self.tableView.tableHeaderView = myImage
loginButton.isEnabled = true
}
override func loadView() {
super.loadView()
self.headerView.frame = CGRect(x: 0, y: 64, width: UIScreen.main.bounds.width, height: 220)
userCircle.alpha = 1
userCircle.center = myBackImageView.center
userCircle.layer.masksToBounds = true
userCircle.layer.cornerRadius = 35
userCircle.isUserInteractionEnabled = true
let userCircleTap = UITapGestureRecognizer()
userCircleTap.addTarget(self, action: #selector(MyMainTableViewController.userCircleAction))
userCircle.addGestureRecognizer(userCircleTap)
myBackImageView.addSubview(userCircle)
loginButton.titleLabel?.font = UIFont(name: "Avenir Next Bold", size: 16)
myBackImageView.addSubview(loginButton)
loginButton.snp.makeConstraints { (make) -> Void in
make.top.equalTo(userCircle.snp.bottom).offset(10)
make.width.equalTo(150)
make.height.equalTo(20)
make.centerX.equalTo(myBackImageView)
}
userCircle.snp.makeConstraints { (make) -> Void in
make.size.equalTo(70)
make.center.equalTo(myBackImageView)
}
// 设置用户头像
userCircle.image = UIImage(named: "touxiang")
// 设置login
loginButton.setTitle("立即登录", for: UIControlState())
loginButton.addTarget(self, action: #selector(MyMainTableViewController.toLoginView(_:)), for: .touchUpInside)
}
func userCircleAction() {
if loginButton.isEnabled {
showLoginView()
}
}
func showLoginView() {
print("d 点击登录")
// let loginViewController = YHConfig.mainStoryboard.instantiateViewController(withIdentifier: "LoginViewController") as! LoginViewController
//
// self.present(loginViewController, animated: true, completion: nil)
}
/**
跳转登录页面
*/
func toLoginView(_ sender: UIButton!){
print("点击了登录")
// let loginViewController = YHConfig.mainStoryboard.instantiateViewController(withIdentifier: "LoginViewController") as! LoginViewController
//
// self.present(loginViewController, animated: true, completion: nil)
//
alertLogin()
}
func alertLogin() {
// Create custom Appearance Configuration
let appearance = SCLAlertView.SCLAppearance(
kTitleFont: UIFont(name: "HelveticaNeue", size: 20)!,
kTextFont: UIFont(name: "HelveticaNeue", size: 14)!,
kButtonFont: UIFont(name: "HelveticaNeue-Bold", size: 14)!,
showCloseButton: false
)
// Initialize SCLAlertView using custom Appearance
let alert = SCLAlertView(appearance: appearance)
// Creat the subview
let subview = UIView(frame: CGRect(x: 0,y: 0,width: 216,height: 70))
let x = (subview.frame.width - 180) / 2
// Add textfield 1
let textfield1 = UITextField(frame: CGRect(x: x,y: 10,width: 180,height: 25))
// textfield1.layer.borderColor = UIColor.green.cgColor
textfield1.layer.borderWidth = 1.5
textfield1.layer.cornerRadius = 5
textfield1.placeholder = "手机号"
textfield1.keyboardType = .phonePad
textfield1.textAlignment = NSTextAlignment.center
subview.addSubview(textfield1)
// Add textfield 2
let textfield2 = UITextField(frame: CGRect(x: x,y: textfield1.frame.maxY + 10,width: 180,height: 25))
textfield2.isSecureTextEntry = true
// textfield2.layer.borderColor = UIColor.blue.cgColor
textfield2.layer.borderWidth = 1.5
textfield2.layer.cornerRadius = 5
textfield1.layer.borderColor = UIColor.blue.cgColor
textfield2.placeholder = "密码"
textfield2.isSecureTextEntry = true
textfield2.textAlignment = NSTextAlignment.center
subview.addSubview(textfield2)
// Add the subview to the alert's UI property
alert.customSubview = subview
_ = alert.addButton("登录/注册") {
print("Logged in")
// textfield1.text
if !self.validateMobile(phone: textfield1.text!) {
print("手机号不对")
}else{
var user: User = User()
user.nickName = textfield1.text!
TouTiaoConfig.userDefaults.set(JSONSerializer.serialize(model: user).toSimpleDictionary(), forKey: "user")
DSDataCenter.sharedInstance.user = user
self.setHeadImage()
}
}
_ = alert.addButton("关闭",backgroundColor: UIColor.gray) {
print("关闭")
}
_ = alert.showInfo("登录/注册", subTitle: "", closeButtonTitle: "10")
}
func validateMobile(phone: String) -> Bool {
let phoneRegex: String = "^((13[0-9])|(15[^4,\\D])|(16[^4,\\D])|(18[0,0-9])|(17[0,0-9]))\\d{8}$"
let phoneTest = NSPredicate(format: "SELF MATCHES %@", phoneRegex)
return phoneTest.evaluate(with: phone)
}
func setHeadImage(){
if let userDic:Dictionary = UserDefaults.standard.dictionary(forKey: "user") {
// let url = URL(string: userDic["headImage"] as! String)
// self.userCircle.kf.setImage(with: url, placeholder: Image(named:"picture-default"), options: [.transition(ImageTransition.fade(1))], progressBlock: nil, completionHandler: nil)
//
self.loginButton.setTitle(userDic["nickName"] as? String, for: UIControlState())
self.loginButton.isEnabled = false
//禁止点击
loginButton.isEnabled = false
loginStatusLabel.text = "退出当前用户"
loginStatusLabel.textColor = UIColor.red
}else{
loginButton.setTitle("立即登录", for: UIControlState())
loginButton.isEnabled = true
userCircle.image = UIImage(named: "touxiang")
loginStatusLabel.text = "立即登录"
loginStatusLabel.textColor = UIColor(rgba: "#f5436d")
}
}
override func viewWillAppear(_ animated: Bool) {
// 刷新用户信息
setHeadImage()
super.viewWillAppear(animated)
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if (indexPath as NSIndexPath).section == 0 && (indexPath as NSIndexPath).row == 0{
}
if (indexPath as NSIndexPath).section == 0 && (indexPath as NSIndexPath).row == 1{
print("意见反馈")
let evaluateString = "http://itunes.apple.com/WebObjects/MZStore.woa/wa/viewContentsUserReviews?id=1044917946&pageNumber=0&sortOrdering=2&type=Purple+Software&mt=8"
UIApplication.shared.openURL(URL(string: evaluateString)!)
}
if (indexPath as NSIndexPath).section == 0 && (indexPath as NSIndexPath).row == 0{
print("给个笑脸")
let evaluateString = "http://itunes.apple.com/WebObjects/MZStore.woa/wa/viewContentsUserReviews?id=1044917946&pageNumber=0&sortOrdering=2&type=Purple+Software&mt=8"
UIApplication.shared.openURL(URL(string: evaluateString)!)
}
if (indexPath as NSIndexPath).section == 0 && (indexPath as NSIndexPath).row == 2 {
print("免责声明")
UIApplication.shared.openURL(URL(string: "https://api.toutiao.itjh.net/mzsm.html"
)!) }
if (indexPath as NSIndexPath).section == 1 && (indexPath as NSIndexPath).row == 1 {
print("朋友推荐")
UMSocialUIManager.showShareMenuViewInWindow(platformSelectionBlock: { (platformType, userInfo) in
let messageObject:UMSocialMessageObject = UMSocialMessageObject.init()
messageObject.text = "推荐一个专注搞笑视频的应用"//分享的文本
//2.分享分享网页
let shareObject:UMShareWebpageObject = UMShareWebpageObject.init()
shareObject.title = "推荐一个专注搞笑视频的应用"
shareObject.descr = "逗音视频 - 好玩人的视频都在这"
shareObject.thumbImage = UIImage.init(named: "Icon-60")//缩略图
shareObject.webpageUrl = "https://api.toutiao.itjh.net/share.html?title=%E5%8D%95%E8%BA%AB%E7%8B%97%E5%9C%A8%E5%AF%82%E5%AF%9E%E7%9A%84%E5%A4%9C%E9%87%8C%E9%83%BD%E4%BC%9A%E5%B9%B2%E5%98%9B&pic=http://img.mms.v1.cn/static/mms/images/2017-02-14/201702141510141635.jpg&videoUrl=http://f04.v1.cn/transcode/14478674MOBILET2.mp4&type=1"
if platformType.rawValue == 0 {
messageObject.text = "推荐一个专注搞笑视频的应用 -- 逗音视频 - 好玩人的视频都在这,试试看吧!下载地址: http://t.cn/Roaq9ZZ"
//创建图片内容对象
let shareImage = UMShareImageObject()
shareImage.thumbImage = UIImage.init(named: "Icon-60")//缩略图
shareImage.shareImage = "https://ws1.sinaimg.cn/large/006tNc79ly1fgwkuqrpzkj3050050jrf.jpg"
messageObject.shareObject = shareImage
}else{
messageObject.shareObject = shareObject;
}
UMSocialManager.default().share(to: platformType, messageObject: messageObject, currentViewController: self, completion: { (shareResponse, error) in
if error != nil {
print("Share Fail with error :%@", error!)
}else{
print("Share succeed")
}
})
})
}
if (indexPath as NSIndexPath).section == 2 && (indexPath as NSIndexPath).row == 0 {
if let userCircle:Dictionary = UserDefaults.standard.dictionary(forKey: "user"){
print("登出")
//确定按钮
let alertController = UIAlertController(title: "确定要退出吗?", message: "", preferredStyle: .alert)
let cancelAction = UIAlertAction(title: "取消", style: .cancel) { (action) in
}
alertController.addAction(cancelAction)
let OKAction = UIAlertAction(title: "确定", style: .default) { (action) in
UserDefaults.standard.removeObject(forKey: "user")
DSDataCenter.sharedInstance.user = User()
self.setHeadImage()
}
alertController.addAction(OKAction)
self.present(alertController, animated: true) {
}
}else{
print("点击了登录")
// let loginViewController = YHConfig.mainStoryboard.instantiateViewController(withIdentifier: "LoginViewController") as! LoginViewController
//
// self.present(loginViewController, animated: true, completion: nil)
alertLogin()
}
}
}
//发送邮件功能
func sendEmailAction(){
// let mailComposeViewController = configuredMailComposeViewController()
// if mailComposeViewController.canSendMail() {
// self.present(mailComposeViewController, animated: true, completion: nil)
// }
}
// func configuredMailComposeViewController() -> MFMailComposeViewController {
// let mailComposerVC = mailComposeController()
// mailComposerVC.mailComposeDelegate = self // Extremely important to set the --mailComposeDelegate-- property, NOT the --delegate-- property
// //设置收件人
// mailComposerVC.setToRecipients(["[email protected]"])
// //设置主题
// mailComposerVC.setSubject("搞笑头条意见反馈")
// //邮件内容
// let info:Dictionary = Bundle.main.infoDictionary!
// let appName = info["CFBundleName"] as! String
// let appVersion = info["CFBundleShortVersionString"] as! String
// mailComposerVC.setMessageBody("</br></br></br></br></br>基本信息:</br></br>\(appName) \(appVersion)</br> \(UIDevice.current.name)</br>iOS \(UIDevice.current.systemVersion)", isHTML: true)
// return mailComposerVC
// }
// MARK: MFMailComposeViewControllerDelegate Method
func sendEmail() {
// if mailComposeController.canSendMail() {
// let mailComposerVC = mailComposeController()
//
// mailComposerVC.setToRecipients(["[email protected]"])
// //设置主题
// mailComposerVC.setSubject("搞笑头条意见反馈")
// //邮件内容
// let info:Dictionary = Bundle.main.infoDictionary!
// let appName = info["CFBundleName"] as! String
// let appVersion = info["CFBundleShortVersionString"] as! String
// mailComposerVC.setMessageBody("</br></br></br></br></br>基本信息:</br></br>\(appName) \(appVersion)</br> \(UIDevice.current.name)</br>iOS \(UIDevice.current.systemVersion)", isHTML: true)
//
//// mail.mailComposeDelegate = self
//// mail.setToRecipients(["[email protected]"])
//// mail.setMessageBody("<p>You're so awesome!</p>", isHTML: true)
////
// present(mailComposerVC, animated: true)
// } else {
// // show failure alert
// }
}
// func mailComposeController(_ controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?) {
// controller.dismiss(animated: true)
// }
// MARK: - Table view data source
// override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// // #warning Incomplete implementation, return the number of sections
// return 2
// }
//
// override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// // #warning Incomplete implementation, return the number of rows
//
// return 0
// }
/*
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("reuseIdentifier", forIndexPath: indexPath)
// Configure the cell...
return cell
}
*/
/*
// Override to support conditional editing of the table view.
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
*/
/*
// Override to support editing the table view.
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
// Delete the row from the data source
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
} else if editingStyle == .Insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// Override to support rearranging the table view.
override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the item to be re-orderable.
return true
}
*/
/*
// MARK: - Navigation
*/
// In a storyboard-based application, you will often want to do a little preparation before navigation
}
extension MyMainTableViewController {
override func scrollViewDidScroll(_ scrollView: UIScrollView) {
let Offset_y = scrollView.contentOffset.y
// 下拉 纵向偏移量变小 变成负的
if ( Offset_y < 0) {
// 拉伸后图片的高度
let totalOffset = 200 - Offset_y;
// 图片放大比例
let scale = totalOffset / 200;
let width = UIScreen.main.bounds.width
// 拉伸后图片位置
myBackImageView!.frame = CGRect(x: -(width * scale - width) / 2, y: Offset_y, width: width * scale, height: totalOffset);
}
}
}
|
mit
|
5706b9f040be535326fb7757d6864e88
| 36.498982 | 347 | 0.575494 | 4.826212 | false | false | false | false |
3lvis/NetworkActivityIndicator
|
DemoUITests/DemoUITests.swift
|
1
|
2888
|
//
// DemoUITests.swift
// DemoUITests
//
// Created by Arda Oğul Üçpınar on 7.01.2018.
//
import XCTest
class DemoUITests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
// In UI tests it is usually best to stop immediately when a failure occurs.
continueAfterFailure = false
// UI tests must launch the application that they test. Doing this in setup will make sure it happens for each test method.
XCUIApplication().launch()
for _ in 0..<NetworkActivityIndicator.sharedIndicator.activitiesCount {
NetworkActivityIndicator.sharedIndicator.visible = false
}
// In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testVisible() {
NetworkActivityIndicator.sharedIndicator.visible = true
XCTAssertTrue(UIApplication.shared.isNetworkActivityIndicatorVisible)
}
func testHidden() {
NetworkActivityIndicator.sharedIndicator.visible = false
XCTAssertFalse(UIApplication.shared.isNetworkActivityIndicatorVisible)
}
func testMultipleVisible() {
NetworkActivityIndicator.sharedIndicator.visible = true
NetworkActivityIndicator.sharedIndicator.visible = true
NetworkActivityIndicator.sharedIndicator.visible = true
XCTAssertTrue(UIApplication.shared.isNetworkActivityIndicatorVisible)
}
func testMultipleHidden() {
NetworkActivityIndicator.sharedIndicator.visible = false
NetworkActivityIndicator.sharedIndicator.visible = false
NetworkActivityIndicator.sharedIndicator.visible = false
XCTAssertFalse(UIApplication.shared.isNetworkActivityIndicatorVisible)
}
func testBalance() {
NetworkActivityIndicator.sharedIndicator.visible = true
NetworkActivityIndicator.sharedIndicator.visible = true
NetworkActivityIndicator.sharedIndicator.visible = true
XCTAssertTrue(UIApplication.shared.isNetworkActivityIndicatorVisible)
NetworkActivityIndicator.sharedIndicator.visible = false
XCTAssertTrue(UIApplication.shared.isNetworkActivityIndicatorVisible)
NetworkActivityIndicator.sharedIndicator.visible = false
NetworkActivityIndicator.sharedIndicator.visible = false
XCTAssertFalse(UIApplication.shared.isNetworkActivityIndicatorVisible)
}
}
|
mit
|
e7976eaca8039d227fc6c2711c592fa7
| 35.025 | 182 | 0.700555 | 5.979253 | false | true | false | false |
huangboju/Moots
|
Examples/SwiftUI/Combine/CombineSwiftPlayground-master/Combine.playground/Pages/Simple Operators.xcplaygroundpage/Contents.swift
|
1
|
1342
|
//: [Previous](@previous)
import Foundation
import Combine
/*:
# Simple operators
- Operators are functions defined on publisher instances...
- ... each operator returns a new publisher ...
- ... operators can be chained to add processing steps
*/
/*:
## Example: `map`
- works like Swift's `map`
- ... operates on values over time
*/
let publisher1 = PassthroughSubject<Int, Never>()
let publisher2 = publisher1.map { value in
value + 100
}
let subscription1 = publisher1
.sink { value in
print("Subscription1 received integer: \(value)")
}
let subscription2 = publisher2
.sink { value in
print("Subscription2 received integer: \(value)")
}
print("* Demonstrating map operator")
print("Publisher1 emits 28")
publisher1.send(28)
print("Publisher1 emits 50")
publisher1.send(50)
subscription1.cancel()
subscription2.cancel()
/*:
## Example: `filter`
- works like Swift's `filter`
- ... operates on values over time
*/
let publisher3 = publisher1.filter {
// only let even values pass through
($0 % 2) == 0
}
let subscription3 = publisher3
.sink { value in
print("Subscription3 received integer: \(value)")
}
print("\n* Demonstrating filter operator")
print("Publisher1 emits 14")
publisher1.send(14)
print("Publisher1 emits 15")
publisher1.send(15)
print("Publisher1 emits 16")
publisher1.send(16)
//: [Next](@next)
|
mit
|
3b4160b23a19bd0a59888aea871aaac9
| 18.449275 | 59 | 0.710879 | 3.476684 | false | false | false | false |
VirrageS/TDL
|
TDL/EditTaskCell.swift
|
1
|
14345
|
import UIKit
let editTaskCellHeight: CGFloat = 40
let editTaskCellTextFontSize: CGFloat = 17
class EditTaskCell: UITableViewCell {
let separatorLineLabel: UILabel
let completeButton: UIButton
let postponeButton: UIButton
let editButton: UIButton
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
let completeImage: UIImage = UIImage(named: "complete-image") as UIImage!
completeButton = UIButton.buttonWithType(UIButtonType.System) as! UIButton
completeButton.setImage(completeImage, forState: UIControlState.Normal)
completeButton.frame = CGRectMake(20, 5, 50, 50)
let postponeImage: UIImage = UIImage(named: "postpone-image") as UIImage!
postponeButton = UIButton.buttonWithType(UIButtonType.System) as! UIButton
postponeButton.setImage(postponeImage, forState: UIControlState.Normal)
postponeButton.frame = CGRectMake(135, 5, 50, 50)
let editImage: UIImage = UIImage(named: "edit-image") as UIImage!
editButton = UIButton.buttonWithType(UIButtonType.InfoDark) as! UIButton
editButton.setImage(editImage, forState: UIControlState.Normal)
editButton.frame = CGRectMake(250, 5, 50, 50)
separatorLineLabel = UILabel(frame: CGRectZero)
separatorLineLabel.backgroundColor = UIColor(red: 178/255, green: 178/255, blue: 178/255, alpha: 1.0)
super.init(style: style, reuseIdentifier: reuseIdentifier)
contentView.backgroundColor = UIColor(red: 160/255, green: 160/255, blue: 160/255, alpha: 0.2)
completeButton.addTarget(self, action: "complete:", forControlEvents: UIControlEvents.TouchUpInside)
postponeButton.addTarget(self, action: "postpone:", forControlEvents: UIControlEvents.TouchUpInside)
editButton.addTarget(self, action: "edit:", forControlEvents: UIControlEvents.TouchUpInside)
// Content subview
contentView.addSubview(separatorLineLabel)
contentView.addSubview(completeButton)
contentView.addSubview(postponeButton)
contentView.addSubview(editButton)
// Constraints
separatorLineLabel.setTranslatesAutoresizingMaskIntoConstraints(false)
contentView.addConstraint(NSLayoutConstraint(item: separatorLineLabel, attribute: .Left, relatedBy: .Equal, toItem: contentView, attribute: .Left, multiplier: 1, constant: 20))
contentView.addConstraint(NSLayoutConstraint(item: separatorLineLabel, attribute: .Top, relatedBy: .Equal, toItem: contentView, attribute: .Bottom, multiplier: 1, constant: -0.5))
contentView.addConstraint(NSLayoutConstraint(item: separatorLineLabel, attribute: .Right, relatedBy: .Equal, toItem: contentView, attribute: .Right, multiplier: 1, constant: 0))
contentView.addConstraint(NSLayoutConstraint(item: separatorLineLabel, attribute: .Bottom, relatedBy: .Equal, toItem: contentView, attribute: .Bottom, multiplier: 1, constant: 0))
}
func complete(sender: UIButton!) {
let buttonCell = sender.superview?.superview as! UITableViewCell
let tableView = buttonCell.superview?.superview as! UITableView
let indexPath = tableView.indexPathForCell(buttonCell) as NSIndexPath?
var window: AnyObject = sender.superview!
while !(window is UIWindow) {
window = window.superview!!
}
window = window.rootViewController as! UINavigationController
if window.topViewController is TaskViewController {
let cellIndexPath = NSIndexPath(forRow: indexPath!.row - 1, inSection: indexPath!.section)
var task: Task = weekTasks[cellIndexPath!.section][cellIndexPath!.row]
for i in 0...allTasks.count-1 {
if allTasks[i] === task {
allTasks.removeAtIndex(i)
break
}
}
editTaskCell!.position = nil
updateWeekTasks()
tableView.beginUpdates()
tableView.deleteRowsAtIndexPaths([indexPath!], withRowAnimation: UITableViewRowAnimation.Left)
tableView.deleteRowsAtIndexPaths([cellIndexPath!], withRowAnimation: UITableViewRowAnimation.Left)
tableView.reloadData()
tableView.endUpdates()
} else if window.topViewController is TodayTaskViewController {
let cellIndexPath = NSIndexPath(forRow: indexPath!.row - 1, inSection: indexPath!.section)
var task: Task = todayTasks[cellIndexPath!.section][cellIndexPath!.row]
for i in 0...allTasks.count-1 {
if allTasks[i] === task {
allTasks.removeAtIndex(i)
break
}
}
editTaskCell!.position = nil
updateTodayTasks()
tableView.beginUpdates()
tableView.deleteRowsAtIndexPaths([indexPath!], withRowAnimation: UITableViewRowAnimation.Left)
tableView.deleteRowsAtIndexPaths([cellIndexPath!], withRowAnimation: UITableViewRowAnimation.Left)
// Add "no task" cell if there is no cells
if (todayTasks[0].count + todayTasks[1].count) == 0 {
tableView.insertRowsAtIndexPaths([NSIndexPath(forRow: 0, inSection: 0)], withRowAnimation: UITableViewRowAnimation.Left)
}
tableView.reloadData()
tableView.endUpdates()
} else if window.topViewController is DetailFilterViewController {
// Change due date
let cellIndexPath = NSIndexPath(forRow: indexPath!.row - 1, inSection: indexPath!.section)
var task: Task = detailFilterTasks[cellIndexPath!.row]
var date: NSDate?
for i in 0...allTasks.count-1 {
if allTasks[i] === task {
allTasks.removeAtIndex(i)
break
}
}
// Delete and insert rows
editTaskCell!.position = nil
updateDetailFilterTasks()
tableView.beginUpdates()
tableView.deleteRowsAtIndexPaths([indexPath!], withRowAnimation: UITableViewRowAnimation.Left)
tableView.deleteRowsAtIndexPaths([cellIndexPath!], withRowAnimation: UITableViewRowAnimation.Left)
// Add no task cell if there is no cells
if detailFilterTasks.count == 0 {
tableView.insertRowsAtIndexPaths([NSIndexPath(forRow: 0, inSection: 0)], withRowAnimation: UITableViewRowAnimation.Left)
}
tableView.reloadData()
tableView.endUpdates()
}
}
func postpone(sender: UIButton!) { // TODO: clean up
let buttonCell = sender.superview?.superview as! UITableViewCell
let tableView = buttonCell.superview?.superview as! UITableView
let indexPath = tableView.indexPathForCell(buttonCell) as NSIndexPath?
if indexPath == nil {
println("postpone button - indexPath is nil")
return
}
var window: AnyObject = sender.superview!
while !(window is UIWindow) {
window = window.superview!!
}
window = window.rootViewController as! UINavigationController
if window.topViewController is TaskViewController {
// Change due date
let cellIndexPath = NSIndexPath(forRow: indexPath!.row - 1, inSection: indexPath!.section)
var task: Task = weekTasks[cellIndexPath!.section][cellIndexPath!.row]
for i in 0...allTasks.count-1 {
if allTasks[i] === task {
allTasks[i].dueDate = NSDate(timeInterval: NSTimeInterval(60*60*24), sinceDate: task.dueDate!)
break
}
}
// Delete and insert rows
editTaskCell!.position = nil
updateWeekTasks()
tableView.beginUpdates()
tableView.deleteRowsAtIndexPaths([indexPath!], withRowAnimation: UITableViewRowAnimation.Left)
tableView.deleteRowsAtIndexPaths([cellIndexPath!], withRowAnimation: UITableViewRowAnimation.Left)
if cellIndexPath!.section + 1 <= 6 {
tableView.insertRowsAtIndexPaths([NSIndexPath(forRow: weekTasks[cellIndexPath!.section + 1].count - 1, inSection: cellIndexPath!.section + 1)], withRowAnimation: UITableViewRowAnimation.Left)
}
tableView.reloadData()
tableView.endUpdates()
} else if window.topViewController is TodayTaskViewController {
// Change due date
let cellIndexPath = NSIndexPath(forRow: indexPath!.row - 1, inSection: indexPath!.section)
var task: Task = todayTasks[cellIndexPath!.section][cellIndexPath!.row]
var date: NSDate?
for i in 0...allTasks.count-1 {
if allTasks[i] === task {
allTasks[i].dueDate = NSDate(timeInterval: NSTimeInterval(60*60*24), sinceDate: task.dueDate!)
date = allTasks[i].dueDate!
break
}
}
// Delete and insert rows
editTaskCell!.position = nil
updateTodayTasks()
tableView.beginUpdates()
tableView.deleteRowsAtIndexPaths([indexPath!], withRowAnimation: UITableViewRowAnimation.Left)
tableView.deleteRowsAtIndexPaths([cellIndexPath!], withRowAnimation: UITableViewRowAnimation.Left)
if date!.isEqualToDateIgnoringTime(NSDate(timeIntervalSinceNow: NSTimeInterval(0))) {
// insert to Today
tableView.insertRowsAtIndexPaths([NSIndexPath(forRow: todayTasks[cellIndexPath!.section + 1].count - 1, inSection: cellIndexPath!.section + 1)], withRowAnimation: UITableViewRowAnimation.Left)
} else if !date!.isEqualToDateIgnoringTime(NSDate(timeIntervalSinceNow: NSTimeInterval(0))) && date!.isEarlierThanDate(NSDate(timeIntervalSinceNow: NSTimeInterval(0))) {
tableView.insertRowsAtIndexPaths([NSIndexPath(forRow: todayTasks[cellIndexPath!.section].count - 1, inSection: cellIndexPath!.section)], withRowAnimation: UITableViewRowAnimation.Left)
}
// Add no task cell if there is no cells
if (todayTasks[0].count + todayTasks[1].count) == 0 {
tableView.insertRowsAtIndexPaths([NSIndexPath(forRow: 0, inSection: 0)], withRowAnimation: UITableViewRowAnimation.Left)
}
tableView.reloadData()
tableView.endUpdates()
} else if window.topViewController is DetailFilterViewController {
// Change due date
let cellIndexPath = NSIndexPath(forRow: indexPath!.row - 1, inSection: indexPath!.section)
var task: Task = detailFilterTasks[cellIndexPath!.row]
var date: NSDate?
if task.dueDate != nil {
for i in 0...allTasks.count-1 {
if allTasks[i] === task {
allTasks[i].dueDate = NSDate(timeInterval: NSTimeInterval(60*60*24), sinceDate: task.dueDate!)
date = allTasks[i].dueDate!
break
}
}
// Delete and insert rows
editTaskCell!.position = nil
updateDetailFilterTasks()
tableView.beginUpdates()
tableView.deleteRowsAtIndexPaths([indexPath!], withRowAnimation: UITableViewRowAnimation.Left)
// Add no task cell if there is no cells
if detailFilterTasks.count == 0 {
tableView.insertRowsAtIndexPaths([NSIndexPath(forRow: 0, inSection: 0)], withRowAnimation: UITableViewRowAnimation.Left)
}
tableView.reloadData()
tableView.endUpdates()
} else {
var alert = UIAlertView()
alert.title = "Error"
alert.message = "You cannot postpone task if it has no due date. Change the due date first"
alert.addButtonWithTitle("Back")
alert.show()
}
}
}
func edit(sender: UIButton!) {
let buttonCell = sender.superview?.superview as! UITableViewCell
let tableView = buttonCell.superview?.superview as! UITableView
let indexPath = tableView.indexPathForCell(buttonCell) as NSIndexPath?
// Check if indexPath is not nil
if indexPath == nil {
println("edit button - indexPath is nil")
return
}
// Search for main window
var window: AnyObject = sender.superview!
while !(window is UIWindow) {
window = window.superview!!
}
window = window.rootViewController as! UINavigationController
let cellIndexPath = NSIndexPath(forRow: indexPath!.row - 1, inSection: indexPath!.section)
if window.topViewController is TaskViewController {
let controller = window.topViewController as! TaskViewController
controller.openEditTaskController(weekTasks[indexPath!.section][indexPath!.row - 1])
} else if window.topViewController is TodayTaskViewController {
let controller = window.topViewController as! TodayTaskViewController
controller.openEditTaskController(todayTasks[indexPath!.section][indexPath!.row - 1])
} else if window.topViewController is DetailFilterViewController {
let controller = window.topViewController as! DetailFilterViewController
controller.openEditTaskController(detailFilterTasks[indexPath!.row - 1])
}
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
|
mit
|
57c97d7e6c0856d03327916b35d251df
| 46.979933 | 208 | 0.616731 | 5.754112 | false | false | false | false |
qingtianbuyu/Mono
|
Moon/Classes/Main/View/Mine/MNFollowFeedCell.swift
|
1
|
2266
|
//
// MNFollowFeedCell.swift
// Moon
//
// Created by YKing on 16/6/18.
// Copyright © 2016年 YKing. All rights reserved.
//
import UIKit
class MNFollowFeedCell: UITableViewCell {
@IBOutlet weak var iconView: UIImageView!
@IBOutlet weak var timeLabel: UILabel!
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var buttonThumb: UIButton!
@IBOutlet weak var buttonComment: UIButton!
@IBOutlet weak var topContainerView: UIView!
lazy var musicView:MNMineMusicView = {
let musicView = MNMineMusicView.viewFromXib() as! MNMineMusicView
self.musicContainerView.addSubview(musicView)
musicView.frame = self.musicContainerView.bounds
return musicView
}()
/// 直接设置xib的view的frame并不起作用,所以在外面套一层
lazy var musicContainerView:UIView = {
let musicView = UIView()
self.contentView.addSubview(musicView)
return musicView
}()
lazy var sevenView:MNMineSevenView = {
let sevenView = MNMineSevenView()
self.contentView.addSubview(sevenView)
return sevenView
}()
var followFeed: MNFollowFeed? {
didSet {
musicView.isHidden = true
sevenView.isHidden = true
let date = Date(timeIntervalSince1970: Double(followFeed?.created_at ?? 0))
let formatter = DateFormatter()
formatter.dateFormat = "yyyy.MM.dd HH:mm"
let dateStr = formatter.string(from: date)
let avatar_url = followFeed?.action_user?.avatar_url
self.iconView.m_setImageWithUrl(avatar_url)
self.timeLabel.text = dateStr
self.titleLabel.text = followFeed?.action_user?.name
let musicViewX:CGFloat = 55
let musicViewY:CGFloat = 50
let musicViewWith = ScreenWidth - musicViewX - 10
// music
if followFeed?.action == 5 {
musicView.meow = followFeed?.meow
musicContainerView.frame = CGRect(x: musicViewX, y: musicViewY, width: musicViewWith, height: 87)
musicView.isHidden = false
} else if followFeed?.action == 7 {
sevenView.group_member = followFeed?.group_member
sevenView.frame = CGRect(x: musicViewX, y: musicViewY, width: musicViewWith, height: 60)
sevenView.isHidden = false
}
}
}
}
|
mit
|
7264a6e367fa8125784eb8bc63da949e
| 27.164557 | 105 | 0.675955 | 4.045455 | false | false | false | false |
groue/RxGRDB
|
Sources/RxGRDB/DatabaseRegionObservation+Rx.swift
|
1
|
2668
|
import GRDB
import RxSwift
extension DatabaseRegionObservation {
/// Reactive extensions.
public var rx: GRDBReactive<Self> { GRDBReactive(self) }
}
extension GRDBReactive where Base == DatabaseRegionObservation {
/// Returns an Observable that emits the same elements as
/// a DatabaseRegionObservation.
///
/// All elements are emitted in a protected database dispatch queue,
/// serialized with all database updates. If you set *startImmediately* to
/// true (the default value), the first element is emitted synchronously
/// upon subscription. See [GRDB Concurrency Guide](https://github.com/groue/GRDB.swift/blob/master/README.md#concurrency)
/// for more information.
///
/// let dbQueue = DatabaseQueue()
/// try dbQueue.write { db in
/// try db.create(table: "player") { t in
/// t.column("id", .integer).primaryKey()
/// t.column("name", .text)
/// }
/// }
///
/// struct Player: Encodable, PersistableRecord {
/// var id: Int64
/// var name: String
/// }
///
/// let request = Player.all()
/// let observation = DatabaseRegionObservation(tracking: request)
/// observation.rx
/// .changes(in: dbQueue)
/// .subscribe(onNext: { db in
/// let count = try! Player.fetchCount(db)
/// print("Number of players: \(count)")
/// })
/// // Prints "Number of players: 0"
///
/// try dbQueue.write { db in
/// try Player(id: 1, name: "Arthur").insert(db)
/// try Player(id: 2, name: "Barbara").insert(db)
/// }
/// // Prints "Number of players: 2"
///
/// try dbQueue.inDatabase { db in
/// try Player(id: 3, name: "Craig").insert(db)
/// // Prints "Number of players: 3"
/// try Player(id: 4, name: "David").insert(db)
/// // Prints "Number of players: 4"
/// }
///
/// - parameter writer: A DatabaseWriter (DatabaseQueue or DatabasePool).
public func changes(in writer: DatabaseWriter) -> Observable<Database> {
Observable.create { observer -> Disposable in
do {
let transactionObserver = try self.base.start(in: writer, onChange: observer.onNext)
return Disposables.create {
writer.remove(transactionObserver: transactionObserver)
}
} catch {
observer.onError(error)
return Disposables.create()
}
}
}
}
|
mit
|
b0a5846e6efb6f326fe3e716f6d8c70e
| 37.666667 | 126 | 0.547601 | 4.484034 | false | false | false | false |
overtake/TelegramSwift
|
Telegram-Mac/ChatMessageItem.swift
|
1
|
44800
|
//
// ChatMessageItem.swift
// Telegram-Mac
//
// Created by keepcoder on 16/09/16.
// Copyright © 2016 Telegram. All rights reserved.
//
import Cocoa
import TGUIKit
import TelegramCore
import InAppVideoServices
import Postbox
import SwiftSignalKit
import InAppSettings
import TGModernGrowingTextView
/*
static func == (lhs: ChatTextCustomEmojiAttribute, rhs: ChatTextCustomEmojiAttribute) -> Bool {
if lhs.fileId != rhs.fileId {
return false
}
if lhs.reference != rhs.reference {
return false
}
if lhs.emoji != rhs.emoji {
return false
}
return true
}
*/
struct ChatTextCustomEmojiAttribute : Equatable {
let fileId: Int64
let file: TelegramMediaFile?
let emoji: String
init(fileId: Int64, file: TelegramMediaFile?, emoji: String) {
self.fileId = fileId
self.emoji = emoji
self.file = file
}
var attachment: TGTextAttachment {
return .init(identifier: "\(arc4random64())", fileId: self.fileId, file: file, text: emoji, info: nil)
}
}
final class InlineStickerItem : Hashable {
enum Source : Equatable {
case attribute(ChatTextCustomEmojiAttribute)
case reference(StickerPackItem)
}
let source: Source
init(source: Source) {
self.source = source
}
func hash(into hasher: inout Hasher) {
switch source {
case let .attribute(emoji):
hasher.combine(emoji.fileId)
case let .reference(sticker):
hasher.combine(sticker.file.fileId.id)
}
}
static func ==(lhs: InlineStickerItem, rhs: InlineStickerItem) -> Bool {
if lhs.source != rhs.source {
return false
}
return true
}
static func apply(to attr: NSMutableAttributedString, associatedMedia: [MediaId : Media], entities: [MessageTextEntity], isPremium: Bool, ignoreSpoiler: Bool = false, offset: Int = 0) {
let copy = attr
var ranges: [NSRange] = []
if ignoreSpoiler {
for entity in entities.sorted(by: { $0.range.lowerBound > $1.range.lowerBound }) {
guard case .Spoiler = entity.type else {
continue
}
let range = NSRange(location: entity.range.lowerBound, length: entity.range.upperBound - entity.range.lowerBound)
ranges.append(range)
}
}
for entity in entities.sorted(by: { $0.range.lowerBound > $1.range.lowerBound }) {
guard case let .CustomEmoji(_, fileId) = entity.type else {
continue
}
let lower = entity.range.lowerBound + offset
let upper = entity.range.upperBound + offset
let range = NSRange(location: lower, length: upper - lower)
let intersection = ranges.first(where: { r in
return r.intersection(range) != nil
})
if intersection == nil {
let currentDict = copy.attributes(at: range.lowerBound, effectiveRange: nil)
var updatedAttributes: [NSAttributedString.Key: Any] = currentDict
let text = copy.string.nsstring.substring(with: range).fixed
updatedAttributes[NSAttributedString.Key("Attribute__EmbeddedItem")] = InlineStickerItem(source: .attribute(.init(fileId: fileId, file: associatedMedia[MediaId(namespace: Namespaces.Media.CloudFile, id: fileId)] as? TelegramMediaFile, emoji: text)))
let insertString = NSAttributedString(string: "🤡", attributes: updatedAttributes)
copy.replaceCharacters(in: range, with: insertString)
}
}
}
}
class ChatMessageItem: ChatRowItem {
public private(set) var messageText:NSAttributedString
public private(set) var textLayout:TextViewLayout
private let youtubeExternalLoader = MetaDisposable()
override var selectableLayout:[TextViewLayout] {
return [textLayout]
}
override func tableViewDidUpdated() {
webpageLayout?.table = self.table
}
override var isSharable: Bool {
if let webpage = webpageLayout {
if webpage.content.type == "proxy" {
return true
}
}
return super.isSharable
}
override var isBubbleFullFilled: Bool {
return containsBigEmoji || super.isBubbleFullFilled
}
override var isStateOverlayLayout: Bool {
return containsBigEmoji && renderType == .bubble || super.isStateOverlayLayout
}
override var bubbleContentInset: CGFloat {
return containsBigEmoji && renderType == .bubble ? 0 : super.bubbleContentInset
}
override var defaultContentTopOffset: CGFloat {
if isBubbled && !hasBubble {
return 2
}
return super.defaultContentTopOffset
}
override var hasBubble: Bool {
get {
if containsBigEmoji {
return false
} else {
return super.hasBubble
}
}
set {
super.hasBubble = newValue
}
}
let containsBigEmoji: Bool
override var isBigEmoji: Bool {
return containsBigEmoji
}
var actionButtonWidth: CGFloat {
if let webpage = webpageLayout {
if webpage.isTheme {
return webpage.size.width
}
} else if message?.adAttribute != nil {
if isBubbled {
return bubbleFrame.width - bubbleDefaultInnerInset
}
}
return self.contentSize.width
}
var actionButtonText: String? {
if let _ = message?.adAttribute, let author = message?.author {
if author.isBot {
return strings().chatMessageViewBot
} else if author.isGroup || author.isSupergroup {
return strings().chatMessageViewGroup
} else {
return strings().chatMessageViewChannel
}
}
if let webpage = webpageLayout, !webpage.hasInstantPage {
let link = inApp(for: webpage.content.url.nsstring, context: context, openInfo: chatInteraction.openInfo)
switch link {
case let .followResolvedName(_, _, postId, _, action, _):
if let action = action {
inner: switch action {
case let .joinVoiceChat(hash):
if hash != nil {
return strings().chatMessageJoinVoiceChatAsSpeaker
} else {
return strings().chatMessageJoinVoiceChatAsListener
}
default:
break inner
}
}
if let postId = postId, postId > 0 {
return strings().chatMessageActionShowMessage
}
default:
break
}
if webpage.wallpaper != nil {
return strings().chatViewBackground
}
if webpage.isTheme {
return strings().chatActionViewTheme
}
}
if unsupported {
return strings().chatUnsupportedUpdatedApp
}
return nil
}
override var isEditMarkVisible: Bool {
if containsBigEmoji {
return false
} else {
return super.isEditMarkVisible
}
}
func invokeAction() {
if let adAttribute = message?.adAttribute, let peer = peer {
let link: inAppLink
switch adAttribute.target {
case let .peer(id, messageId, startParam):
let action: ChatInitialAction?
if let startParam = startParam {
action = .start(parameter: startParam, behavior: .none)
} else {
action = nil
}
link = inAppLink.peerInfo(link: "", peerId: id, action: action, openChat: peer.isChannel || peer.isBot, postId: messageId?.id, callback: chatInteraction.openInfo)
case let .join(_, joinHash):
link = .joinchat(link: "", joinHash, context: context, callback: chatInteraction.openInfo)
}
execute(inapp: link)
} else if let webpage = webpageLayout {
let link = inApp(for: webpage.content.url.nsstring, context: context, openInfo: chatInteraction.openInfo)
execute(inapp: link)
} else if unsupported {
#if APP_STORE
execute(inapp: inAppLink.external(link: "https://apps.apple.com/us/app/telegram/id747648890", false))
#else
(NSApp.delegate as? AppDelegate)?.checkForUpdates("")
#endif
}
}
let wpPresentation: WPLayoutPresentation
var webpageLayout:WPLayout?
override init(_ initialSize:NSSize, _ chatInteraction:ChatInteraction,_ context: AccountContext, _ entry: ChatHistoryEntry, _ downloadSettings: AutomaticMediaDownloadSettings, theme: TelegramPresentationTheme) {
if let message = entry.message {
let isIncoming: Bool = message.isIncoming(context.account, entry.renderType == .bubble)
var openSpecificTimecodeFromReply:((Double?)->Void)? = nil
let messageAttr:NSMutableAttributedString
if message.inlinePeer == nil, message.text.isEmpty && (message.media.isEmpty || message.effectiveMedia is TelegramMediaUnsupported) {
let attr = NSMutableAttributedString()
_ = attr.append(string: strings().chatMessageUnsupportedNew, color: theme.chat.textColor(isIncoming, entry.renderType == .bubble), font: .code(theme.fontSize))
messageAttr = attr
} else {
var mediaDuration: Double? = nil
var mediaDurationMessage:Message?
var canAssignToReply: Bool = true
if let media = message.effectiveMedia as? TelegramMediaWebpage {
switch media.content {
case let .Loaded(content):
canAssignToReply = !ExternalVideoLoader.isPlayable(content)
default:
break
}
}
if canAssignToReply, let reply = message.replyAttribute {
mediaDurationMessage = message.associatedMessages[reply.messageId]
} else {
mediaDurationMessage = message
}
if let message = mediaDurationMessage {
if let file = message.effectiveMedia as? TelegramMediaFile, file.isVideo && !file.isAnimated, let duration = file.duration {
mediaDuration = Double(duration)
} else if let media = message.effectiveMedia as? TelegramMediaWebpage {
switch media.content {
case let .Loaded(content):
if ExternalVideoLoader.isPlayable(content) {
mediaDuration = 10 * 60 * 60
}
default:
break
}
}
}
let openInfo:(PeerId, Bool, MessageId?, ChatInitialAction?)->Void = { [weak chatInteraction] peerId, toChat, postId, initialAction in
chatInteraction?.openInfo(peerId, toChat, postId, initialAction ?? .source(message.id))
}
messageAttr = ChatMessageItem.applyMessageEntities(with: message.attributes, for: message.text, message: message, context: context, fontSize: theme.fontSize, openInfo:openInfo, botCommand:chatInteraction.sendPlainText, hashtag: chatInteraction.context.bindings.globalSearch, applyProxy: chatInteraction.applyProxy, textColor: theme.chat.textColor(isIncoming, entry.renderType == .bubble), linkColor: theme.chat.linkColor(isIncoming, entry.renderType == .bubble), monospacedPre: theme.chat.monospacedPreColor(isIncoming, entry.renderType == .bubble), monospacedCode: theme.chat.monospacedCodeColor(isIncoming, entry.renderType == .bubble), mediaDuration: mediaDuration, timecode: { timecode in
openSpecificTimecodeFromReply?(timecode)
}).mutableCopy() as! NSMutableAttributedString
var formatting: Bool = messageAttr.length > 0
var index:Int = 0
while formatting {
var effectiveRange:NSRange = NSMakeRange(NSNotFound, 0)
if let _ = messageAttr.attribute(.preformattedPre, at: index, effectiveRange: &effectiveRange), effectiveRange.location != NSNotFound {
let beforeAndAfter:(Int)->Bool = { index -> Bool in
let prefix:String = messageAttr.string.nsstring.substring(with: NSMakeRange(index, 1))
let whiteSpaceRange = prefix.rangeOfCharacter(from: NSCharacterSet.whitespaces)
var increment: Bool = false
if let _ = whiteSpaceRange {
messageAttr.replaceCharacters(in: NSMakeRange(index, 1), with: "\n")
} else if prefix != "\n" {
messageAttr.insert(.initialize(string: "\n"), at: index)
increment = true
}
return increment
}
if effectiveRange.min > 0 {
let increment = beforeAndAfter(effectiveRange.min)
if increment {
effectiveRange = NSMakeRange(effectiveRange.location, effectiveRange.length + 1)
}
}
if effectiveRange.max < messageAttr.length - 1 {
let increment = beforeAndAfter(effectiveRange.max)
if increment {
effectiveRange = NSMakeRange(effectiveRange.location, effectiveRange.length + 1)
}
}
}
if effectiveRange.location != NSNotFound {
index += effectiveRange.length
} else {
index += 1
}
formatting = index < messageAttr.length
}
}
let copy = messageAttr.mutableCopy() as! NSMutableAttributedString
if let peer = message.peers[message.id.peerId] {
if peer is TelegramSecretChat {
copy.detectLinks(type: [.Links, .Mentions], context: context, color: theme.chat.linkColor(isIncoming, entry.renderType == .bubble), openInfo: chatInteraction.openInfo)
}
}
let containsBigEmoji: Bool
if message.effectiveMedia == nil, bigEmojiMessage(context.sharedContext, message: message) {
containsBigEmoji = true
switch copy.string.count {
case 1:
copy.addAttribute(.font, value: NSFont.normal(theme.fontSize * 8), range: copy.range)
case 2:
copy.addAttribute(.font, value: NSFont.normal(theme.fontSize * 7), range: copy.range)
case 3:
copy.addAttribute(.font, value: NSFont.normal(theme.fontSize * 6), range: copy.range)
case 4:
copy.addAttribute(.font, value: NSFont.normal(theme.fontSize * 5), range: copy.range)
case 5:
copy.addAttribute(.font, value: NSFont.normal(theme.fontSize * 4), range: copy.range)
case 6:
copy.addAttribute(.font, value: NSFont.normal(theme.fontSize * 3), range: copy.range)
default:
copy.addAttribute(.font, value: NSFont.normal(theme.fontSize * 2), range: copy.range)
}
} else {
containsBigEmoji = false
}
self.containsBigEmoji = containsBigEmoji
if message.flags.contains(.Failed) || message.flags.contains(.Unsent) || message.flags.contains(.Sending) {
copy.detectLinks(type: [.Links, .Mentions, .Hashtags, .Commands], context: context, color: theme.chat.linkColor(isIncoming, entry.renderType == .bubble), openInfo: chatInteraction.openInfo, hashtag: { _ in }, command: { _ in }, applyProxy: chatInteraction.applyProxy)
}
var spoilers:[TextViewLayout.Spoiler] = []
for attr in message.attributes {
if let attr = attr as? TextEntitiesMessageAttribute {
for entity in attr.entities {
switch entity.type {
case .Spoiler:
let color: NSColor
if entry.renderType == .bubble {
color = theme.chat.grayText(isIncoming, entry.renderType == .bubble)
} else {
color = theme.chat.textColor(isIncoming, entry.renderType == .bubble)
}
let range = NSMakeRange(entity.range.lowerBound, entity.range.upperBound - entity.range.lowerBound)
copy.addAttribute(.init(rawValue: TGSpoilerAttributeName), value: TGInputTextTag(uniqueId: arc4random64(), attachment: NSNumber(value: -1), attribute: TGInputTextAttribute(name: NSAttributedString.Key.foregroundColor.rawValue, value: color)), range: range)
default:
break
}
}
}
}
InlineStickerItem.apply(to: copy, associatedMedia: message.associatedMedia, entities: message.textEntities?.entities ?? [], isPremium: context.isPremium)
copy.fixUndefinedEmojies()
if let text = message.restrictedText(context.contentSettings) {
self.messageText = .initialize(string: text, color: theme.colors.grayText, font: .italic(theme.fontSize))
} else {
self.messageText = copy
}
copy.enumerateAttribute(.init(rawValue: TGSpoilerAttributeName), in: copy.range, options: .init(), using: { value, range, stop in
if let text = value as? TGInputTextTag {
if let color = text.attribute.value as? NSColor {
spoilers.append(.init(range: range, color: color, isRevealed: chatInteraction.presentation.interfaceState.revealedSpoilers.contains(message.id)))
}
}
})
textLayout = TextViewLayout(self.messageText, selectText: theme.chat.selectText(isIncoming, entry.renderType == .bubble), strokeLinks: entry.renderType == .bubble && !containsBigEmoji, alwaysStaticItems: true, disableTooltips: false, mayItems: !message.isCopyProtected(), spoilers: spoilers, onSpoilerReveal: { [weak chatInteraction] in
chatInteraction?.update({
$0.updatedInterfaceState({
$0.withRevealedSpoiler(message.id)
})
})
})
textLayout.mayBlocked = entry.renderType != .bubble
if let highlightFoundText = entry.additionalData.highlightFoundText {
if highlightFoundText.isMessage {
let range = copy.string.lowercased().nsstring.range(of: highlightFoundText.query.lowercased())
if range.location != NSNotFound {
textLayout.additionalSelections = [TextSelectedRange(range: range, color: theme.colors.accentIcon.withAlphaComponent(0.5), def: false)]
}
} else {
var additionalSelections:[TextSelectedRange] = []
let string = copy.string.lowercased().nsstring
var searchRange = NSMakeRange(0, string.length)
var foundRange:NSRange = NSMakeRange(NSNotFound, 0)
while (searchRange.location < string.length) {
searchRange.length = string.length - searchRange.location
foundRange = string.range(of: highlightFoundText.query.lowercased(), options: [], range: searchRange)
if (foundRange.location != NSNotFound) {
additionalSelections.append(TextSelectedRange(range: foundRange, color: theme.colors.grayIcon.withAlphaComponent(0.5), def: false))
searchRange.location = foundRange.location+foundRange.length;
} else {
break
}
}
textLayout.additionalSelections = additionalSelections
}
}
if let range = selectManager.find(entry.stableId) {
textLayout.selectedRange.range = range
}
var media = message.effectiveMedia
if let game = media as? TelegramMediaGame {
media = TelegramMediaWebpage(webpageId: MediaId(namespace: 0, id: 0), content: TelegramMediaWebpageContent.Loaded(TelegramMediaWebpageLoadedContent(url: "", displayUrl: "", hash: 0, type: "photo", websiteName: game.name, title: game.name, text: game.description, embedUrl: nil, embedType: nil, embedSize: nil, duration: nil, author: nil, image: game.image, file: game.file, attributes: [], instantPage: nil)))
}
self.wpPresentation = WPLayoutPresentation(text: theme.chat.textColor(isIncoming, entry.renderType == .bubble), activity: theme.chat.webPreviewActivity(isIncoming, entry.renderType == .bubble), link: theme.chat.linkColor(isIncoming, entry.renderType == .bubble), selectText: theme.chat.selectText(isIncoming, entry.renderType == .bubble), ivIcon: theme.chat.instantPageIcon(isIncoming, entry.renderType == .bubble, presentation: theme), renderType: entry.renderType)
if let webpage = media as? TelegramMediaWebpage {
switch webpage.content {
case let .Loaded(content):
var forceArticle: Bool = false
if let instantPage = content.instantPage {
if instantPage.blocks.count == 3 {
switch instantPage.blocks[2] {
case .collage, .slideshow:
forceArticle = true
default:
break
}
}
}
if content.type == "telegram_background" {
forceArticle = true
}
if content.file == nil || forceArticle {
webpageLayout = WPArticleLayout(with: content, context: context, chatInteraction: chatInteraction, parent:message, fontSize: theme.fontSize, presentation: wpPresentation, approximateSynchronousValue: Thread.isMainThread, downloadSettings: downloadSettings, autoplayMedia: entry.autoplayMedia, theme: theme, mayCopyText: !message.isCopyProtected())
} else {
webpageLayout = WPMediaLayout(with: content, context: context, chatInteraction: chatInteraction, parent:message, fontSize: theme.fontSize, presentation: wpPresentation, approximateSynchronousValue: Thread.isMainThread, downloadSettings: downloadSettings, autoplayMedia: entry.autoplayMedia, theme: theme, mayCopyText: !message.isCopyProtected())
}
default:
break
}
}
super.init(initialSize, chatInteraction, context, entry, downloadSettings, theme: theme)
(webpageLayout as? WPMediaLayout)?.parameters?.showMedia = { [weak self] message in
if let webpage = message.effectiveMedia as? TelegramMediaWebpage {
switch webpage.content {
case let .Loaded(content):
if content.embedType == "iframe" && content.type != kBotInlineTypeGif, let url = content.embedUrl {
showModal(with: WebpageModalController(context: context, url: url, title: content.websiteName ?? content.title ?? strings().webAppTitle, effectiveSize: content.embedSize?.size, chatInteraction: self?.chatInteraction), for: context.window)
return
}
default:
break
}
} else if let keybaord = message.replyMarkup {
if let button = keybaord.rows.first?.buttons.first {
switch button.action {
case .openWebApp:
self?.chatInteraction.requestMessageActionCallback(message.id, true, nil)
return
default:
break
}
}
}
showChatGallery(context: context, message: message, self?.table, (self?.webpageLayout as? WPMediaLayout)?.parameters, type: .alone)
}
openSpecificTimecodeFromReply = { [weak self] timecode in
if let timecode = timecode {
var canAssignToReply: Bool = true
if let media = message.effectiveMedia as? TelegramMediaWebpage {
switch media.content {
case let .Loaded(content):
canAssignToReply = !ExternalVideoLoader.isPlayable(content)
default:
break
}
}
var assignMessage: Message?
if canAssignToReply, let reply = message.replyAttribute {
assignMessage = message.associatedMessages[reply.messageId]
} else {
assignMessage = message
}
if let message = assignMessage {
let id = ChatHistoryEntryId.message(message)
if let item = self?.table?.item(stableId: id) as? ChatMediaItem {
item.parameters?.set_timeCodeInitializer(timecode)
item.parameters?.showMedia(message)
} else if let groupInfo = message.groupInfo {
let id = ChatHistoryEntryId.groupedPhotos(groupInfo: groupInfo)
if let item = self?.table?.item(stableId: id) as? ChatGroupedItem {
item.parameters.first?.set_timeCodeInitializer(timecode)
item.parameters.first?.showMedia(message)
}
} else if let item = self?.table?.item(stableId: id) as? ChatMessageItem {
if let content = item.webpageLayout?.content {
let content = content.withUpdatedYoutubeTimecode(timecode)
execute(inapp: .external(link: content.url, false))
}
}
}
}
}
let interactions = globalLinkExecutor
interactions.copy = {
selectManager.copy(selectManager)
return !selectManager.isEmpty
}
interactions.copyToClipboard = { text in
copyToClipboard(text)
}
interactions.topWindow = { [weak self] in
if let strongSelf = self {
return strongSelf.menuAdditionView
} else {
return .single(nil)
}
}
interactions.menuItems = { [weak self] type in
if let strongSelf = self, let message = strongSelf.message {
return chatMenuItems(for: message, entry: strongSelf.entry, textLayout: (strongSelf.textLayout, type), chatInteraction: strongSelf.chatInteraction)
}
return .complete()
}
interactions.hoverOnLink = { value in
}
textLayout.interactions = interactions
return
}
fatalError("entry has not message")
}
override var identifier: String {
if webpageLayout == nil {
return super.identifier
} else {
return super.identifier + "\(stableId)"
}
}
override var ignoreAtInitialization: Bool {
return message?.adAttribute != nil
}
override var isForceRightLine: Bool {
if actionButtonText != nil {
return true
}
if let webpageLayout = webpageLayout {
if let webpageLayout = webpageLayout as? WPArticleLayout {
if webpageLayout.hasInstantPage {
return true
}
if let _ = webpageLayout.imageSize {
return true
}
if actionButtonText != nil {
return true
}
if webpageLayout.groupLayout != nil {
return true
}
} else if webpageLayout is WPMediaLayout {
return true
}
}
if self.webpageLayout?.content.type == "proxy" {
return true
} else {
return super.isForceRightLine
}
}
override func makeContentSize(_ width: CGFloat) -> NSSize {
let size:NSSize = super.makeContentSize(width)
webpageLayout?.measure(width: min(width, 380))
let textBlockWidth: CGFloat = isBubbled ? max((webpageLayout?.size.width ?? width), min(240, width)) : width
textLayout.measure(width: textBlockWidth, isBigEmoji: containsBigEmoji)
var contentSize = NSMakeSize(max(webpageLayout?.contentRect.width ?? 0, textLayout.layoutSize.width), size.height + textLayout.layoutSize.height)
if let webpageLayout = webpageLayout {
contentSize.height += webpageLayout.size.height + defaultContentInnerInset
contentSize.width = max(webpageLayout.size.width, contentSize.width)
}
if let _ = actionButtonText {
contentSize.height += actionButtonHeight
contentSize.width = max(contentSize.width, 200)
}
return contentSize
}
var actionButtonHeight: CGFloat {
return 36
}
override var instantlyResize: Bool {
return true
}
override var bubbleFrame: NSRect {
var frame = super.bubbleFrame
if isBubbleFullFilled {
frame.size.width = contentSize.width + additionBubbleInset
return frame
}
if replyMarkupModel != nil, webpageLayout == nil, textLayout.layoutSize.width < 200 {
frame.size.width = max(blockWidth, frame.width)
}
return frame
}
override func menuItems(in location: NSPoint) -> Signal<[ContextMenuItem], NoError> {
if let message = message {
return chatMenuItems(for: message, entry: entry, textLayout: (self.textLayout, nil), chatInteraction: self.chatInteraction)
}
return super.menuItems(in: location)
}
deinit {
youtubeExternalLoader.dispose()
}
override func viewClass() -> AnyClass {
return ChatMessageView.self
}
static func applyMessageEntities(with attributes:[MessageAttribute], for text:String, message: Message?, context: AccountContext, fontSize: CGFloat, openInfo:@escaping (PeerId, Bool, MessageId?, ChatInitialAction?)->Void, botCommand:@escaping (String)->Void = { _ in }, hashtag:@escaping (String)->Void = { _ in }, applyProxy:@escaping (ProxyServerSettings)->Void = { _ in }, textColor: NSColor = theme.colors.text, linkColor: NSColor = theme.colors.link, monospacedPre:NSColor = theme.colors.monospacedPre, monospacedCode: NSColor = theme.colors.monospacedCode, mediaDuration: Double? = nil, timecode: @escaping(Double?)->Void = { _ in }, openBank: @escaping(String)->Void = { _ in }) -> NSAttributedString {
var entities: [MessageTextEntity] = []
for attribute in attributes {
if let attribute = attribute as? TextEntitiesMessageAttribute {
entities = attribute.entities
break
}
}
var fontAttributes: [(NSRange, ChatTextFontAttributes)] = []
let string = NSMutableAttributedString(string: text, attributes: [NSAttributedString.Key.font: NSFont.normal(fontSize), NSAttributedString.Key.foregroundColor: textColor])
let new = addLocallyGeneratedEntities(text, enabledTypes: [.timecode], entities: entities, mediaDuration: mediaDuration)
var nsString: NSString?
entities = entities + (new ?? [])
for entity in entities {
let range = string.trimRange(NSRange(location: entity.range.lowerBound, length: entity.range.upperBound - entity.range.lowerBound))
switch entity.type {
case .Url:
string.addAttribute(NSAttributedString.Key.foregroundColor, value: linkColor, range: range)
if nsString == nil {
nsString = text as NSString
}
let link = inApp(for:nsString!.substring(with: range) as NSString, context:context, openInfo:openInfo, applyProxy: applyProxy)
string.addAttribute(NSAttributedString.Key.link, value: link, range: range)
case .Email:
string.addAttribute(NSAttributedString.Key.foregroundColor, value: linkColor, range: range)
if nsString == nil {
nsString = text as NSString
}
string.addAttribute(NSAttributedString.Key.link, value: inAppLink.external(link: "mailto:\(nsString!.substring(with: range))", false), range: range)
case let .TextUrl(url):
string.addAttribute(NSAttributedString.Key.foregroundColor, value: linkColor, range: range)
if nsString == nil {
nsString = text as NSString
}
string.addAttribute(NSAttributedString.Key.link, value: inApp(for: url as NSString, context: context, openInfo: openInfo, hashtag: hashtag, command: botCommand, applyProxy: applyProxy, confirm: nsString?.substring(with: range).trimmed != url), range: range)
case .Bold:
fontAttributes.append((range, .bold))
case .Italic:
fontAttributes.append((range, .italic))
case .Mention:
string.addAttribute(NSAttributedString.Key.foregroundColor, value: linkColor, range: range)
if nsString == nil {
nsString = text as NSString
}
string.addAttribute(NSAttributedString.Key.link, value: inAppLink.followResolvedName(link: nsString!.substring(with: range), username: nsString!.substring(with: range), postId:nil, context:context, action:nil, callback: openInfo), range: range)
case let .TextMention(peerId):
string.addAttribute(NSAttributedString.Key.foregroundColor, value: linkColor, range: range)
string.addAttribute(NSAttributedString.Key.link, value: inAppLink.peerInfo(link: "", peerId: peerId, action:nil, openChat: false, postId: nil, callback: openInfo), range: range)
case .BotCommand:
string.addAttribute(NSAttributedString.Key.foregroundColor, value: textColor, range: range)
if nsString == nil {
nsString = text as NSString
}
string.addAttribute(NSAttributedString.Key.foregroundColor, value: linkColor, range: range)
string.addAttribute(NSAttributedString.Key.link, value: inAppLink.botCommand(nsString!.substring(with: range), botCommand), range: range)
case .Code:
string.addAttribute(.preformattedCode, value: 4.0, range: range)
fontAttributes.append((range, .monospace))
string.addAttribute(NSAttributedString.Key.foregroundColor, value: monospacedCode, range: range)
string.addAttribute(NSAttributedString.Key.link, value: inAppLink.code(text.nsstring.substring(with: range), { link in
copyToClipboard(link)
context.bindings.showControllerToaster(ControllerToaster(text: strings().shareLinkCopied), true)
}), range: range)
case .Pre:
string.addAttribute(.preformattedCode, value: 4.0, range: range)
fontAttributes.append((range, .monospace))
// string.addAttribute(.preformattedPre, value: 4.0, range: range)
string.addAttribute(NSAttributedString.Key.foregroundColor, value: monospacedPre, range: range)
case .Hashtag:
string.addAttribute(NSAttributedString.Key.foregroundColor, value: linkColor, range: range)
if nsString == nil {
nsString = text as NSString
}
string.addAttribute(NSAttributedString.Key.link, value: inAppLink.hashtag(nsString!.substring(with: range), hashtag), range: range)
case .Strikethrough:
string.addAttribute(NSAttributedString.Key.strikethroughStyle, value: true, range: range)
case .Underline:
string.addAttribute(NSAttributedString.Key.underlineStyle, value: true, range: range)
case .BankCard:
if nsString == nil {
nsString = text as NSString
}
string.addAttribute(NSAttributedString.Key.foregroundColor, value: linkColor, range: range)
string.addAttribute(NSAttributedString.Key.link, value: inAppLink.callback(nsString!.substring(with: range), { bankCard in
openBank(bankCard)
}), range: range)
case let .Custom(type):
if type == ApplicationSpecificEntityType.Timecode {
string.addAttribute(NSAttributedString.Key.foregroundColor, value: linkColor, range: range)
if nsString == nil {
nsString = text as NSString
}
let code = parseTimecodeString(nsString!.substring(with: range))
var link = ""
if let message = message {
var peer: Peer?
var messageId: MessageId?
if let info = message.forwardInfo {
peer = info.author
messageId = info.sourceMessageId
} else {
peer = message.effectiveAuthor
messageId = message.id
}
if let peer = peer, let messageId = messageId {
if let code = code, peer.isChannel || peer.isSupergroup {
let code = Int(round(code))
let address = peer.addressName ?? "\(messageId.peerId.id)"
link = "t.me/\(address)/\(messageId.id)?t=\(code)"
}
}
}
string.addAttribute(NSAttributedString.Key.link, value: inAppLink.callback(link, { _ in
timecode(code)
}), range: range)
}
default:
break
}
}
for (i, (range, attr)) in fontAttributes.enumerated() {
var font: NSFont?
var intersects:[(NSRange, ChatTextFontAttributes)] = []
for (j, value) in fontAttributes.enumerated() {
if j != i {
if let intersection = value.0.intersection(range) {
intersects.append((intersection, value.1))
}
}
}
switch attr {
case .monospace, .blockQuote:
font = .code(fontSize)
case .italic:
font = .italic(fontSize)
case .bold:
font = .bold(fontSize)
default:
break
}
if let font = font {
string.addAttribute(.font, value: font, range: range)
}
for intersect in intersects {
var font: NSFont? = nil
loop: switch intersect.1 {
case .italic:
switch attr {
case .bold:
font = .boldItalic(fontSize)
default:
break loop
}
case .bold:
switch attr {
case .bold:
font = .boldItalic(fontSize)
default:
break loop
}
default:
break loop
}
if let font = font {
string.addAttribute(.font, value: font, range: range)
}
}
}
return string.copy() as! NSAttributedString
}
}
/*
if let color = NSColor(hexString: nsString!.substring(with: range)) {
struct RunStruct {
let ascent: CGFloat
let descent: CGFloat
let width: CGFloat
}
let dimensions = NSMakeSize(theme.fontSize + 6, theme.fontSize + 6)
let extentBuffer = UnsafeMutablePointer<RunStruct>.allocate(capacity: 1)
extentBuffer.initialize(to: RunStruct(ascent: 0.0, descent: 0.0, width: dimensions.width))
var callbacks = CTRunDelegateCallbacks(version: kCTRunDelegateVersion1, dealloc: { (pointer) in
}, getAscent: { (pointer) -> CGFloat in
let d = pointer.assumingMemoryBound(to: RunStruct.self)
return d.pointee.ascent
}, getDescent: { (pointer) -> CGFloat in
let d = pointer.assumingMemoryBound(to: RunStruct.self)
return d.pointee.descent
}, getWidth: { (pointer) -> CGFloat in
let d = pointer.assumingMemoryBound(to: RunStruct.self)
return d.pointee.width
})
let delegate = CTRunDelegateCreate(&callbacks, extentBuffer)
let key = kCTRunDelegateAttributeName as String
let attrDictionaryDelegate:[NSAttributedString.Key : Any] = [NSAttributedString.Key(key): delegate as Any, .hexColorMark : color, .hexColorMarkDimensions: dimensions]
string.addAttributes(attrDictionaryDelegate, range: NSMakeRange(range.upperBound - 1, 1))
}
*/
|
gpl-2.0
|
74a6216526b9ec64a554146c506567a9
| 44.756895 | 713 | 0.543866 | 5.46626 | false | false | false | false |
abertelrud/swift-package-manager
|
Sources/XCBuildSupport/XcodeBuildSystem.swift
|
2
|
12192
|
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift open source project
//
// Copyright (c) 2020 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import Basics
import Dispatch
import class Foundation.JSONEncoder
import PackageGraph
import PackageModel
import SPMBuildCore
import TSCBasic
import class TSCUtility.MultiLinePercentProgressAnimation
import enum TSCUtility.Diagnostics
import protocol TSCUtility.ProgressAnimationProtocol
public final class XcodeBuildSystem: SPMBuildCore.BuildSystem {
private let buildParameters: BuildParameters
private let packageGraphLoader: () throws -> PackageGraph
private let logLevel: Basics.Diagnostic.Severity
private let xcbuildPath: AbsolutePath
private var packageGraph: PackageGraph?
private var pifBuilder: PIFBuilder?
private let fileSystem: FileSystem
private let observabilityScope: ObservabilityScope
/// The output stream for the build delegate.
private let outputStream: OutputByteStream
/// The delegate used by the build system.
public weak var delegate: SPMBuildCore.BuildSystemDelegate?
public var builtTestProducts: [BuiltTestProduct] {
guard let graph = try? getPackageGraph() else {
return []
}
var builtProducts: [BuiltTestProduct] = []
for package in graph.rootPackages {
for product in package.products where product.type == .test {
let binaryPath = buildParameters.binaryPath(for: product)
builtProducts.append(
BuiltTestProduct(
productName: product.name,
binaryPath: binaryPath
)
)
}
}
return builtProducts
}
public var buildPlan: SPMBuildCore.BuildPlan {
get throws {
throw StringError("XCBuild does not provide a build plan")
}
}
public init(
buildParameters: BuildParameters,
packageGraphLoader: @escaping () throws -> PackageGraph,
outputStream: OutputByteStream,
logLevel: Basics.Diagnostic.Severity,
fileSystem: FileSystem,
observabilityScope: ObservabilityScope
) throws {
self.buildParameters = buildParameters
self.packageGraphLoader = packageGraphLoader
self.outputStream = outputStream
self.logLevel = logLevel
self.fileSystem = fileSystem
self.observabilityScope = observabilityScope.makeChildScope(description: "Xcode Build System")
if let xcbuildTool = ProcessEnv.vars["XCBUILD_TOOL"] {
xcbuildPath = try AbsolutePath(validating: xcbuildTool)
} else {
let xcodeSelectOutput = try TSCBasic.Process.popen(args: "xcode-select", "-p").utf8Output().spm_chomp()
let xcodeDirectory = try AbsolutePath(validating: xcodeSelectOutput)
xcbuildPath = try AbsolutePath(validating: "../SharedFrameworks/XCBuild.framework/Versions/A/Support/xcbuild", relativeTo: xcodeDirectory)
}
guard fileSystem.exists(xcbuildPath) else {
throw StringError("xcbuild executable at '\(xcbuildPath)' does not exist or is not executable")
}
}
public func build(subset: BuildSubset) throws {
let pifBuilder = try getPIFBuilder()
let pif = try pifBuilder.generatePIF()
try self.fileSystem.writeIfChanged(path: buildParameters.pifManifest, bytes: ByteString(encodingAsUTF8: pif))
var arguments = [
xcbuildPath.pathString,
"build",
buildParameters.pifManifest.pathString,
"--configuration",
buildParameters.configuration.xcbuildName,
"--derivedDataPath",
buildParameters.dataPath.pathString,
"--target",
subset.pifTargetName
]
let buildParamsFile: AbsolutePath?
// Do not generate a build parameters file if a custom one has been passed.
if !buildParameters.xcbuildFlags.contains("--buildParametersFile") {
buildParamsFile = try createBuildParametersFile()
if let buildParamsFile = buildParamsFile {
arguments += ["--buildParametersFile", buildParamsFile.pathString]
}
} else {
buildParamsFile = nil
}
arguments += buildParameters.xcbuildFlags
let delegate = createBuildDelegate()
var hasStdout = false
var stdoutBuffer: [UInt8] = []
var stderrBuffer: [UInt8] = []
let redirection: TSCBasic.Process.OutputRedirection = .stream(stdout: { bytes in
hasStdout = hasStdout || !bytes.isEmpty
delegate.parse(bytes: bytes)
if !delegate.didParseAnyOutput {
stdoutBuffer.append(contentsOf: bytes)
}
}, stderr: { bytes in
stderrBuffer.append(contentsOf: bytes)
})
let process = TSCBasic.Process(arguments: arguments, outputRedirection: redirection)
try process.launch()
let result = try process.waitUntilExit()
if let buildParamsFile = buildParamsFile {
try? self.fileSystem.removeFileTree(buildParamsFile)
}
guard result.exitStatus == .terminated(code: 0) else {
if hasStdout {
if !delegate.didParseAnyOutput {
self.observabilityScope.emit(error: String(decoding: stdoutBuffer, as: UTF8.self))
}
} else {
if !stderrBuffer.isEmpty {
self.observabilityScope.emit(error: String(decoding: stderrBuffer, as: UTF8.self))
} else {
self.observabilityScope.emit(error: "Unknown error: stdout and stderr are empty")
}
}
throw Diagnostics.fatalError
}
}
func createBuildParametersFile() throws -> AbsolutePath {
// Generate the run destination parameters.
let runDestination = XCBBuildParameters.RunDestination(
platform: "macosx",
sdk: "macosx",
sdkVariant: nil,
targetArchitecture: buildParameters.triple.arch.rawValue,
supportedArchitectures: [],
disableOnlyActiveArch: true
)
// Generate a table of any overriding build settings.
var settings: [String: String] = [:]
// An error with determining the override should not be fatal here.
settings["CC"] = try? buildParameters.toolchain.getClangCompiler().pathString
// Always specify the path of the effective Swift compiler, which was determined in the same way as for the native build system.
settings["SWIFT_EXEC"] = buildParameters.toolchain.swiftCompilerPath.pathString
settings["LIBRARY_SEARCH_PATHS"] = "$(inherited) \(try buildParameters.toolchain.toolchainLibDir.pathString)"
settings["OTHER_CFLAGS"] = (
["$(inherited)"]
+ buildParameters.toolchain.extraFlags.cCompilerFlags
+ buildParameters.flags.cCompilerFlags.map { $0.spm_shellEscaped() }
).joined(separator: " ")
settings["OTHER_CPLUSPLUSFLAGS"] = (
["$(inherited)"]
+ buildParameters.toolchain.extraFlags.cxxCompilerFlags
+ buildParameters.flags.cxxCompilerFlags.map { $0.spm_shellEscaped() }
).joined(separator: " ")
settings["OTHER_SWIFT_FLAGS"] = (
["$(inherited)"]
+ buildParameters.toolchain.extraFlags.swiftCompilerFlags
+ buildParameters.flags.swiftCompilerFlags.map { $0.spm_shellEscaped() }
).joined(separator: " ")
settings["OTHER_LDFLAGS"] = (
["$(inherited)"]
+ buildParameters.flags.linkerFlags.map { $0.spm_shellEscaped() }
).joined(separator: " ")
// Optionally also set the list of architectures to build for.
if !buildParameters.archs.isEmpty {
settings["ARCHS"] = buildParameters.archs.joined(separator: " ")
}
// Generate the build parameters.
let params = XCBBuildParameters(
configurationName: buildParameters.configuration.xcbuildName,
overrides: .init(synthesized: .init(table: settings)),
activeRunDestination: runDestination
)
// Write out the parameters as a JSON file, and return the path.
let encoder = JSONEncoder.makeWithDefaults()
let data = try encoder.encode(params)
let file = try withTemporaryFile(deleteOnClose: false) { $0.path }
try self.fileSystem.writeFileContents(file, bytes: ByteString(data))
return file
}
public func cancel(deadline: DispatchTime) throws {
}
/// Returns a new instance of `XCBuildDelegate` for a build operation.
private func createBuildDelegate() -> XCBuildDelegate {
let progressAnimation: ProgressAnimationProtocol = self.logLevel.isVerbose
? VerboseProgressAnimation(stream: self.outputStream)
: MultiLinePercentProgressAnimation(stream: self.outputStream, header: "")
let delegate = XCBuildDelegate(
buildSystem: self,
outputStream: self.outputStream,
progressAnimation: progressAnimation,
logLevel: self.logLevel,
observabilityScope: self.observabilityScope
)
return delegate
}
private func getPIFBuilder() throws -> PIFBuilder {
try memoize(to: &pifBuilder) {
let graph = try getPackageGraph()
let pifBuilder = PIFBuilder(
graph: graph,
parameters: .init(buildParameters),
fileSystem: self.fileSystem,
observabilityScope: self.observabilityScope
)
return pifBuilder
}
}
/// Returns the package graph using the graph loader closure.
///
/// First access will cache the graph.
public func getPackageGraph() throws -> PackageGraph {
try memoize(to: &packageGraph) {
try packageGraphLoader()
}
}
}
struct XCBBuildParameters: Encodable {
struct RunDestination: Encodable {
var platform: String
var sdk: String
var sdkVariant: String?
var targetArchitecture: String
var supportedArchitectures: [String]
var disableOnlyActiveArch: Bool
}
struct XCBSettingsTable: Encodable {
var table: [String: String]
}
struct SettingsOverride: Encodable {
var synthesized: XCBSettingsTable? = nil
}
var configurationName: String
var overrides: SettingsOverride
var activeRunDestination: RunDestination
}
extension BuildConfiguration {
public var xcbuildName: String {
switch self {
case .debug: return "Debug"
case .release: return "Release"
}
}
}
extension PIFBuilderParameters {
public init(_ buildParameters: BuildParameters) {
self.init(
enableTestability: buildParameters.enableTestability,
shouldCreateDylibForDynamicProducts: buildParameters.shouldCreateDylibForDynamicProducts,
toolchainLibDir: (try? buildParameters.toolchain.toolchainLibDir) ?? .root
)
}
}
extension BuildSubset {
var pifTargetName: String {
switch self {
case .product(let name):
return PackagePIFProjectBuilder.targetName(for: name)
case .target(let name):
return name
case .allExcludingTests:
return PIFBuilder.allExcludingTestsTargetName
case .allIncludingTests:
return PIFBuilder.allIncludingTestsTargetName
}
}
}
extension Basics.Diagnostic.Severity {
var isVerbose: Bool {
return self <= .info
}
}
|
apache-2.0
|
27b7c986bbf1b4f736cd3e62e0e02e5d
| 36.284404 | 150 | 0.632054 | 5.067332 | false | false | false | false |
LetItPlay/iOSClient
|
blockchainapp/scenes/Feed/FeedViewController.swift
|
1
|
5808
|
//
// FeedViewController.swift
// blockchainapp
//
// Created by Ivan Gorbulin on 30/08/2017.
// Copyright © 2017 Ivan Gorbulin. All rights reserved.
//
import UIKit
enum FeedType {
case feed, popular
}
class FeedViewController: UIViewController, FeedViewProtocol {
var presenter: FeedPresenterProtocol!
fileprivate var source = [Track]()
var cellHeight: CGFloat = 343.0 + 24.0
var type: FeedType = .feed
let tableView: UITableView = UITableView()
let emptyLabel: UILabel = {
let label = UILabel()
label.font = AppFont.Title.big
label.textColor = AppColor.Title.dark
label.textAlignment = .center
label.numberOfLines = 0
label.text = "There are no tracks here.\nPlease subscribe on one\nof the channels in Channel tab".localized
return label
}()
convenience init(type: FeedType) {
self.init(nibName: nil, bundle: nil)
self.type = type
}
override func viewDidLoad() {
super.viewDidLoad()
navigationController?.navigationBar.prefersLargeTitles = false
self.navigationItem.largeTitleDisplayMode = .automatic
let refreshControl = UIRefreshControl()
refreshControl.addTarget(self, action: #selector(onRefreshAction(refreshControl:)), for: .valueChanged)
presenter = FeedPresenter(view: self, orderByListens: self.type == .popular)
// navigationController?.isNavigationBarHidden = true
view.backgroundColor = UIColor.vaWhite
self.view.addSubview(tableView)
tableView.snp.makeConstraints { (make) in
make.edges.equalToSuperview()
}
tableView.dataSource = self
tableView.delegate = self
tableView.refreshControl = refreshControl
tableView.separatorStyle = .none
tableView.contentInset = UIEdgeInsets(top: 0,
left: 0,
bottom: 72,
right: 0)
tableView.register(NewFeedTableViewCell.self, forCellReuseIdentifier: NewFeedTableViewCell.cellID)
tableView.backgroundColor = .white
tableView.backgroundView?.backgroundColor = .clear
tableView.sectionIndexBackgroundColor = .clear
refreshControl.beginRefreshing()
tableView.tableFooterView = UIView()
self.view.addSubview(emptyLabel)
emptyLabel.snp.makeConstraints { (make) in
make.center.equalTo(self.view)
}
emptyLabel.isHidden = self.type == .popular
presenter.getData { (tracks) in
}
self.tableView.refreshControl?.beginRefreshing()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.cellHeight = self.view.frame.width - 16 * 2 + 24 // side margins
}
@objc func onRefreshAction(refreshControl: UIRefreshControl) {
presenter.getData { (tracks) in
}
DispatchQueue.main.asyncAfter(deadline: .now() + 5, execute: {[weak self] in self?.tableView.refreshControl?.endRefreshing()})
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func display() {
// source = tracks
tableView.reloadData()
self.tableView.refreshControl?.endRefreshing()
if self.type == .feed {
self.emptyLabel.isHidden = presenter.tracks.count != 0
}
}
func reload(update: [Int], delete: [Int], insert: [Int]) {
// UIView.setAnimationsEnabled(false)
// tableView.beginUpdates()
// if self.view.window != nil {
// tableView.insertRows(at: insert.map({IndexPath(row: $0, section: 0)}), with: .none)
// tableView.deleteRows(at: delete.map({IndexPath(row: $0, section: 0)}), with: .none)
// tableView.reloadRows(at: update.map({IndexPath(row: $0, section: 0)}), with: .none)
// } else {
tableView.reloadData()
// }
// tableView.endUpdates()
self.tableView.refreshControl?.endRefreshing()
// UIView.setAnimationsEnabled(true)
if self.type == .feed {
self.emptyLabel.isHidden = presenter.tracks.count != 0
}
}
}
extension FeedViewController: UITableViewDelegate, UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.presenter.tracks.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: NewFeedTableViewCell.cellID)
return cell ?? UITableViewCell.init(frame: CGRect.zero)
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
self.presenter.play(index: indexPath.item)
}
func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
let cell = cell as? NewFeedTableViewCell
let track = self.presenter.tracks[indexPath.item]
cell?.track = track
cell?.set(isPlaying: indexPath.item == self.presenter.playingIndex)
cell?.onPlay = { [weak self] _ in
let index = indexPath.item
self?.presenter.play(index: index)
}
cell?.onLike = { [weak self] track in
let index = indexPath.item
self?.presenter.like(index: index)
}
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
let track = self.presenter.tracks[indexPath.item]
return NewFeedTableViewCell.height(text: track.name, width: tableView.frame.width)
// return self.cellHeight
}
func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
let track = self.presenter.tracks[indexPath.item]
return NewFeedTableViewCell.height(text: track.name, width: tableView.frame.width)
// return self.cellHeight
}
}
|
mit
|
17388a5ef87c353fec833b6302bd18b8
| 30.389189 | 128 | 0.689685 | 4.211022 | false | false | false | false |
carabina/ActionSwift3
|
ActionSwift3/media/Sound.swift
|
1
|
926
|
//
// Sound.swift
// ActionSwift
//
// Created by Craig on 6/08/2015.
// Copyright (c) 2015 Interactive Coconut. All rights reserved.
//
import SpriteKit
/**
Be sure to store either the sound or soundChannel in an instance variable, as the sound will be "garbage collected"
(or the Swift equivalent at least, *deinitialized* when there are no references to it)
*/
public class Sound: EventDispatcher {
private var name:String
private var soundChannel:SoundChannel = SoundChannel()
public init(name:String) {
self.name = name
}
public func load(name:String) {
self.name = name
}
///Returns a SoundChannel, which you can use to *stop* the Sound.
public func play(startTime:Number = 0, loops:int = 0)->SoundChannel {
soundChannel = SoundChannel()
soundChannel.play(self.name,startTime:startTime, loops:loops)
return soundChannel
}
}
|
mit
|
5e007bad8e03f2030ef7a734941b2c47
| 27.9375 | 115 | 0.677106 | 4.008658 | false | false | false | false |
CanyFrog/HCComponent
|
HCSource/HCTipsView.swift
|
1
|
9864
|
//
// HCTipsView.swift
// HCComponents
//
// Created by Magee Huang on 5/2/17.
// Copyright © 2017 Person Inc. All rights reserved.
//
// tips view
// The view struct is backview below of contentview, contentview contain in stackview
// you can add custom view in stackview and it will auto layout subviews
import UIKit
public enum HCTipsBackType {
case blur, plain
}
public enum HCTipsAnimationType {
case none
case fade
case zoom
}
open class HCTipsView: UIView {
/// background
private var backView: UIVisualEffectView?
/// set back view effect
public var backEffect: UIVisualEffect = UIBlurEffect(style: .dark) {
didSet { backView?.effect = backEffect }
}
/// wether display blur of plain
public var backType: HCTipsBackType = .plain
public var backAlpha: CGFloat = 0.5
public var showDuration: TimeInterval = 0.3
public var hideDuration: TimeInterval = 0.3
/// set custom view in stackview edge
public var stackInsert: UIEdgeInsets = UIEdgeInsetsMake(24, 24, 24, 24) { didSet { layoutStack() } }
/// position in center, can add custom view in contentview
public private(set) var contentView: UIScrollView = {
let content = UIScrollView()
content.translatesAutoresizingMaskIntoConstraints = false
content.backgroundColor = UIColor.white
content.layer.cornerRadius = 4
content.clipsToBounds = true
return content
}()
/// stack view
public private(set) var stack: UIStackView = {
let stack = UIStackView()
stack.translatesAutoresizingMaskIntoConstraints = false
stack.axis = .vertical
stack.alignment = .center
stack.distribution = .equalSpacing
stack.spacing = 12
return stack
}()
fileprivate var delayTimer: Timer?
// MARK: -- life cycle
public override init(frame: CGRect) {
super.init(frame: frame)
alpha = 0.0
layer.zPosition = 100
setUpBackView()
setUpContentView()
}
public convenience init(in view: UIView) {
self.init(frame: view.bounds)
view.addSubview(self)
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
deinit {
delayTimer?.invalidate()
}
// MARK: -- setUp
fileprivate func setUpBackView() {
switch backType {
case .blur:
guard backView == nil else {
backView?.alpha = backAlpha
return
}
backgroundColor = UIColor.clear
backView = UIVisualEffectView(frame: bounds)
backView?.effect = backEffect
insertSubview(backView!, at: 0)
case .plain:
backView?.removeFromSuperview()
backView = nil
let back = backgroundColor ?? UIColor.black
backgroundColor = back != UIColor.clear ? back.withAlphaComponent(backAlpha) : UIColor.black.withAlphaComponent(backAlpha)
}
}
private func setUpContentView() {
addSubview(contentView)
contentView.addSubview(stack)
NSLayoutConstraint.activate([
contentView.centerXAnchor.constraint(equalTo: centerXAnchor),
contentView.centerYAnchor.constraint(equalTo: centerYAnchor),
contentView.widthAnchor.constraint(lessThanOrEqualTo: widthAnchor, multiplier: 0.9),
contentView.heightAnchor.constraint(lessThanOrEqualTo: heightAnchor, multiplier: 0.8),
])
let top = contentView.topAnchor.constraint(greaterThanOrEqualTo: topAnchor, constant: 88)
top.priority = UILayoutPriorityDefaultLow
top.isActive = true
layoutStack()
}
private func layoutStack() {
NSLayoutConstraint.deactivate(contentView.constraints)
NSLayoutConstraint.activate([
stack.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: stackInsert.left),
stack.topAnchor.constraint(equalTo: contentView.topAnchor, constant: stackInsert.top),
stack.widthAnchor.constraint(equalTo: contentView.widthAnchor, constant: -(stackInsert.left + stackInsert.right)),
stack.heightAnchor.constraint(lessThanOrEqualTo: contentView.heightAnchor, constant: -(stackInsert.top + stackInsert.bottom))
])
}
open override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
// interpute response chain
}
}
// MARK: - add convenience func like stackview
extension HCTipsView {
open func removeArrangedSubview(_ view: UIView) {
stack.removeArrangedSubview(view)
}
open func addArrangedSubview(_ view: UIView) {
stack.addArrangedSubview(view)
}
open func insertArrangedSubview(_ view: UIView, at stackIndex: Int)
{
stack.insertArrangedSubview(view, at: stackIndex)
}
}
// MARK: -- show function
extension HCTipsView {
public func showTipsView(_ animationType: HCTipsAnimationType = .none, afterDismiss: TimeInterval? = nil, completion: EmptyExecute? = nil) {
animationTask(isShow: true, animationType: animationType, completion: completion)
if let _ = self.delayTimer { self.delayTimer?.invalidate() }
if let delay = afterDismiss {
delayTimer = Timer.after(delay, { [weak self] in
self?.animationTask(isShow: false, animationType: animationType, completion: nil)
self?.delayTimer?.invalidate()
})
}
}
public func dismissTipsView(_ animationType: HCTipsAnimationType = .none, afterDelay: TimeInterval? = nil, completion: EmptyExecute? = nil) {
if let _ = self.delayTimer { self.delayTimer?.invalidate() }
if let delay = afterDelay {
delayTimer = Timer.after(delay, { [weak self] in
self?.animationTask(isShow: false, animationType: animationType, completion: completion)
})
}
else {
animationTask(isShow: false, animationType: animationType, completion: completion)
}
}
private func animationTask(isShow: Bool , animationType: HCTipsAnimationType ,completion: EmptyExecute?) {
guard animationType != .none else {
if isShow == false {
self.removeAllSubviews()
self.removeFromSuperview()
return
}
else{
setUpBackView()
alpha = 1.0
return
}
}
if animationType == .zoom {
transform = isShow ? CGAffineTransform.init(scaleX: 1.2, y: 1.2) : CGAffineTransform.identity
}
let animations = {
self.setUpBackView()
self.alpha = isShow ? 1.0 : 0.0
switch animationType {
case .zoom:
self.transform = isShow ? CGAffineTransform.identity : CGAffineTransform.init(scaleX: 1.2, y: 1.2)
default:
break
}
}
UIView.animate(withDuration: isShow ? showDuration : hideDuration, delay: 0.0, options: [.beginFromCurrentState], animations: {
animations()
}) { _ in
if isShow == false {
self.removeAllSubviews()
self.removeFromSuperview()
}
if let com = completion { com() }
}
}
}
// MARK: -- Class function
extension HCTipsView {
open class func dismiss(in view: UIView, animation: HCTipsAnimationType = .none, delay: TimeInterval? = nil, completion: EmptyExecute? = nil) {
let views = view.subviews.reversed()
for v in views {
if v.isKind(of: self), let t = (v as? HCTipsView) {
t.dismissTipsView(animation, afterDelay: delay, completion: completion)
break
}
}
}
@discardableResult
open class func show(imageIn view: UIView, image: UIImage? = nil, detail: String? = nil, afterDelay: TimeInterval? = nil, animation: HCTipsAnimationType = .none, completion: EmptyExecute? = nil) -> HCTipsView? {
if image == nil && detail == nil { return nil }
let tips = HCTipsView(in: view)
if let i = image {
let imageView = UIImageView()
imageView.image = i
tips.addArrangedSubview(imageView)
}
if let s = detail {
let detailLabel = UILabel()
detailLabel.numberOfLines = 0
detailLabel.text = s
tips.addArrangedSubview(detailLabel)
}
tips.showTipsView(animation, afterDismiss: afterDelay, completion: completion)
return tips
}
@discardableResult
open class func show(indicatorIn view: UIView, detail: String? = nil, animation: HCTipsAnimationType = .none, afterDelay: TimeInterval? = nil, completion: EmptyExecute? = nil) -> HCTipsView? {
let tips = HCTipsView(in: view)
let indicator = UIActivityIndicatorView(frame: CGRect.init(origin: CGPoint.zero, size: CGSize(width: 24, height: 24)))
indicator.activityIndicatorViewStyle = .whiteLarge
indicator.color = UIColor.darkGray
indicator.startAnimating()
tips.addArrangedSubview(indicator)
if let s = detail, s.characters.count > 0 {
let detailLabel = UILabel()
detailLabel.numberOfLines = 0
detailLabel.text = s
detailLabel.textColor = UIColor.white
tips.addArrangedSubview(detailLabel)
}
tips.showTipsView(animation, afterDismiss: afterDelay, completion: completion)
return tips
}
}
|
mit
|
f1b618c12a661d529dca4d2020e03ee7
| 34.606498 | 215 | 0.615736 | 4.97127 | false | false | false | false |
manfengjun/KYMart
|
Section/Mine/View/KYWithDrawListTVCell.swift
|
1
|
1125
|
//
// KYWithDrawListTVCell.swift
// KYMart
//
// Created by JUN on 2017/6/29.
// Copyright © 2017年 JUN. All rights reserved.
//
import UIKit
class KYWithDrawListTVCell: UITableViewCell {
@IBOutlet weak var numberL: UILabel!
@IBOutlet weak var timeL: UILabel!
@IBOutlet weak var moneyL: UILabel!
@IBOutlet weak var statusL: UILabel!
var result:Result?{
didSet {
if let text = result?.id {
numberL.text = "\(text)"
}
if let text = result?.create_time {
timeL.text = "\(text)".timeStampToString()
}
if let text = result?.money {
moneyL.text = "\(text)"
}
if let text = result?.status_text {
statusL.text = "\(text)"
}
}
}
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
|
mit
|
d948a28d490cd80d17fc5c96ca4d9c11
| 23.933333 | 65 | 0.546346 | 4.365759 | false | false | false | false |
gellis12/SimpleGame
|
SimpleGame/GameView.swift
|
1
|
1557
|
//
// GameView.swift
// SimpleGame
//
// Created by Gordon Ellis on 2014-11-29.
// Copyright (c) 2014 Gordon Ellis. All rights reserved.
//
import SceneKit
class GameView: SCNView {
override func mouseDown(theEvent: NSEvent) {
/* Called when a mouse click occurs */
// check what nodes are clicked
let p = self.convertPoint(theEvent.locationInWindow, fromView: nil)
if let hitResults = self.hitTest(p, options: nil) {
// check that we clicked on at least one object
if hitResults.count > 0 {
// retrieved the first clicked object
let result: AnyObject = hitResults[0]
// get its material
let material = result.node!.geometry!.firstMaterial!
// highlight it
SCNTransaction.begin()
SCNTransaction.setAnimationDuration(0.5)
// on completion - unhighlight
SCNTransaction.setCompletionBlock() {
SCNTransaction.begin()
SCNTransaction.setAnimationDuration(0.5)
material.emission.contents = NSColor.blackColor()
SCNTransaction.commit()
}
material.emission.contents = NSColor.redColor()
SCNTransaction.commit()
}
}
super.mouseDown(theEvent)
}
}
|
apache-2.0
|
338b735da5835c2e052b1bf310519e83
| 30.14 | 75 | 0.510597 | 5.853383 | false | false | false | false |
adachic/ObjectMapper
|
ObjectMapperTests/CustomTransformTests.swift
|
9
|
5158
|
//
// CustomTransformTests.swift
// ObjectMapper
//
// Created by Tristan Himmelman on 2015-03-09.
// Copyright (c) 2015 hearst. All rights reserved.
//
import Foundation
import XCTest
import ObjectMapper
import Nimble
class CustomTransformTests: XCTestCase {
let mapper = Mapper<Transforms>()
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 testDateTransform() {
var transforms = Transforms()
transforms.date = NSDate(timeIntervalSince1970: 946684800)
transforms.dateOpt = NSDate(timeIntervalSince1970: 946684912)
let JSON = mapper.toJSON(transforms)
let parsedTransforms = mapper.map(JSON)
expect(parsedTransforms).notTo(beNil())
expect(parsedTransforms?.date).to(equal(transforms.date))
expect(parsedTransforms?.dateOpt).to(equal(transforms.dateOpt))
}
func testISO8601DateTransform() {
var transforms = Transforms()
transforms.ISO8601Date = NSDate(timeIntervalSince1970: 1398956159)
transforms.ISO8601DateOpt = NSDate(timeIntervalSince1970: 1398956159)
let JSON = mapper.toJSON(transforms)
let parsedTransforms = mapper.map(JSON)
expect(parsedTransforms).notTo(beNil())
expect(parsedTransforms?.ISO8601Date).to(equal(transforms.ISO8601Date))
expect(parsedTransforms?.ISO8601DateOpt).to(equal(transforms.ISO8601DateOpt))
}
func testISO8601DateTransformWithInvalidInput() {
var JSON: [String: AnyObject] = ["ISO8601Date": ""]
let transforms = mapper.map(JSON)
expect(transforms?.ISO8601DateOpt).to(beNil())
JSON["ISO8601Date"] = "incorrect format"
let transforms2 = mapper.map(JSON)
expect(transforms2?.ISO8601DateOpt).to(beNil())
}
func testCustomFormatDateTransform(){
let dateString = "2015-03-03T02:36:44"
var JSON: [String: AnyObject] = ["customFormateDate": dateString]
let transform: Transforms! = mapper.map(JSON)
expect(transform).notTo(beNil())
let JSONOutput = mapper.toJSON(transform)
expect(JSONOutput["customFormateDate"] as? String).to(equal(dateString))
}
func testIntToStringTransformOf() {
let intValue = 12345
var JSON: [String: AnyObject] = ["intWithString": "\(intValue)"]
let transforms = mapper.map(JSON)
expect(transforms?.intWithString).to(equal(intValue))
}
func testInt64MaxValue() {
let transforms = Transforms()
transforms.int64Value = INT64_MAX
let JSON = mapper.toJSON(transforms)
let parsedTransforms = mapper.map(JSON)
expect(parsedTransforms).notTo(beNil())
expect(parsedTransforms?.int64Value).to(equal(transforms.int64Value))
}
func testURLTranform() {
let transforms = Transforms()
transforms.URL = NSURL(string: "http://google.com/image/1234")!
transforms.URLOpt = NSURL(string: "http://google.com/image/1234")
let JSON = mapper.toJSON(transforms)
let parsedTransforms = mapper.map(JSON)
expect(parsedTransforms).notTo(beNil())
expect(parsedTransforms?.URL).to(equal(transforms.URL))
expect(parsedTransforms?.URLOpt).to(equal(transforms.URLOpt))
}
func testEnumTransform() {
var JSON: [String: AnyObject] = ["firstImageType" : "cover", "secondImageType" : "thumbnail"]
let transforms = mapper.map(JSON)
let imageType = Transforms.ImageType.self
expect(transforms?.firstImageType).to(equal(imageType.Cover))
expect(transforms?.secondImageType).to(equal(imageType.Thumbnail))
}
}
class Transforms: Mappable {
internal enum ImageType: String {
case Cover = "cover"
case Thumbnail = "thumbnail"
}
var date = NSDate()
var dateOpt: NSDate?
var ISO8601Date: NSDate = NSDate()
var ISO8601DateOpt: NSDate?
var customFormatDate = NSDate()
var customFormatDateOpt: NSDate?
var URL = NSURL()
var URLOpt: NSURL?
var intWithString: Int = 0
var int64Value: Int64 = 0
var firstImageType: ImageType?
var secondImageType: ImageType?
static func newInstance(map: Map) -> Mappable? {
return Transforms()
}
func mapping(map: Map) {
date <- (map["date"], DateTransform())
dateOpt <- (map["dateOpt"], DateTransform())
ISO8601Date <- (map["ISO8601Date"], ISO8601DateTransform())
ISO8601DateOpt <- (map["ISO8601DateOpt"], ISO8601DateTransform())
customFormatDate <- (map["customFormateDate"], CustomDateFormatTransform(formatString: "yyyy-MM-dd'T'HH:mm:ss"))
customFormatDateOpt <- (map["customFormateDateOpt"], CustomDateFormatTransform(formatString: "yyyy-MM-dd'T'HH:mm:ss"))
URL <- (map["URL"], URLTransform())
URLOpt <- (map["URLOpt"], URLTransform())
intWithString <- (map["intWithString"], TransformOf<Int, String>(fromJSON: { $0?.toInt() }, toJSON: { $0.map { String($0) } }))
int64Value <- (map["int64Value"], TransformOf<Int64, NSNumber>(fromJSON: { $0?.longLongValue }, toJSON: { $0.map { NSNumber(longLong: $0) } }))
firstImageType <- (map["firstImageType"], EnumTransform<ImageType>())
secondImageType <- (map["secondImageType"], EnumTransform<ImageType>())
}
}
|
mit
|
8196d87b01d8cd07a2f15dd2cff81ba5
| 29.702381 | 147 | 0.718108 | 3.609517 | false | true | false | false |
cklab/ForecastIO
|
Source/FIORequest.swift
|
1
|
822
|
//
// FIORequest.swift
// ForecastIO
//
// Created by CK Guven on 10/28/15.
//
//
import Foundation
public class FIORequest {
private var lat: Double
private var lon: Double
private var date: NSDate?
init(lat: Double, lon: Double) {
self.lat = lat
self.lon = lon
}
func withCoordinates(lat: Double, lon: Double) -> Self {
self.lat = lat
self.lon = lon
return self
}
func withDate(date: NSDate) -> Self {
self.date = date
return self
}
func build(api: ForecastIO) -> String {
var url = "\(ForecastIO.ApiServer)/\(api.ApiKey)/\(lat),\(lon)"
if let date = date {
url += "," + String(Int(date.timeIntervalSince1970))
}
return url
}
}
|
mit
|
6a866b57e32cfd9628669cf39bf04eae
| 18.571429 | 71 | 0.525547 | 3.990291 | false | false | false | false |
OpenStack-mobile/OAuth2-Swift
|
Sources/OAuth2/AuthorizationResponse.swift
|
1
|
2941
|
//
// AuthorizationResponse.swift
// OAuth2
//
// Created by Alsey Coleman Miller on 12/16/16.
// Copyright © 2016 OpenStack. All rights reserved.
//
import Foundation
// MARK: - Success Response
public protocol AuthorizationResponse: Response {
/// Required, if present in authorization request.
/// The same value as sent in the `state` parameter in the request.
var state: String? { get }
}
// MARK: - Error Response
/// Authorization Error Response as defined in
/// [4.1.2.1. (Authorization Code Grant) Error Response](https://tools.ietf.org/html/rfc6749#section-4.1.2.1) and
/// [4.2.2.1. (Implicit Grant) Error Response](https://tools.ietf.org/html/rfc6749#section-4.2.2.1)
///
/// For example, the authorization server redirects the user-agent by
/// sending the following HTTP response:
///
/// ```
/// HTTP/1.1 302 Found
/// Location: https://client.example.com/cb?error=access_denied&state=xyz
/// ```
public protocol AuthorizationErrorResponse: ErrorResponse {
/// Error code
var code: AuthorizationErrorCode { get }
/// Required, if present in authorization request.
/// The same value as sent in the `state` parameter in the request.
var state: String? { get }
}
public enum AuthorizationErrorResponseParameter: String {
/// Required, if present in authorization request. The same value as sent in the state parameter in the request.
case state
}
public enum AuthorizationErrorCode: String {
/// The request is missing a required parameter,
/// includes an invalid parameter value,
/// includes a parameter more than once,
/// or is otherwise malformed.
case invalidRequest = "invalid_request"
/// The client is not authorized to request an access token using this method.
case unauthorizedClient = "unauthorized_client"
/// The resource owner or authorization server denied the request.
case accessDenied = "access_denied"
/// The authorization server does not support obtaining an access token using this method.
case unsupportedResponseType = "unsupported_response_type"
/// The requested scope is invalid, unknown, or malformed.
case invalidScope = "invalid_scope"
/// The authorization server encountered an unexpected
/// condition that prevented it from fulfilling the request.
///
/// - Note: This error code is needed because a 500 Internal Server
/// Error HTTP status code cannot be returned to the client via an HTTP redirect.
case serverError = "server_error"
/// The authorization server is currently unable to handle
/// the request due to a temporary overloading or maintenance of the server.
///
/// - Note: This error code is needed because a 503 Service Unavailable HTTP status code
/// cannot be returned to the client via an HTTP redirect.
case temporarilyUnavailable = "temporarily_unavailable"
}
|
mit
|
65031919f93798e397dd942b61a18ed4
| 34.853659 | 116 | 0.701361 | 4.523077 | false | false | false | false |
tbointeractive/TBODeveloperOverlay
|
TBODeveloperOverlay/TBODeveloperOverlay/UserDefaultsTableViewController.swift
|
1
|
4582
|
//
// UserDefaultsTableViewController.swift
// TBODeveloperOverlay
//
// Created by Cornelius Horstmann on 28.07.17.
// Copyright © 2017 TBO Interactive GmbH & CO KG. All rights reserved.
//
import Foundation
open class UserDefaultsTableViewController: TableViewController {
static let defaultUserDefaultsKeysBlacklist: [String] = ["AppleLanguages", "AppleLocale", "AppleKeyboards", "AppleITunesStoreItemKinds", "AddingEmojiKeybordHandled", "ApplePasscodeKeyboards", "NSInterfaceStyle", "PKKeychainVersionKey", "AppleKeyboardsExpanded", "NSLanguages", "AppleLanguagesDidMigrate"]
let canEdit: Bool
let inspectorCollection: InspectorCollection
let userDefaults: UserDefaults
let keys: [String]
public convenience init(style: UITableView.Style, userDefaults: UserDefaults, canEdit: Bool = false, inspectorCollection: InspectorCollection? = nil, userDefaultsKeysBlacklist: [String]? = nil, userDefaultsKeysWhitelist: [String]? = nil) {
self.init(style: style, userDefaults: userDefaults, canEdit: canEdit, inspectorCollection: inspectorCollection) { key in
if let whitelist = userDefaultsKeysWhitelist {
return whitelist.contains(key)
}
let blacklist = userDefaultsKeysBlacklist ?? UserDefaultsTableViewController.defaultUserDefaultsKeysBlacklist
return !blacklist.contains(key)
}
}
public convenience init(style: UITableView.Style, userDefaults: UserDefaults, canEdit: Bool = false, inspectorCollection: InspectorCollection? = nil, userDefaultsKeyFilter: (String)->(Bool)) {
let keys = userDefaults.dictionaryRepresentation().keys.filter(userDefaultsKeyFilter)
self.init(style: style, userDefaults: userDefaults, canEdit: canEdit, inspectorCollection: inspectorCollection, keys: Array(keys))
}
public init(style: UITableView.Style, userDefaults: UserDefaults, canEdit: Bool = false, inspectorCollection: InspectorCollection? = nil, keys: [String]) {
self.userDefaults = userDefaults
self.keys = keys.sorted { $0.lowercased() < $1.lowercased() }
self.canEdit = canEdit
self.inspectorCollection = inspectorCollection ?? InspectorCollection.defaultCollection
super.init(style: style, sections: [])
}
required public init?(coder aDecoder: NSCoder) {
self.canEdit = false
self.keys = []
self.inspectorCollection = InspectorCollection.defaultCollection
self.userDefaults = UserDefaults.standard
super.init(coder: aDecoder)
}
open override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
}
open override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
let section = Section.from(userDefaults, whitelist: keys)
self.dataSource = Datasource(sections: [section])
}
open func canEditItem(forKey key: String) -> Bool {
return canEdit
}
@discardableResult open override func handleDidSelect(_ item: Section.Item, forItemAt indexPath: IndexPath) -> Bool {
guard !super.handleDidSelect(item, forItemAt: indexPath) else { return true }
switch item {
case .segue(let key, _, let identifier, _):
guard let identifier = identifier,
let value = userDefaults.object(forKey: identifier) else { return false }
let canEdit = canEditItem(forKey: identifier)
let viewController = inspector(key: identifier, value: value)
if canEdit {
viewController.didEdit = { [weak self] newValue in
self?.userDefaults.set(newValue, forKey: key)
}
}
viewController.title = key
navigationController?.pushViewController(viewController, animated: true)
return true
default: return false
}
}
internal func inspector(key: String, value: Any) -> InspectorViewController {
return inspectorCollection.inspector(for: value)
}
}
extension Section {
static func from(_ userDefaults: UserDefaults, whitelist: [String]) -> Section {
var items: [Item] = []
for key in whitelist {
if let value = UserDefaults.standard.object(forKey: key) {
let item = Item.segue(title: key, detail: "\(value)", identifier: key, viewController: nil)
items.append(item)
}
}
return Section(items: items, title: "UserDefaults")
}
}
|
mit
|
9456d9b98551952ed52aea0718b29e6b
| 43.911765 | 308 | 0.671251 | 5.023026 | false | false | false | false |
OneBusAway/onebusaway-iphone
|
Carthage/Checkouts/IGListKit/Examples/Examples-iOS/IGListKitExamples/SectionControllers/DemoSectionController.swift
|
2
|
2800
|
/**
Copyright (c) Facebook, Inc. and its affiliates.
The examples provided by Facebook are for non-commercial testing and evaluation
purposes only. Facebook reserves all rights not expressly granted.
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
FACEBOOK 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 IGListKit
import UIKit
final class DemoItem: NSObject {
let name: String
let controllerClass: UIViewController.Type
let controllerIdentifier: String?
init(
name: String,
controllerClass: UIViewController.Type,
controllerIdentifier: String? = nil
) {
self.name = name
self.controllerClass = controllerClass
self.controllerIdentifier = controllerIdentifier
}
}
extension DemoItem: ListDiffable {
func diffIdentifier() -> NSObjectProtocol {
return name as NSObjectProtocol
}
func isEqual(toDiffableObject object: ListDiffable?) -> Bool {
if self === object { return true }
guard let object = object as? DemoItem else { return false }
return controllerClass == object.controllerClass && controllerIdentifier == object.controllerIdentifier
}
}
final class DemoSectionController: ListSectionController {
private var object: DemoItem?
override func sizeForItem(at index: Int) -> CGSize {
return CGSize(width: collectionContext!.containerSize.width, height: 55)
}
override func cellForItem(at index: Int) -> UICollectionViewCell {
guard let cell = collectionContext?.dequeueReusableCell(of: LabelCell.self, for: self, at: index) as? LabelCell else {
fatalError()
}
cell.text = object?.name
return cell
}
override func didUpdate(to object: Any) {
self.object = object as? DemoItem
}
override func didSelectItem(at index: Int) {
if let identifier = object?.controllerIdentifier {
let storyboard = UIStoryboard(name: "Demo", bundle: nil)
let controller = storyboard.instantiateViewController(withIdentifier: identifier)
controller.title = object?.name
viewController?.navigationController?.pushViewController(controller, animated: true)
} else if let controller = object?.controllerClass.init() {
controller.title = object?.name
viewController?.navigationController?.pushViewController(controller, animated: true)
}
}
}
|
apache-2.0
|
032bb27e0d47b723491314f2548364a5
| 33.146341 | 126 | 0.698571 | 5.175601 | false | false | false | false |
ghotjunwoo/Tiat
|
publicAlbumViewController.swift
|
1
|
3221
|
//
// publicAlbumViewController.swift
// Tiat
//
// Created by 이종승 on 2016. 8. 10..
// Copyright © 2016년 JW. All rights reserved.
//
import UIKit
import Firebase
import MobileCoreServices
class publicAlbumViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout {
@IBOutlet var collectionView: UICollectionView!
let imagePicker = UIImagePickerController()
let storageRef = FIRStorage.storage().reference(forURL: "gs://tiat-ea6fd.appspot.com")
var values = 1
var imageArray:[UIImage] = [UIImage(named: "second")!]
var metadata = FIRStorageMetadata()
override func viewDidLoad() {
super.viewDidLoad()
let albumRef = FIRDatabase.database().reference().child("albumnum")
albumRef.observe(.value) { (snap: FIRDataSnapshot) in
print(snap.value)
self.values = snap.value as! Int
}
print(values)
let albumImageRef = FIRStorage.storage().reference(forURL: "gs://tiat-ea6fd.appspot.com")
.child("albumNum")
for num in 1...values {
albumImageRef.child("\(num)").data(withMaxSize: Int64.max, completion: {(data, error) in
if error == nil {
self.imageArray.append(UIImage(data: data!)!)
self.collectionView.reloadData()
} else {
print(error?.localizedDescription)
}
})
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return values
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "publicAlbumCell", for: indexPath) as! AlbumCollectionViewCell
cell.imageView?.image = self.imageArray[(indexPath as NSIndexPath).row]
return cell
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
let albumImageRef = FIRStorage.storage().reference(forURL: "gs://tiat-ea6fd.appspot.com")
.child("albumNum")
self.dismiss(animated: true, completion: nil)
let image = info[UIImagePickerControllerOriginalImage] as! UIImage
let newImage = UIImageJPEGRepresentation(image, 3.0)
self.metadata.contentType = "image/jpeg"
print("\(values + 1)")
albumImageRef.child("\(values + 1)").put(newImage!, metadata: self.metadata){metadata, error in
if error == nil {self.collectionView.reloadData()}
else {print(error?.localizedDescription)}
}
}
@IBAction func plusButtonTapped(_ sender: AnyObject) {
imagePicker.sourceType = UIImagePickerControllerSourceType.photoLibrary
imagePicker.mediaTypes = [kUTTypeImage as String]
self.present(imagePicker, animated: true, completion: nil)
}
}
|
gpl-3.0
|
75910a61b4296c58f8466ce08fa5bbbe
| 35.5 | 141 | 0.646638 | 5.172303 | false | false | false | false |
oronbz/RWPickFlavor
|
RWPickFlavor/PickFlavorViewController.swift
|
1
|
2436
|
//
// ViewController.swift
// IceCreamShop
//
// Created by Joshua Greene on 2/8/15.
// Copyright (c) 2015 Razeware, LLC. All rights reserved.
//
import UIKit
import Alamofire
import MBProgressHUD
import BetterBaseClasses
public class PickFlavorViewController: BaseViewController, UICollectionViewDelegate {
// MARK: Instance Variables
var flavors: [Flavor] = [] {
didSet {
pickFlavorDataSource?.flavors = flavors
}
}
private var pickFlavorDataSource: PickFlavorDataSource? {
return collectionView?.dataSource as! PickFlavorDataSource?
}
private let flavorFactory = FlavorFactory()
// MARK: Outlets
@IBOutlet var contentView: UIView!
@IBOutlet var collectionView: UICollectionView!
@IBOutlet var iceCreamView: IceCreamView!
@IBOutlet var label: UILabel!
// MARK: View Lifecycle
public override func viewDidLoad() {
super.viewDidLoad()
loadFlavors()
}
private func loadFlavors() {
let urlString = "http://www.raywenderlich.com/downloads/Flavors.plist"
showLoadingHUD()
Alamofire.request(.GET, urlString, encoding: .PropertyList(.XMLFormat_v1_0, 0)).responsePropertyList {
request, response, array, error in
self.hideLoadingHUD()
if let error = error {
println("Error: \(error)")
} else if let array = array as? [[String: String]] {
if array.isEmpty {
println("No flavors were found!")
} else {
self.flavors = self.flavorFactory.flavorsFromDictionaryArray(array)
self.collectionView.reloadData()
self.selectFirstFlavor()
}
}
}
}
private func showLoadingHUD() {
let hud = MBProgressHUD.showHUDAddedTo(contentView, animated: true)
hud.labelText = "Loading..."
}
private func hideLoadingHUD() {
MBProgressHUD.hideAllHUDsForView(contentView, animated: true)
}
private func selectFirstFlavor() {
if let flavor = flavors.first {
updateWithFlavor(flavor)
}
}
// MARK: UICollectionViewDelegate
public func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
let flavor = flavors[indexPath.row]
updateWithFlavor(flavor)
}
// MARK: Internal
private func updateWithFlavor(flavor: Flavor) {
iceCreamView.updateWithFlavor(flavor)
label.text = flavor.name
}
}
|
mit
|
0b3dbc43599f8d7ce61f21517ce26ee4
| 23.36 | 113 | 0.672003 | 4.804734 | false | false | false | false |
DannyVancura/SwifTrix
|
SwifTrix/User Interface/FormFill/STFormFillDataType.swift
|
1
|
4040
|
//
// STFormFillDataType.swift
// SwifTrix
//
// The MIT License (MIT)
//
// Copyright © 2015 Daniel Vancura
//
// 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
/**
STFormFillDataTypes provide some information about common data types in forms. These data types provide requirements to text that the user enters while filling a form.
You can provide your own data types by using .UnformattedText (which does not provide any requirements on its own) as a data type and provide additional requirements.
*/
public enum STFormFillDataType {
/**
Data of type unformatted text, i.e. text that does not conform to any specific syntax rules like for example E-Mails do.
*/
case UnformattedText
/**
Data of type E-Mail, i.e. something formatted like [email protected]
*/
case EMail
/**
Data of type date (with day, month and year, without time)
*/
case Date
/**
Data of type time (a date without a specific day, month and year, only time)
*/
case Time
/**
An array of value checks that can be applied to a string and check if this string is in the correct format for the data type in question. If not, it provides an error text that can be shown to the user to describe what is wrong with the provided string value.
*/
var requirements: [(valueCheck: String -> Bool, errorText: String)?] {
get {
switch self {
case .UnformattedText:
return []
case .Time:
let timeFormatter = NSDateFormatter()
timeFormatter.locale = NSLocale.autoupdatingCurrentLocale()
timeFormatter.dateStyle = .NoStyle
timeFormatter.timeStyle = .ShortStyle
return [({timeFormatter.dateFromString($0) != nil}, NSLocalizedString("The entered value is not a valid time.", comment: "Error text displayed to a user inside an STFormFillCell when he or she was supposed to enter a time."))]
case .EMail:
let emailRegEx = "^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\\.[a-zA-Z0-9-.]+$"
let eMailCheck: String -> Bool = { return NSPredicate(format: "SELF MATCHES %@", emailRegEx).evaluateWithObject($0) }
return [(eMailCheck, NSLocalizedString("This is not a valid E-Mail address", comment: "Error text displayed to a user inside an STFormFillCell when he or she was supposed to enter a valid E-Mail address"))]
case .Date:
let dateFormatter = NSDateFormatter()
dateFormatter.locale = NSLocale.autoupdatingCurrentLocale()
dateFormatter.dateStyle = .ShortStyle
dateFormatter.timeStyle = .NoStyle
return [({dateFormatter.dateFromString($0) != nil}, NSLocalizedString("The entered value is not a valid date.", comment: "Error text displayed to a user inside an STFormFillCell when he or she was supposed to enter a date."))]
}
}
}
}
|
mit
|
b57347175b1db26981414e92c87e853b
| 48.268293 | 264 | 0.678138 | 4.746181 | false | false | false | false |
gorhack/Borrowed
|
ListController.swift
|
1
|
7108
|
//
// ListController.swift
// Borrowed
//
// Created by Kyle Gorak on 1/1/15.
// Copyright (c) 2015 Kyle Gorak. All rights reserved.
//
import UIKit
import CoreData
class ListController: UITableViewController {
var itemList = Array<AnyObject>()
// Set context as the apps Managed Object Context
lazy var managedObjectContext : NSManagedObjectContext? = {
let appDelegate = UIApplication.sharedApplication().delegate as AppDelegate
if let managedObjectContext = appDelegate.managedObjectContext {
return managedObjectContext
}
else {
return nil
}
}()
override func viewDidLoad() {
super.viewDidLoad()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem()
// Add both edit and settings to navigation bar
self.navigationItem.leftItemsSupplementBackButton = true;
var editButton = UIBarButtonItem(barButtonSystemItem: .Edit, target: self, action: nil);
var settingsButton = UIBarButtonItem(title: "Settings", style: .Plain, target: self, action: nil);
self.navigationItem.leftBarButtonItems = [editButton, settingsButton];
}
override func viewDidAppear(animated: Bool) {
// set up fetch request
let context = managedObjectContext!
let freq = NSFetchRequest(entityName: "ItemRecord")
var error: NSError? = nil
itemList = context.executeFetchRequest(freq, error: &error)!
if error != nil {
println(error)
}
tableView.reloadData()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Potentially incomplete method implementation.
// Return the number of sections.
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete method implementation.
// Return the number of rows in the section.
return itemList.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
// Configure the cell...
// cell identifier
let cellID: NSString = "ItemCell"
var cell: UITableViewCell = tableView.dequeueReusableCellWithIdentifier(cellID) as UITableViewCell
// set data source
var data: NSManagedObject = itemList[indexPath.row] as NSManagedObject
// set cell labels
cell.textLabel?.text = (data.valueForKeyPath("itemName") as String)
cell.detailTextLabel?.text = (data.valueForKeyPath("desc") as String)
return cell
}
// Override to support conditional editing of the table view.
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return NO if you do not want the specified item to be editable.
return true
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
// Rename navigation controller's back button to cancel
//self.navigationItem.title = "Cancel"
}
// Override to support editing the table view.
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
let context = managedObjectContext!
if editingStyle == .Delete {
// Delete the row from the listView and data source
context.deleteObject(itemList[indexPath.row] as NSManagedObject)
itemList.removeAtIndex(indexPath.row)
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Fade)
var error: NSError? = nil
// Commit changes to data object
if !context.save(&error) {
abort()
}
//self.tableView.reloadData()
} /*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
} */
}
@IBOutlet weak var editTable: UIBarButtonItem!
override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
return true
}
// Override to support rearranging the table view.
override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {
if (editTable != nil) {
let item: AnyObject = itemList[fromIndexPath.row]
itemList.removeAtIndex(fromIndexPath.row)
itemList.insert(item, atIndex: toIndexPath.row)
}
}
/*
// Override to support conditional rearranging of the table view.
override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return NO if you do not want the item to be re-orderable.
return true
}
*/
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if (segue.identifier? == "itemDetailSegue") {
var selectedItem: NSManagedObject = itemList[self.tableView.indexPathForSelectedRow()!.row] as NSManagedObject
let detailController = segue.destinationViewController as NewItemView
// Pass values to the next view controller
detailController.selectedItemName = selectedItem.valueForKey("itemName") as String
detailController.selectedBorrowerName = selectedItem.valueForKey("borrowerName") as String
detailController.selectedDescription = selectedItem.valueForKey("desc") as String
detailController.selectedPicker = selectedItem.valueForKey("itemTypeID") as Int
detailController.selectedDate = selectedItem.valueForKey("dueDate") as NSDate
detailController.existingItem = selectedItem as NSManagedObject
// Rename view controller back button to Cancel
self.navigationItem.backBarButtonItem = UIBarButtonItem(title: "Cancel", style: UIBarButtonItemStyle.Plain, target: nil, action: nil)
}
}
}
|
gpl-2.0
|
eb58531ad13178b47dcbd3d78175172d
| 37.421622 | 157 | 0.651941 | 5.938179 | false | false | false | false |
mitchtreece/Bulletin
|
Example/Pods/Espresso/Espresso/Classes/Core/UIKit/UIBlurView.swift
|
1
|
1540
|
//
// UIBlurView.swift
// Espresso
//
// Created by Mitch Treece on 7/2/18.
//
import UIKit
import SnapKit
/**
Blurred `UIView` subclass that responds to tint color changes.
*/
open class UIBlurView: UIView {
private var blurView: UIVisualEffectView!
private var blurStyle = UIBlurEffect.Style.light
/**
A `UIView` object that can have a visual effect view added to it.
Add subviews to the `contentView` and not to `UIBlurView` directly.
*/
public var contentView: UIView {
return blurView.contentView
}
open override func tintColorDidChange() {
self.backgroundColor = self.tintColor
}
/**
Initializes a new `UIBlurView` with a specified blur style.
- Parameter frame: The view's frame.
- Parameter style: The blur style.
*/
public init(frame: CGRect, style: UIBlurEffect.Style) {
super.init(frame: frame)
self.blurStyle = style
setup()
}
public override init(frame: CGRect) {
super.init(frame: frame)
setup()
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setup()
}
private func setup() {
self.clipsToBounds = true
blurView = UIVisualEffectView(effect: UIBlurEffect(style: blurStyle))
self.addSubview(blurView)
blurView.snp.makeConstraints { (make) in
make.edges.equalTo(0)
}
}
}
|
mit
|
b02a57cba217d260fbb74058193d807c
| 21.647059 | 77 | 0.594805 | 4.638554 | false | false | false | false |
mathiasquintero/Sweeft
|
Sources/Sweeft/PriorityQueue.swift
|
3
|
2659
|
//
// PriorityQueue.swift
// Pods
//
// Created by Mathias Quintero on 2/22/17.
//
//
import Foundation
public class PriorityQueue<T: Hashable, P: Comparable> {
var itemPositions: [T:Int] = .empty
var items: [(item: T, priority: P)] = .empty
public var count: Int {
return items.count
}
public var isEmpty: Bool {
return count < 1
}
private func swap(_ a: Int, _ b: Int) {
items[a] <=> items[b]
itemPositions[items[a].item] = a
itemPositions[items[b].item] = b
}
private func childrenOfItem(at index: Int) -> [(element: (item: T, priority: P), index: Int)] {
let indexes = [2 * index + 1, 2 * index + 2]
return self.items.withIndex | indexes
}
private func siftUp(at index: Int) {
guard index > 0 else {
return
}
let parentIndex = (index - 1)/2
let parent = items[parentIndex]
let current = items[index]
if parent.priority > current.priority {
self.swap(parentIndex, index)
siftUp(at: parentIndex)
}
}
private func siftDown(at index: Int) {
let children = childrenOfItem(at: index)
guard let child = children.argmin({ $0.element.priority }) else {
return
}
if child.element.priority < items[index].priority {
self.swap(child.index, index)
siftDown(at: child.index)
}
}
public func priority(for item: T) -> P? {
guard let position = itemPositions[item] else {
return nil
}
return items[position].priority
}
public func update(_ item: T, with priority: P) {
guard let position = itemPositions[item] else {
return
}
items[position].priority = priority
siftUp(at: position)
if let position = itemPositions[item] {
siftUp(at: position)
}
}
public func add(_ item: T, with priority: P) {
items.append((item, priority))
itemPositions[item] = items.lastIndex
siftUp(at: items.lastIndex)
}
public func popWithPriority() -> (T, P)? {
if count > 1 {
swap(0, items.lastIndex)
let item = items.removeLast()
itemPositions[item.item] = nil
siftDown(at: 0)
return item
} else {
itemPositions = .empty
let item = items.first
items = .empty
return item
}
}
public func pop() -> T? {
return popWithPriority()?.0
}
}
|
mit
|
7cf882d69d5fbe92e0882836be5a1dbc
| 25.068627 | 99 | 0.529522 | 4.059542 | false | false | false | false |
jerrypupu111/LearnDrawingToolSet
|
SwiftGL-Demo/Source/colorPicker/ColorPickerController.swift
|
1
|
1900
|
//
// ColorPickerController.swift
//
// Created by Matthias Schlemm on 24/03/15.
// Copyright (c) 2015 Sixpolys. All rights reserved.
//
import UIKit
public class ColorPickerController: NSObject {
public var onColorChange:((color:UIColor, finished:Bool)->Void)? = nil
// Hue Picker
public var huePicker:HuePicker
// Color Well
public var colorWell:ColorWell {
didSet {
huePicker.setHueFromColor(colorWell.color)
colorPicker.color = colorWell.color
}
}
// Color Picker
public var colorPicker:ColorPicker
public var color:UIColor? {
set(value) {
colorPicker.color = value!
colorWell.color = value!
huePicker.setHueFromColor(value!)
}
get {
return colorPicker.color
}
}
public init(svPickerView:ColorPicker, huePickerView:HuePicker, colorWell:ColorWell) {
self.huePicker = huePickerView
self.colorPicker = svPickerView
self.colorWell = colorWell
self.colorWell.color = colorPicker.color
self.huePicker.setHueFromColor(colorPicker.color)
super.init()
self.colorPicker.onColorChange = {(color, finished) -> Void in
self.huePicker.setHueFromColor(color)
self.colorWell.previewColor = (finished) ? nil : color
if(finished) {self.colorWell.color = color}
self.onColorChange?(color: color, finished: finished)
}
self.huePicker.onHueChange = {(hue, finished) -> Void in
self.colorPicker.h = CGFloat(hue)
let color = self.colorPicker.color
self.colorWell.previewColor = (finished) ? nil : color
if(finished) {self.colorWell.color = color}
self.onColorChange?(color: color, finished: finished)
}
}
}
|
mit
|
635ae1a03b20fb865b782920ba67891b
| 28.6875 | 89 | 0.608421 | 4.37788 | false | false | false | false |
tsuchikazu/iTunesSwift
|
ITunesSwiftDemo/ITunesSwiftDemo/json.swift
|
1
|
11547
|
//
// json.swift
// json
//
// Created by Dan Kogai on 7/15/14.
// Copyright (c) 2014 Dan Kogai. All rights reserved.
//
import Foundation
/// init
public class JSON {
private let _value:AnyObject
/// pass the object that was returned from
/// NSJSONSerialization
public init(_ obj:AnyObject) { self._value = obj }
/// pass the JSON object for another instance
public init(_ json:JSON){ self._value = json._value }
}
/// class properties
extension JSON {
public typealias NSNull = Foundation.NSNull
public typealias NSError = Foundation.NSError
public class var null:NSNull { return NSNull() }
/// constructs JSON object from string
public convenience init(string:String) {
var err:NSError?
let enc:NSStringEncoding = NSUTF8StringEncoding
var obj:AnyObject? = NSJSONSerialization.JSONObjectWithData(
string.dataUsingEncoding(enc)!, options:nil, error:&err
)
self.init(err != nil ? err! : obj!)
}
/// parses string to the JSON object
/// same as JSON(string:String)
public class func parse(string:String)->JSON {
return JSON(string:string)
}
/// constructs JSON object from the content of NSURL
public convenience init(nsurl:NSURL) {
var enc:NSStringEncoding = NSUTF8StringEncoding
var err:NSError?
let str:String? =
NSString(
contentsOfURL:nsurl, usedEncoding:&enc, error:&err
)
if err != nil { self.init(err!) }
else { self.init(string:str!) }
}
/// fetch the JSON string from NSURL and parse it
/// same as JSON(nsurl:NSURL)
public class func fromNSURL(nsurl:NSURL) -> JSON {
return JSON(nsurl:nsurl)
}
/// constructs JSON object from the content of URL
public convenience init(url:String) {
self.init(nsurl:NSURL(string:url))
}
/// fetch the JSON string from URL in the string
public class func fromURL(url:String) -> JSON {
return JSON(url:url)
}
/// does what JSON.stringify in ES5 does.
/// when the 2nd argument is set to true it pretty prints
public class func stringify(obj:AnyObject, pretty:Bool=false) -> String! {
if !NSJSONSerialization.isValidJSONObject(obj) {
JSON(NSError(
domain:"JSONErrorDomain",
code:422,
userInfo:[NSLocalizedDescriptionKey: "not an JSON object"]
))
return nil
}
return JSON(obj).toString(pretty:pretty)
}
}
/// instance properties
extension JSON {
/// access the element like array
public subscript(idx:Int) -> JSON {
switch _value {
case let err as NSError:
return self
case let ary as NSArray:
if 0 <= idx && idx < ary.count {
return JSON(ary[idx])
}
return JSON(NSError(
domain:"JSONErrorDomain", code:404, userInfo:[
NSLocalizedDescriptionKey:
"[\(idx)] is out of range"
]))
default:
return JSON(NSError(
domain:"JSONErrorDomain", code:500, userInfo:[
NSLocalizedDescriptionKey: "not an array"
]))
}
}
/// access the element like dictionary
public subscript(key:String)->JSON {
switch _value {
case let err as NSError:
return self
case let dic as NSDictionary:
if let val:AnyObject = dic[key] { return JSON(val) }
return JSON(NSError(
domain:"JSONErrorDomain", code:404, userInfo:[
NSLocalizedDescriptionKey:
"[\"\(key)\"] not found"
]))
default:
return JSON(NSError(
domain:"JSONErrorDomain", code:500, userInfo:[
NSLocalizedDescriptionKey: "not an object"
]))
}
}
/// access json data object
public var data:AnyObject? {
return self.isError ? nil : self._value
}
/// Gives the type name as string.
/// e.g. if it returns "Double"
/// .asDouble returns Double
public var type:String {
switch _value {
case is NSError: return "NSError"
case is NSNull: return "NSNull"
case let o as NSNumber:
switch String.fromCString(o.objCType)! {
case "c", "C": return "Bool"
case "q", "l", "i", "s": return "Int"
case "Q", "L", "I", "S": return "UInt"
default: return "Double"
}
case is NSString: return "String"
case is NSArray: return "Array"
case is NSDictionary: return "Dictionary"
default: return "NSError"
}
}
/// check if self is NSError
public var isError: Bool { return _value is NSError }
/// check if self is NSNull
public var isNull: Bool { return _value is NSNull }
/// check if self is Bool
public var isBool: Bool { return type == "Bool" }
/// check if self is Int
public var isInt: Bool { return type == "Int" }
/// check if self is UInt
public var isUInt: Bool { return type == "UInt" }
/// check if self is Double
public var isDouble: Bool { return type == "Double" }
/// check if self is any type of number
public var isNumber: Bool {
if let o = _value as? NSNumber {
let t = String.fromCString(o.objCType)!
return t != "c" && t != "C"
}
return false
}
/// check if self is String
public var isString: Bool { return _value is NSString }
/// check if self is Array
public var isArray: Bool { return _value is NSArray }
/// check if self is Dictionary
public var isDictionary: Bool { return _value is NSDictionary }
/// check if self is a valid leaf node.
public var isLeaf: Bool {
return !(isArray || isDictionary || isError)
}
/// gives NSError if it holds the error. nil otherwise
public var asError:NSError? {
return _value as? NSError
}
/// gives NSNull if self holds it. nil otherwise
public var asNull:NSNull? {
return _value is NSNull ? JSON.null : nil
}
/// gives Bool if self holds it. nil otherwise
public var asBool:Bool? {
switch _value {
case let o as NSNumber:
switch String.fromCString(o.objCType)! {
case "c", "C": return Bool(o.boolValue)
default:
return nil
}
default: return nil
}
}
/// gives Int if self holds it. nil otherwise
public var asInt:Int? {
switch _value {
case let o as NSNumber:
switch String.fromCString(o.objCType)! {
case "c", "C":
return nil
default:
return Int(o.longLongValue)
}
default: return nil
}
}
/// gives Double if self holds it. nil otherwise
public var asDouble:Double? {
switch _value {
case let o as NSNumber:
switch String.fromCString(o.objCType)! {
case "c", "C":
return nil
default:
return Double(o.doubleValue)
}
default: return nil
}
}
// an alias to asDouble
public var asNumber:Double? { return asDouble }
/// gives String if self holds it. nil otherwise
public var asString:String? {
switch _value {
case let o as NSString:
return o as String
default: return nil
}
}
/// if self holds NSArray, gives a [JSON]
/// with elements therein. nil otherwise
public var asArray:[JSON]? {
switch _value {
case let o as NSArray:
var result = [JSON]()
for v:AnyObject in o { result.append(JSON(v)) }
return result
default:
return nil
}
}
/// if self holds NSDictionary, gives a [String:JSON]
/// with elements therein. nil otherwise
public var asDictionary:[String:JSON]? {
switch _value {
case let o as NSDictionary:
var result = [String:JSON]()
for (k:AnyObject, v:AnyObject) in o {
result[k as String] = JSON(v)
}
return result
default: return nil
}
}
/// Yields date from string
public var asDate:NSDate? {
if let dateString = _value as? NSString {
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZZZZ"
return dateFormatter.dateFromString(dateString)
}
return nil
}
/// gives the number of elements if an array or a dictionary.
/// you can use this to check if you can iterate.
public var length:Int {
switch _value {
case let o as NSArray: return o.count
case let o as NSDictionary: return o.count
default: return 0
}
}
}
extension JSON : SequenceType {
public func generate()->GeneratorOf<(AnyObject,JSON)> {
switch _value {
case let o as NSArray:
var i = -1
return GeneratorOf<(AnyObject, JSON)> {
if ++i == o.count { return nil }
return (i, JSON(o[i]))
}
case let o as NSDictionary:
var ks = o.allKeys.reverse()
return GeneratorOf<(AnyObject, JSON)> {
if ks.isEmpty { return nil }
let k = ks.removeLast() as String
return (k, JSON(o.valueForKey(k)!))
}
default:
return GeneratorOf<(AnyObject, JSON)>{ nil }
}
}
public func mutableCopyOfTheObject() -> AnyObject {
return _value.mutableCopy()
}
}
extension JSON : Printable {
/// stringifies self.
/// if pretty:true it pretty prints
public func toString(pretty:Bool=false)->String {
switch _value {
case is NSError: return "\(_value)"
case is NSNull: return "null"
case let o as NSNumber:
switch String.fromCString(o.objCType)! {
case "c", "C":
return o.boolValue.description
case "q", "l", "i", "s":
return o.longLongValue.description
case "Q", "L", "I", "S":
return o.unsignedLongLongValue.description
default:
switch o.doubleValue {
case 0.0/0.0: return "0.0/0.0" // NaN
case -1.0/0.0: return "-1.0/0.0" // -infinity
case +1.0/0.0: return "+1.0/0.0" // infinity
default:
return o.doubleValue.description
}
}
case let o as NSString:
return o.debugDescription
default:
let opts = pretty
? NSJSONWritingOptions.PrettyPrinted : nil
let data = NSJSONSerialization.dataWithJSONObject(
_value, options:opts, error:nil
)
return NSString(
data:data!, encoding:NSUTF8StringEncoding
)
}
}
public var description:String { return toString() }
}
|
mit
|
cad59e410f6eab6ad4e52282e6cdbdda
| 33.678679 | 78 | 0.53988 | 4.637349 | false | false | false | false |
neoneye/SwiftyFORM
|
Source/Cells/StepperCell.swift
|
1
|
2526
|
// MIT license. Copyright (c) 2021 SwiftyFORM. All rights reserved.
import UIKit
public struct StepperCellModel {
var title: String = ""
var value: Int = 0
var valueDidChange: (Int) -> Void = { (value: Int) in
SwiftyFormLog("value \(value)")
}
}
public class StepperCell: UITableViewCell {
public let model: StepperCellModel
public let valueLabel = UILabel()
public let stepperView = UIStepper()
public var containerView = UIView()
public init(model: StepperCellModel) {
self.model = model
super.init(style: .value1, reuseIdentifier: nil)
selectionStyle = .none
textLabel?.text = model.title
valueLabel.font = UIFont.preferredFont(forTextStyle: UIFont.TextStyle.body)
valueLabel.textColor = UIColor.gray
containerView.addSubview(stepperView)
containerView.addSubview(valueLabel)
accessoryView = containerView
stepperView.addTarget(self, action: #selector(StepperCell.valueChanged), for: .valueChanged)
valueLabel.text = "0"
}
public override func layoutSubviews() {
super.layoutSubviews()
stepperView.sizeToFit()
valueLabel.sizeToFit()
let rightPadding: CGFloat = layoutMargins.right
let valueStepperPadding: CGFloat = 10
let valueSize = valueLabel.frame.size
let stepperSize = stepperView.frame.size
let containerWidth = ceil(valueSize.width + valueStepperPadding + stepperSize.width)
containerView.frame = CGRect(x: bounds.width - rightPadding - containerWidth, y: 0, width: containerWidth, height: stepperSize.height)
let valueY: CGFloat = bounds.midY - valueSize.height / 2
valueLabel.frame = CGRect(x: 0, y: valueY, width: valueSize.width, height: valueSize.height).integral
let stepperY: CGFloat = bounds.midY - stepperSize.height / 2
stepperView.frame = CGRect(x: containerWidth - stepperSize.width, y: stepperY, width: stepperSize.width, height: stepperSize.height)
}
public required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
@objc public func valueChanged() {
SwiftyFormLog("value did change")
let value: Double = stepperView.value
let intValue: Int = Int(round(value))
updateValue(intValue)
model.valueDidChange(intValue)
setNeedsLayout()
}
public func updateValue(_ value: Int) {
let value: Double = stepperView.value
let intValue: Int = Int(round(value))
self.valueLabel.text = "\(intValue)"
}
public func setValueWithoutSync(_ value: Int, animated: Bool) {
SwiftyFormLog("set value \(value)")
stepperView.value = Double(value)
updateValue(value)
}
}
|
mit
|
20f1959a2a57281a3870576f86784517
| 28.034483 | 136 | 0.743072 | 3.775785 | false | false | false | false |
Gregsen/okapi
|
MXStatusMenu/Timer.swift
|
1
|
2008
|
import Foundation
class Timer {
/// Closure will be called every time the timer fires
typealias Closure = (timer: Timer) -> ()
/// Parameters
let closure: Closure
let queue: dispatch_queue_t
var isSuspended: Bool = true
/// The default initializer
init(queue: dispatch_queue_t, closure: Closure) {
self.queue = queue
self.closure = closure
}
/// Suspend the timer before it gets destroyed
deinit {
suspend()
}
/// This timer implementation uses Grand Central Dispatch sources
lazy var source: dispatch_source_t = {
dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, self.queue)
}()
/// Convenience class method that creates and start a timer
class func repeatEvery(repeatEvery: Double, closure: Closure) -> Timer {
let timer = Timer(queue: dispatch_get_global_queue(0, 0), closure: closure)
timer.resume(0, `repeat`: repeatEvery, leeway: 0)
return timer
}
/// Fire the timer by calling its closure
func fire() {
closure(timer: self)
}
/// Start or resume the timer with the specified double values
func resume(start: Double, `repeat`: Double, leeway: Double) {
let NanosecondsPerSecond = Double(NSEC_PER_SEC)
resume(Int64(start * NanosecondsPerSecond), `repeat`: UInt64(`repeat` * NanosecondsPerSecond), leeway: UInt64(leeway * NanosecondsPerSecond))
}
/// Start or resume the timer with the specified integer values
func resume(start: Int64, `repeat`: UInt64, leeway: UInt64) {
if isSuspended {
let startTime = dispatch_time(DISPATCH_TIME_NOW, start)
dispatch_source_set_timer(source, startTime, `repeat`, leeway)
dispatch_source_set_event_handler(source) { [weak self] in
if let timer = self {
timer.fire()
}
}
dispatch_resume(source)
isSuspended = false
}
}
/// Suspend the timer
func suspend() {
if !isSuspended {
dispatch_suspend(source)
isSuspended = true
}
}
}
|
mit
|
9360d0fadee1de64a3dba2040d9cb8fb
| 28.101449 | 143 | 0.659363 | 3.80303 | false | false | false | false |
BPForEveryone/BloodPressureForEveryone
|
BPApp/BPEveryone/BPEPatientGraphViewController.swift
|
1
|
9138
|
//
// BPEPatientGraphViewController.swift
// BPForEveryone
//
// Created by MiningMarsh on 11/28/17.
// Copyright © 2017 BlackstoneBuilds. All rights reserved.
//
import Foundation
import UIKit
import CorePlot
class BPEPatientGraphViewController : UIViewController, CPTScatterPlotDataSource, CPTAxisDelegate {
// The number of blood pressure measurements to consider in the graph.
let numberOfMeasurements = 10
// The ID of the patient we are displaying for.
var patientId: Int = 0
// Holds our reference the graph we are rendering,
private var scatterGraph : CPTXYGraph? = nil
// The graph displays doubles.
typealias plotDataType = [CPTScatterPlotField : Double]
// Holds the measurements we want to plot.
private var dataForPlot = [plotDataType]()
// The container that we render the graph to.
@IBOutlet weak var graphContainer: CPTGraphHostingView!
// Returns the currently selected patient.
private var patient: Patient {
get {
return Config.patients[self.patientId]
}
}
// Return the blood pressure measurements we are working with.
private var measurements: [BloodPressureMeasurement] {
get {
return self.patient.bloodPressureMeasurements
}
}
// Calculates the x width of the graph, based on the blood pressure measurement history.
private func graphWidth() -> Double {
if measurements.count == 0 {
return 10.0
}
// Get the date range of possible data.
//let range = measurements[measurements.count].measurementDate. measurements[0].measurementDate
return 0.0
}
// Internal function responsible for setting up the graph.
private func setupGraph() {
// Create the graph, use a dark theme for it.
let graph = CPTXYGraph(frame: .zero)
graph.apply(CPTTheme(named: .plainWhiteTheme))
// Assign the created graph to the view we are in.
let hostingView = self.graphContainer
hostingView!.hostedGraph = graph
// Pad the graph.
graph.paddingLeft = 10.0
graph.paddingRight = 10.0
graph.paddingTop = 10.0
graph.paddingBottom = 10.0
// The space for the plot. Some values currently assumed.
let plotSpace = graph.defaultPlotSpace as! CPTXYPlotSpace
plotSpace.allowsUserInteraction = true
plotSpace.yRange = CPTPlotRange(location:1.0, length:4.0)
plotSpace.xRange = CPTPlotRange(location:1.0, length:5.0)
// Create the axis for the graph.
let axisSet = graph.axisSet as! CPTXYAxisSet
// Create the x axis.
if let x = axisSet.xAxis {
x.majorIntervalLength = 0.5
x.orthogonalPosition = 2.0
x.minorTicksPerInterval = 2
x.labelExclusionRanges = [
CPTPlotRange(location: 0.99, length: 0.02),
CPTPlotRange(location: 1.99, length: 0.02),
CPTPlotRange(location: 2.99, length: 0.02)
]
}
// Create the y axis.
if let y = axisSet.xAxis {
y.majorIntervalLength = 0.5
y.minorTicksPerInterval = 5
y.orthogonalPosition = 2.0
y.labelExclusionRanges = [
CPTPlotRange(location: 0.99, length: 0.02),
CPTPlotRange(location: 1.99, length: 0.02),
CPTPlotRange(location: 3.99, length: 0.02)
]
y.delegate = self
}
// Create a blue plot area
let boundLinePlot = CPTScatterPlot(frame: .zero)
let blueLineStyle = CPTMutableLineStyle()
blueLineStyle.miterLimit = 1.0
blueLineStyle.lineWidth = 3.0
blueLineStyle.lineColor = .blue()
boundLinePlot.dataLineStyle = blueLineStyle
boundLinePlot.identifier = NSString.init(string: "Blue Plot")
boundLinePlot.dataSource = self
graph.add(boundLinePlot)
/* We don't currently want a background image.
let fillImage = CPTImage(named:"BlueTexture")
fillImage.isTiled = true
boundLinePlot.areaFill = CPTFill(image: fillImage)
boundLinePlot.areaBaseValue = 0.0
*/
// Add plot symbols
let symbolLineStyle = CPTMutableLineStyle()
symbolLineStyle.lineColor = .black()
let plotSymbol = CPTPlotSymbol.ellipse()
plotSymbol.fill = CPTFill(color: .blue())
plotSymbol.lineStyle = symbolLineStyle
plotSymbol.size = CGSize(width: 10.0, height: 10.0)
boundLinePlot.plotSymbol = plotSymbol
// Create a green plot area
let dataSourceLinePlot = CPTScatterPlot(frame: .zero)
let greenLineStyle = CPTMutableLineStyle()
greenLineStyle.lineWidth = 3.0
greenLineStyle.lineColor = .green()
greenLineStyle.dashPattern = [5.0, 5.0]
dataSourceLinePlot.dataLineStyle = greenLineStyle
dataSourceLinePlot.identifier = NSString.init(string: "Green Plot")
dataSourceLinePlot.dataSource = self
// Put an area gradient under the plot above
let areaColor = CPTColor(componentRed: 0.3, green: 1.0, blue: 0.3, alpha: 0.8)
let areaGradient = CPTGradient(beginning: areaColor, ending: .clear())
areaGradient.angle = -90.0
let areaGradientFill = CPTFill(gradient: areaGradient)
dataSourceLinePlot.areaFill = areaGradientFill
dataSourceLinePlot.areaBaseValue = 1.75
// Animate in the new plot, as an example
dataSourceLinePlot.opacity = 0.0
graph.add(dataSourceLinePlot)
// Add some initial data
var contentArray = [plotDataType]()
for i in 0 ..< 60 {
let x = 1.0 + Double(i) * 0.05
let y = 1.2 * Double(arc4random()) / Double(UInt32.max) + 1.2
let dataPoint: plotDataType = [.X: x, .Y: y]
contentArray.append(dataPoint)
}
self.dataForPlot = contentArray
self.scatterGraph = graph }
@IBAction func back(_ sender: Any) {
dismiss(animated: true, completion: nil)
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.setupGraph()
}
override func prepare(for segue: UIStoryboardSegue, sender: Any!) {
// Blood pressure list also requires a patient id.
if (segue.identifier == "bloodPressureList") {
let controller = (segue.destination as! UINavigationController).topViewController as! BPEBPListViewController
controller.patientId = self.patientId
}
}
// MARK: - Plot Data Source Methods
func numberOfRecords(for plot: CPTPlot) -> UInt
{
return UInt(self.dataForPlot.count)
}
func number(for plot: CPTPlot, field: UInt, record: UInt) -> Any?
{
let plotField = CPTScatterPlotField(rawValue: Int(field))
if let num = self.dataForPlot[Int(record)][plotField!] {
let plotID = plot.identifier as! String
if (plotField! == .Y) && (plotID == "Green Plot") {
return (num + 1.0) as NSNumber
}
else {
return num as NSNumber
}
}
else {
return nil
}
}
// MARK: - Axis Delegate Methods
private func axis(_ axis: CPTAxis, shouldUpdateAxisLabelsAtLocations locations: NSSet!) -> Bool
{
if let formatter = axis.labelFormatter {
let labelOffset = axis.labelOffset
var newLabels = Set<CPTAxisLabel>()
if let labelTextStyle = axis.labelTextStyle?.mutableCopy() as? CPTMutableTextStyle {
for location in locations {
if let tickLocation = location as? NSNumber {
if tickLocation.doubleValue >= 0.0 {
labelTextStyle.color = .green()
}
else {
labelTextStyle.color = .red()
}
let labelString = formatter.string(for:tickLocation)
let newLabelLayer = CPTTextLayer(text: labelString, style: labelTextStyle)
let newLabel = CPTAxisLabel(contentLayer: newLabelLayer)
newLabel.tickLocation = tickLocation
newLabel.offset = labelOffset
newLabels.insert(newLabel)
}
}
axis.axisLabels = newLabels
}
}
return false
}
}
|
mit
|
da7abab97fa0a7fc5b05248388a568a7
| 35.257937 | 121 | 0.570866 | 4.628673 | false | false | false | false |
Guichaguri/react-native-track-player
|
ios/RNTrackPlayer/Vendor/SwiftAudio/Classes/QueuedAudioPlayer.swift
|
1
|
5776
|
//
// QueuedAudioPlayer.swift
// SwiftAudio
//
// Created by Jørgen Henrichsen on 24/03/2018.
//
import Foundation
import MediaPlayer
/**
An audio player that can keep track of a queue of AudioItems.
*/
public class QueuedAudioPlayer: AudioPlayer {
let queueManager: QueueManager = QueueManager<AudioItem>()
/// The repeat mode for the queue player.
public var repeatMode: RepeatMode = .off
public override var currentItem: AudioItem? {
return queueManager.current
}
/**
The index of the current item.
*/
public var currentIndex: Int {
return queueManager.currentIndex
}
/**
Stops the player and clears the queue.
*/
public override func stop() {
super.stop()
}
override func reset() {
super.reset()
queueManager.clearQueue()
}
/**
All items currently in the queue.
*/
public var items: [AudioItem] {
return queueManager.items
}
/**
The previous items held by the queue.
*/
public var previousItems: [AudioItem] {
return queueManager.previousItems
}
/**
The upcoming items in the queue.
*/
public var nextItems: [AudioItem] {
return queueManager.nextItems
}
/**
Will replace the current item with a new one and load it into the player.
- parameter item: The AudioItem to replace the current item.
- throws: APError.LoadError
*/
public override func load(item: AudioItem, playWhenReady: Bool) throws {
try super.load(item: item, playWhenReady: playWhenReady)
queueManager.replaceCurrentItem(with: item)
}
/**
Add a single item to the queue.
- parameter item: The item to add.
- parameter playWhenReady: If the AudioPlayer has no item loaded, it will load the `item`. If this is `true` it will automatically start playback. Default is `true`.
- throws: `APError`
*/
public func add(item: AudioItem, playWhenReady: Bool = true) throws {
if currentItem == nil {
queueManager.addItem(item)
try self.load(item: item, playWhenReady: playWhenReady)
}
else {
queueManager.addItem(item)
}
}
/**
Add items to the queue.
- parameter items: The items to add to the queue.
- parameter playWhenReady: If the AudioPlayer has no item loaded, it will load the first item in the list. If this is `true` it will automatically start playback. Default is `true`.
- throws: `APError`
*/
public func add(items: [AudioItem], playWhenReady: Bool = true) throws {
if currentItem == nil {
queueManager.addItems(items)
try self.load(item: currentItem!, playWhenReady: playWhenReady)
}
else {
queueManager.addItems(items)
}
}
public func add(items: [AudioItem], at index: Int) throws {
try queueManager.addItems(items, at: index)
}
/**
Step to the next item in the queue.
- throws: `APError`
*/
public func next() throws {
event.playbackEnd.emit(data: .skippedToNext)
let nextItem = try queueManager.next()
try self.load(item: nextItem, playWhenReady: true)
}
/**
Step to the previous item in the queue.
*/
public func previous() throws {
event.playbackEnd.emit(data: .skippedToPrevious)
let previousItem = try queueManager.previous()
try self.load(item: previousItem, playWhenReady: true)
}
/**
Remove an item from the queue.
- parameter index: The index of the item to remove.
- throws: `APError.QueueError`
*/
public func removeItem(at index: Int) throws {
try queueManager.removeItem(at: index)
}
/**
Jump to a certain item in the queue.
- parameter index: The index of the item to jump to.
- parameter playWhenReady: Wether the item should start playing when ready. Default is `true`.
- throws: `APError`
*/
public func jumpToItem(atIndex index: Int, playWhenReady: Bool = true) throws {
event.playbackEnd.emit(data: .jumpedToIndex)
let item = try queueManager.jump(to: index)
try self.load(item: item, playWhenReady: playWhenReady)
}
/**
Move an item in the queue from one position to another.
- parameter fromIndex: The index of the item to move.
- parameter toIndex: The index to move the item to.
- throws: `APError.QueueError`
*/
func moveItem(fromIndex: Int, toIndex: Int) throws {
try queueManager.moveItem(fromIndex: fromIndex, toIndex: toIndex)
}
/**
Remove all upcoming items, those returned by `next()`
*/
public func removeUpcomingItems() {
queueManager.removeUpcomingItems()
}
/**
Remove all previous items, those returned by `previous()`
*/
public func removePreviousItems() {
queueManager.removePreviousItems()
}
// MARK: - AVPlayerWrapperDelegate
override func AVWrapperItemDidPlayToEndTime() {
super.AVWrapperItemDidPlayToEndTime()
switch repeatMode {
case .off: try? self.next()
case .track:
seek(to: 0)
play()
case .queue:
do {
try self.next()
} catch APError.QueueError.noNextItem {
do {
try jumpToItem(atIndex: 0, playWhenReady: true)
} catch { /* TODO: handle possible errors from load */ }
} catch { /* TODO: handle possible errors from load */ }
}
}
}
|
gpl-3.0
|
ce1a8d38ba207ca57d0b81a3d1e98020
| 27.589109 | 186 | 0.603117 | 4.494163 | false | false | false | false |
ReactiveKit/Bond
|
Sources/Bond/Observable Collections/OrderedCollectionDiff+Strideable+Differ.swift
|
3
|
4095
|
//
// The MIT License (MIT)
//
// Copyright (c) 2018 DeclarativeHub/Bond
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
import Differ
import ReactiveKit
extension OrderedCollectionDiff where Index == Int {
public init(from diff: ExtendedDiff) {
self.init()
for element in diff.elements {
switch element {
case .insert(let at):
inserts.append(at)
case .delete(let at):
deletes.append(at)
case .move(let from, let to):
moves.append((from: from, to: to))
}
}
}
}
extension SignalProtocol where Element: Collection, Element.Index == Int {
/// Diff each next element (array) against the previous one and emit a diff event.
public func diff(_ areEqual: @escaping (Element.Element, Element.Element) -> Bool) -> Signal<OrderedCollectionChangeset<Element>, Error> {
return diff(generateDiff: { c1, c2 in OrderedCollectionDiff<Int>(from: c1.extendedDiff(c2, isEqual: areEqual)) })
}
}
extension SignalProtocol where Element: Collection, Element.Element: Equatable, Element.Index == Int {
/// Diff each next element (array) against the previous one and emit a diff event.
public func diff() -> Signal<OrderedCollectionChangeset<Element>, Error> {
return diff(generateDiff: { c1, c2 in OrderedCollectionDiff<Int>(from: c1.extendedDiff(c2)) })
}
}
extension MutableChangesetContainerProtocol where Changeset: OrderedCollectionChangesetProtocol, Changeset.Collection.Index == Int {
/// Replace the underlying collection with the given collection. Setting `performDiff: true` will make the framework
/// calculate the diff between the existing and new collection and emit an event with the calculated diff.
/// - Complexity: O((N+M)*D) if `performDiff: true`, O(1) otherwise.
public func replace(with newCollection: Changeset.Collection, performDiff: Bool, areEqual: @escaping (Changeset.Collection.Element, Changeset.Collection.Element) -> Bool) {
replace(with: newCollection, performDiff: performDiff) { (old, new) -> OrderedCollectionDiff<Int> in
return OrderedCollectionDiff<Int>(from: old.extendedDiff(new, isEqual: areEqual))
}
}
}
extension MutableChangesetContainerProtocol where Changeset: OrderedCollectionChangesetProtocol, Changeset.Collection.Index == Int, Changeset.Collection.Element: Equatable {
/// Replace the underlying collection with the given collection. Setting `performDiff: true` will make the framework
/// calculate the diff between the existing and new collection and emit an event with the calculated diff.
/// - Complexity: O((N+M)*D) if `performDiff: true`, O(1) otherwise.
public func replace(with newCollection: Changeset.Collection, performDiff: Bool) {
replace(with: newCollection, performDiff: performDiff) { (old, new) -> OrderedCollectionDiff<Int> in
return OrderedCollectionDiff<Int>(from: old.extendedDiff(new))
}
}
}
|
mit
|
d96029f8f022a1308b763b4e6edce56d
| 48.337349 | 176 | 0.714042 | 4.427027 | false | false | false | false |
mperovic/my41
|
my41/Classes/String+Extensions.swift
|
1
|
741
|
//
// Extensions.swift
// i41CV
//
// Created by Miroslav Perovic on 8/14/14.
// Copyright (c) 2014 iPera. All rights reserved.
//
import Foundation
extension String {
subscript(integerIndex: Int) -> Character {
let index = self.index(self.startIndex, offsetBy: integerIndex)
// let index = advance(startIndex, integerIndex)
return self[index]
}
subscript(integerRange: Range<Int>) -> String {
let start = self.index(self.startIndex, offsetBy: integerRange.lowerBound)
let end = self.index(self.startIndex, offsetBy: integerRange.upperBound)
// let start = advance(startIndex, integerRange.startIndex)
// let end = advance(startIndex, integerRange.endIndex)
let range = start..<end
return String(self[range])
}
}
|
bsd-3-clause
|
940ae907c5ae8cf4eec1b864acd5cf36
| 27.5 | 76 | 0.723347 | 3.545455 | false | false | false | false |
JakeLin/IBAnimatable
|
Sources/Protocols/Designable/BackgroundImageDesignable.swift
|
2
|
1194
|
//
// Created by phimage on 25/03/2017.
// Copyright © 2017 IBAnimatable. All rights reserved.
//
import UIKit
/// Protocol for designing background
public protocol BackgroundDesignable: class {
/**
* The background view
*/
var backgroundView: UIView? { get set }
}
/// Protocol for designing background image
public protocol BackgroundImageDesignable: BackgroundDesignable {
/**
* The background image
*/
var backgroundImage: UIImage? { get set }
}
public extension BackgroundImageDesignable {
func configureBackgroundImage() {
if let image = backgroundImage {
if let imageView = backgroundView as? UIImageView {
imageView.image = image
} else {
backgroundView = PrivateAnimatableImageView(image: image)
}
} else {
if backgroundView is PrivateAnimatableImageView {
backgroundView = nil
}
}
}
var backgroundImageView: UIImageView? {
get {
return backgroundView as? UIImageView
}
set {
backgroundView = newValue
}
}
}
/// Private class of image view used in `BackgroundImageDesignable` only
private class PrivateAnimatableImageView: AnimatableImageView {
}
|
mit
|
dd5b3bd440922fd752c49608bbbbfa2a
| 19.568966 | 72 | 0.685666 | 4.82996 | false | false | false | false |
longitachi/ZLPhotoBrowser
|
Sources/General/ZLFetchImageOperation.swift
|
1
|
6011
|
//
// ZLFetchImageOperation.swift
// ZLPhotoBrowser
//
// Created by long on 2020/8/18.
//
// Copyright (c) 2020 Long Zhang <[email protected]>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import UIKit
import Photos
class ZLFetchImageOperation: Operation {
private let model: ZLPhotoModel
private let isOriginal: Bool
private let progress: ((CGFloat, Error?, UnsafeMutablePointer<ObjCBool>, [AnyHashable: Any]?) -> Void)?
private let completion: (UIImage?, PHAsset?) -> Void
private var pri_isExecuting = false {
willSet {
self.willChangeValue(forKey: "isExecuting")
}
didSet {
self.didChangeValue(forKey: "isExecuting")
}
}
override var isExecuting: Bool {
return pri_isExecuting
}
private var pri_isFinished = false {
willSet {
self.willChangeValue(forKey: "isFinished")
}
didSet {
self.didChangeValue(forKey: "isFinished")
}
}
override var isFinished: Bool {
return pri_isFinished
}
private var pri_isCancelled = false {
willSet {
willChangeValue(forKey: "isCancelled")
}
didSet {
didChangeValue(forKey: "isCancelled")
}
}
private var requestImageID: PHImageRequestID = PHInvalidImageRequestID
override var isCancelled: Bool {
return pri_isCancelled
}
init(
model: ZLPhotoModel,
isOriginal: Bool,
progress: ((CGFloat, Error?, UnsafeMutablePointer<ObjCBool>, [AnyHashable: Any]?) -> Void)? = nil,
completion: @escaping ((UIImage?, PHAsset?) -> Void)
) {
self.model = model
self.isOriginal = isOriginal
self.progress = progress
self.completion = completion
super.init()
}
override func start() {
if isCancelled {
fetchFinish()
return
}
zl_debugPrint("---- start fetch")
pri_isExecuting = true
// 存在编辑的图片
if let ei = model.editImage {
if ZLPhotoConfiguration.default().saveNewImageAfterEdit {
ZLPhotoManager.saveImageToAlbum(image: ei) { [weak self] _, asset in
self?.completion(ei, asset)
self?.fetchFinish()
}
} else {
ZLMainAsync {
self.completion(ei, nil)
self.fetchFinish()
}
}
return
}
if ZLPhotoConfiguration.default().allowSelectGif, model.type == .gif {
requestImageID = ZLPhotoManager.fetchOriginalImageData(for: model.asset) { [weak self] data, _, isDegraded in
if !isDegraded {
let image = UIImage.zl.animateGifImage(data: data)
self?.completion(image, nil)
self?.fetchFinish()
}
}
return
}
if isOriginal {
requestImageID = ZLPhotoManager.fetchOriginalImage(for: model.asset, progress: progress) { [weak self] image, isDegraded in
if !isDegraded {
zl_debugPrint("---- 原图加载完成 \(String(describing: self?.isCancelled))")
self?.completion(image?.zl.fixOrientation(), nil)
self?.fetchFinish()
}
}
} else {
requestImageID = ZLPhotoManager.fetchImage(for: model.asset, size: model.previewSize, progress: progress) { [weak self] image, isDegraded in
if !isDegraded {
zl_debugPrint("---- 加载完成 isCancelled: \(String(describing: self?.isCancelled))")
self?.completion(self?.scaleImage(image?.zl.fixOrientation()), nil)
self?.fetchFinish()
}
}
}
}
override func cancel() {
super.cancel()
zl_debugPrint("---- cancel \(isExecuting) \(requestImageID)")
PHImageManager.default().cancelImageRequest(requestImageID)
pri_isCancelled = true
if isExecuting {
fetchFinish()
}
}
private func scaleImage(_ image: UIImage?) -> UIImage? {
guard let i = image else {
return nil
}
guard let data = i.jpegData(compressionQuality: 1) else {
return i
}
let mUnit: CGFloat = 1024 * 1024
if data.count < Int(0.2 * mUnit) {
return i
}
let scale: CGFloat = (data.count > Int(mUnit) ? 0.6 : 0.8)
guard let d = i.jpegData(compressionQuality: scale) else {
return i
}
return UIImage(data: d)
}
private func fetchFinish() {
pri_isExecuting = false
pri_isFinished = true
}
}
|
mit
|
24172a0a70b9e5724276b350c7ddaf51
| 32.022099 | 152 | 0.573866 | 4.911257 | false | false | false | false |
nicadre/SwiftyProtein
|
Pods/SWXMLHash/Source/SWXMLHash.swift
|
2
|
21975
|
//
// SWXMLHash.swift
//
// Copyright (c) 2014 David Mohundro
//
// 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.
// swiftlint exceptions:
// - Disabled file_length because there are a number of users that still pull the
// source down as is and it makes pulling the code into a project easier.
// swiftlint:disable file_length
import Foundation
let rootElementName = "SWXMLHash_Root_Element"
/// Parser options
public class SWXMLHashOptions {
internal init() {}
/// determines whether to parse the XML with lazy parsing or not
public var shouldProcessLazily = false
/// determines whether to parse XML namespaces or not (forwards to
/// `NSXMLParser.shouldProcessNamespaces`)
public var shouldProcessNamespaces = false
}
/// Simple XML parser
public class SWXMLHash {
let options: SWXMLHashOptions
private init(_ options: SWXMLHashOptions = SWXMLHashOptions()) {
self.options = options
}
/**
Method to configure how parsing works.
- parameters:
- configAction: a block that passes in an `SWXMLHashOptions` object with
options to be set
- returns: an `SWXMLHash` instance
*/
class public func config(configAction: (SWXMLHashOptions) -> ()) -> SWXMLHash {
let opts = SWXMLHashOptions()
configAction(opts)
return SWXMLHash(opts)
}
/**
Begins parsing the passed in XML string.
- parameters:
- xml: an XML string. __Note__ that this is not a URL but a
string containing XML.
- returns: an `XMLIndexer` instance that can be iterated over
*/
public func parse(xml: String) -> XMLIndexer {
return parse((xml as NSString).dataUsingEncoding(NSUTF8StringEncoding)!)
}
/**
Begins parsing the passed in XML string.
- parameters:
- data: an `NSData` instance containing XML
- returns: an `XMLIndexer` instance that can be iterated over
*/
public func parse(data: NSData) -> XMLIndexer {
let parser: SimpleXmlParser = options.shouldProcessLazily
? LazyXMLParser(options)
: XMLParser(options)
return parser.parse(data)
}
/**
Method to parse XML passed in as a string.
- parameter xml: The XML to be parsed
- returns: An XMLIndexer instance that is used to look up elements in the XML
*/
class public func parse(xml: String) -> XMLIndexer {
return SWXMLHash().parse(xml)
}
/**
Method to parse XML passed in as an NSData instance.
- parameter data: The XML to be parsed
- returns: An XMLIndexer instance that is used to look up elements in the XML
*/
class public func parse(data: NSData) -> XMLIndexer {
return SWXMLHash().parse(data)
}
/**
Method to lazily parse XML passed in as a string.
- parameter xml: The XML to be parsed
- returns: An XMLIndexer instance that is used to look up elements in the XML
*/
class public func lazy(xml: String) -> XMLIndexer {
return config { conf in conf.shouldProcessLazily = true }.parse(xml)
}
/**
Method to lazily parse XML passed in as an NSData instance.
- parameter data: The XML to be parsed
- returns: An XMLIndexer instance that is used to look up elements in the XML
*/
class public func lazy(data: NSData) -> XMLIndexer {
return config { conf in conf.shouldProcessLazily = true }.parse(data)
}
}
struct Stack<T> {
var items = [T]()
mutating func push(item: T) {
items.append(item)
}
mutating func pop() -> T {
return items.removeLast()
}
mutating func removeAll() {
items.removeAll(keepCapacity: false)
}
func top() -> T {
return items[items.count - 1]
}
}
protocol SimpleXmlParser {
init(_ options: SWXMLHashOptions)
func parse(data: NSData) -> XMLIndexer
}
/// The implementation of NSXMLParserDelegate and where the lazy parsing actually happens.
class LazyXMLParser: NSObject, SimpleXmlParser, NSXMLParserDelegate {
required init(_ options: SWXMLHashOptions) {
self.options = options
super.init()
}
var root = XMLElement(name: rootElementName)
var parentStack = Stack<XMLElement>()
var elementStack = Stack<String>()
var data: NSData?
var ops: [IndexOp] = []
let options: SWXMLHashOptions
func parse(data: NSData) -> XMLIndexer {
self.data = data
return XMLIndexer(self)
}
func startParsing(ops: [IndexOp]) {
// clear any prior runs of parse... expected that this won't be necessary,
// but you never know
parentStack.removeAll()
root = XMLElement(name: rootElementName)
parentStack.push(root)
self.ops = ops
let parser = NSXMLParser(data: data!)
parser.shouldProcessNamespaces = options.shouldProcessNamespaces
parser.delegate = self
parser.parse()
}
func parser(parser: NSXMLParser,
didStartElement elementName: String,
namespaceURI: String?,
qualifiedName qName: String?,
attributes attributeDict: [String: String]) {
elementStack.push(elementName)
if !onMatch() {
return
}
let currentNode = parentStack.top().addElement(elementName, withAttributes: attributeDict)
parentStack.push(currentNode)
}
func parser(parser: NSXMLParser, foundCharacters string: String) {
if !onMatch() {
return
}
let current = parentStack.top()
current.addText(string)
}
func parser(parser: NSXMLParser,
didEndElement elementName: String,
namespaceURI: String?,
qualifiedName qName: String?) {
let match = onMatch()
elementStack.pop()
if match {
parentStack.pop()
}
}
func onMatch() -> Bool {
// we typically want to compare against the elementStack to see if it matches ops, *but*
// if we're on the first element, we'll instead compare the other direction.
if elementStack.items.count > ops.count {
return elementStack.items.startsWith(ops.map { $0.key })
} else {
return ops.map { $0.key }.startsWith(elementStack.items)
}
}
}
/// The implementation of NSXMLParserDelegate and where the parsing actually happens.
class XMLParser: NSObject, SimpleXmlParser, NSXMLParserDelegate {
required init(_ options: SWXMLHashOptions) {
self.options = options
super.init()
}
var root = XMLElement(name: rootElementName)
var parentStack = Stack<XMLElement>()
let options: SWXMLHashOptions
func parse(data: NSData) -> XMLIndexer {
// clear any prior runs of parse... expected that this won't be necessary,
// but you never know
parentStack.removeAll()
parentStack.push(root)
let parser = NSXMLParser(data: data)
parser.shouldProcessNamespaces = options.shouldProcessNamespaces
parser.delegate = self
parser.parse()
return XMLIndexer(root)
}
func parser(parser: NSXMLParser,
didStartElement elementName: String,
namespaceURI: String?,
qualifiedName qName: String?,
attributes attributeDict: [String: String]) {
let currentNode = parentStack.top().addElement(elementName, withAttributes: attributeDict)
parentStack.push(currentNode)
}
func parser(parser: NSXMLParser, foundCharacters string: String) {
let current = parentStack.top()
current.addText(string)
}
func parser(parser: NSXMLParser,
didEndElement elementName: String,
namespaceURI: String?,
qualifiedName qName: String?) {
parentStack.pop()
}
}
/// Represents an indexed operation against a lazily parsed `XMLIndexer`
public class IndexOp {
var index: Int
let key: String
init(_ key: String) {
self.key = key
self.index = -1
}
func toString() -> String {
if index >= 0 {
return key + " " + index.description
}
return key
}
}
/// Represents a collection of `IndexOp` instances. Provides a means of iterating them
/// to find a match in a lazily parsed `XMLIndexer` instance.
public class IndexOps {
var ops: [IndexOp] = []
let parser: LazyXMLParser
init(parser: LazyXMLParser) {
self.parser = parser
}
func findElements() -> XMLIndexer {
parser.startParsing(ops)
let indexer = XMLIndexer(parser.root)
var childIndex = indexer
for op in ops {
childIndex = childIndex[op.key]
if op.index >= 0 {
childIndex = childIndex[op.index]
}
}
ops.removeAll(keepCapacity: false)
return childIndex
}
func stringify() -> String {
var s = ""
for op in ops {
s += "[" + op.toString() + "]"
}
return s
}
}
/// Returned from SWXMLHash, allows easy element lookup into XML data.
public enum XMLIndexer: SequenceType {
case Element(XMLElement)
case List([XMLElement])
case Stream(IndexOps)
case XMLError(Error)
/// Error type that is thrown when an indexing or parsing operation fails.
public enum Error: ErrorType {
case Attribute(attr: String)
case AttributeValue(attr: String, value: String)
case Key(key: String)
case Index(idx: Int)
case Init(instance: AnyObject)
case Error
}
/// The underlying XMLElement at the currently indexed level of XML.
public var element: XMLElement? {
switch self {
case .Element(let elem):
return elem
case .Stream(let ops):
let list = ops.findElements()
return list.element
default:
return nil
}
}
/// All elements at the currently indexed level
public var all: [XMLIndexer] {
switch self {
case .List(let list):
var xmlList = [XMLIndexer]()
for elem in list {
xmlList.append(XMLIndexer(elem))
}
return xmlList
case .Element(let elem):
return [XMLIndexer(elem)]
case .Stream(let ops):
let list = ops.findElements()
return list.all
default:
return []
}
}
/// All child elements from the currently indexed level
public var children: [XMLIndexer] {
var list = [XMLIndexer]()
for elem in all.map({ $0.element! }).flatMap({ $0 }) {
for elem in elem.xmlChildren {
list.append(XMLIndexer(elem))
}
}
return list
}
/**
Allows for element lookup by matching attribute values.
- parameters:
- attr: should the name of the attribute to match on
- value: should be the value of the attribute to match on
- throws: an XMLIndexer.XMLError if an element with the specified attribute isn't found
- returns: instance of XMLIndexer
*/
public func withAttr(attr: String, _ value: String) throws -> XMLIndexer {
switch self {
case .Stream(let opStream):
opStream.stringify()
let match = opStream.findElements()
return try match.withAttr(attr, value)
case .List(let list):
if let elem = list.filter({$0.attributes[attr] == value}).first {
return .Element(elem)
}
throw Error.AttributeValue(attr: attr, value: value)
case .Element(let elem):
if let attr = elem.attributes[attr] {
if attr == value {
return .Element(elem)
}
throw Error.AttributeValue(attr: attr, value: value)
}
fallthrough
default:
throw Error.Attribute(attr: attr)
}
}
/**
Initializes the XMLIndexer
- parameter _: should be an instance of XMLElement, but supports other values for error handling
- throws: an Error if the object passed in isn't an XMLElement or LaxyXMLParser
*/
public init(_ rawObject: AnyObject) throws {
switch rawObject {
case let value as XMLElement:
self = .Element(value)
case let value as LazyXMLParser:
self = .Stream(IndexOps(parser: value))
default:
throw Error.Init(instance: rawObject)
}
}
/**
Initializes the XMLIndexer
- parameter _: an instance of XMLElement
*/
public init(_ elem: XMLElement) {
self = .Element(elem)
}
init(_ stream: LazyXMLParser) {
self = .Stream(IndexOps(parser: stream))
}
/**
Find an XML element at the current level by element name
- parameter key: The element name to index by
- returns: instance of XMLIndexer to match the element (or elements) found by key
- throws: Throws an XMLIndexerError.Key if no element was found
*/
public func byKey(key: String) throws -> XMLIndexer {
switch self {
case .Stream(let opStream):
let op = IndexOp(key)
opStream.ops.append(op)
return .Stream(opStream)
case .Element(let elem):
let match = elem.xmlChildren.filter({ $0.name == key })
if !match.isEmpty {
if match.count == 1 {
return .Element(match[0])
} else {
return .List(match)
}
}
fallthrough
default:
throw Error.Key(key: key)
}
}
/**
Find an XML element at the current level by element name
- parameter key: The element name to index by
- returns: instance of XMLIndexer to match the element (or elements) found by
*/
public subscript(key: String) -> XMLIndexer {
do {
return try self.byKey(key)
} catch let error as Error {
return .XMLError(error)
} catch {
return .XMLError(.Key(key: key))
}
}
/**
Find an XML element by index within a list of XML Elements at the current level
- parameter index: The 0-based index to index by
- throws: XMLIndexer.XMLError if the index isn't found
- returns: instance of XMLIndexer to match the element (or elements) found by index
*/
public func byIndex(index: Int) throws -> XMLIndexer {
switch self {
case .Stream(let opStream):
opStream.ops[opStream.ops.count - 1].index = index
return .Stream(opStream)
case .List(let list):
if index <= list.count {
return .Element(list[index])
}
return .XMLError(.Index(idx: index))
case .Element(let elem):
if index == 0 {
return .Element(elem)
}
fallthrough
default:
return .XMLError(.Index(idx: index))
}
}
/**
Find an XML element by index
- parameter index: The 0-based index to index by
- returns: instance of XMLIndexer to match the element (or elements) found by index
*/
public subscript(index: Int) -> XMLIndexer {
do {
return try byIndex(index)
} catch let error as Error {
return .XMLError(error)
} catch {
return .XMLError(.Index(idx: index))
}
}
typealias GeneratorType = XMLIndexer
/**
Method to iterate (for-in) over the `all` collection
- returns: an array of `XMLIndexer` instances
*/
public func generate() -> IndexingGenerator<[XMLIndexer]> {
return all.generate()
}
}
/// XMLIndexer extensions
extension XMLIndexer: BooleanType {
/// True if a valid XMLIndexer, false if an error type
public var boolValue: Bool {
switch self {
case .XMLError:
return false
default:
return true
}
}
}
extension XMLIndexer: CustomStringConvertible {
/// The XML representation of the XMLIndexer at the current level
public var description: String {
switch self {
case .List(let list):
return list.map { $0.description }.joinWithSeparator("")
case .Element(let elem):
if elem.name == rootElementName {
return elem.children.map { $0.description }.joinWithSeparator("")
}
return elem.description
default:
return ""
}
}
}
extension XMLIndexer.Error: CustomStringConvertible {
/// The description for the `XMLIndexer.Error`.
public var description: String {
switch self {
case .Attribute(let attr):
return "XML Attribute Error: Missing attribute [\"\(attr)\"]"
case .AttributeValue(let attr, let value):
return "XML Attribute Error: Missing attribute [\"\(attr)\"] with value [\"\(value)\"]"
case .Key(let key):
return "XML Element Error: Incorrect key [\"\(key)\"]"
case .Index(let index):
return "XML Element Error: Incorrect index [\"\(index)\"]"
case .Init(let instance):
return "XML Indexer Error: initialization with Object [\"\(instance)\"]"
case .Error:
return "Unknown Error"
}
}
}
/// Models content for an XML doc, whether it is text or XML
public protocol XMLContent: CustomStringConvertible {
}
/// Models a text element
public class TextElement: XMLContent {
public let text: String
init(text: String) {
self.text = text
}
}
/// Models an XML element, including name, text and attributes
public class XMLElement: XMLContent {
/// The name of the element
public let name: String
/// The attributes of the element
public var attributes = [String:String]()
/// The inner text of the element, if it exists
public var text: String? {
return children
.map({ $0 as? TextElement })
.flatMap({ $0 })
.reduce("", combine: { $0 + $1!.text })
}
var children = [XMLContent]()
var count: Int = 0
var index: Int
var xmlChildren: [XMLElement] {
return children.map { $0 as? XMLElement }.flatMap { $0 }
}
/**
Initialize an XMLElement instance
- parameters:
- name: The name of the element to be initialized
- index: The index of the element to be initialized
*/
init(name: String, index: Int = 0) {
self.name = name
self.index = index
}
/**
Adds a new XMLElement underneath this instance of XMLElement
- parameters:
- name: The name of the new element to be added
- withAttributes: The attributes dictionary for the element being added
- returns: The XMLElement that has now been added
*/
func addElement(name: String, withAttributes attributes: NSDictionary) -> XMLElement {
let element = XMLElement(name: name, index: count)
count += 1
children.append(element)
for (keyAny, valueAny) in attributes {
if let key = keyAny as? String,
let value = valueAny as? String {
element.attributes[key] = value
}
}
return element
}
func addText(text: String) {
let elem = TextElement(text: text)
children.append(elem)
}
}
extension TextElement: CustomStringConvertible {
/// The text value for a `TextElement` instance.
public var description: String {
return text
}
}
extension XMLElement: CustomStringConvertible {
/// The tag, attributes and content for a `XMLElement` instance (<elem id="foo">content</elem>)
public var description: String {
var attributesStringList = [String]()
if !attributes.isEmpty {
for (key, val) in attributes {
attributesStringList.append("\(key)=\"\(val)\"")
}
}
var attributesString = attributesStringList.joinWithSeparator(" ")
if !attributesString.isEmpty {
attributesString = " " + attributesString
}
if !children.isEmpty {
var xmlReturn = [String]()
xmlReturn.append("<\(name)\(attributesString)>")
for child in children {
xmlReturn.append(child.description)
}
xmlReturn.append("</\(name)>")
return xmlReturn.joinWithSeparator("")
}
if text != nil {
return "<\(name)\(attributesString)>\(text!)</\(name)>"
} else {
return "<\(name)\(attributesString)/>"
}
}
}
|
gpl-3.0
|
dd59a7c26a05caadf10ebc17b68c1a28
| 28.979536 | 100 | 0.602639 | 4.840308 | false | false | false | false |
sean915213/SGYWebSession
|
Example/Pods/SGYSwiftUtility/SGYSwiftUtility/Classes/NSLayoutConstraintExtension.swift
|
1
|
5966
|
//
// AutoLayoutExtensions.swift
// SGYSwiftUtility
//
// Created by Sean G Young on 2/13/16.
//
//
import Foundation
extension NSLayoutConstraint {
/**
Creates and returns an array of `NSLayoutConstraint` objects constructed to pin the provided view on all sides within its superview. The applied margins are zero on all sides.
- parameter view: The view to create the layout constraints for.
- returns: An array of `NSLayoutConstraint` objects pinning the view.
*/
public class func constraintsPinningView(_ view: UIView, toMargins: Bool = false) -> [NSLayoutConstraint] {
if toMargins {
let hConstraints = constraintsPinningView(view, axis: .horizontal, toMargins: toMargins)
let vConstraints = constraintsPinningView(view, axis: .horizontal, toMargins: toMargins)
return hConstraints + vConstraints
} else {
return constraintsPinningView(view, insets: UIEdgeInsets.zero)
}
}
/**
Creates and returns an array of `NSLayoutConstraint` objects constructed to pin the provided view on all sides within its superview. The provided `insets` determine the margins.
- parameter view: The view to create the layout constraints for.
- parameter insets: A `UIEdgeInsets` value describing the margins to apply.
- returns: An array of `NSLayoutConstraint` objects pinning the view.
*/
public class func constraintsPinningView(_ view: UIView, insets: UIEdgeInsets) -> [NSLayoutConstraint] {
let hConstraints = NSLayoutConstraint.constraintsPinningView(view, axis: .horizontal, leadMargin: insets.left, trailingMargin: insets.right)
let vConstraints = NSLayoutConstraint.constraintsPinningView(view, axis: .vertical, leadMargin: insets.top, trailingMargin: insets.bottom)
return hConstraints + vConstraints
}
/**
Creates and returns an array of `NSLayoutConstraint` objects constructed to pin the provided `views` to their respective superviews along the provided `axis`. The leading and trailing margins are both zero.
- parameter views: An array of views to create the layout constraints for.
- parameter axis: The axis along which to pin `views`.
- returns: An array of `NSLayoutConstraint` objects pinning `views` along `axis`.
*/
public class func constraintsPinningViews(_ views: [UIView], axis: UILayoutConstraintAxis, toMargins: Bool = false) -> [NSLayoutConstraint] {
if toMargins {
return views.flatMap { self.constraintsPinningView($0, axis: axis, toMargins: toMargins) }
} else {
return constraintsPinningViews(views, axis: axis, leadMargin: 0, trailingMargin: 0)
}
}
/**
Creates and returns an array of `NSLayoutConstraint` objects constructed to pin `views` to their respective superviews along the provided `axis`.
- parameter views: An array of views to create the layout constraints for.
- parameter axis: The axis along which to pin `views`.
- parameter leadMargin: The leading margin to apply to each view.
- parameter trailingMargin: The trailing margin to apply to each view.
- returns: An array of `NSLayoutConstraint` objects pinning `views` along `axis`.
*/
public class func constraintsPinningViews(_ views: [UIView], axis: UILayoutConstraintAxis, leadMargin: CGFloat, trailingMargin: CGFloat) -> [NSLayoutConstraint] {
return views.flatMap { self.constraintsPinningView($0, axis: axis, leadMargin: leadMargin, trailingMargin: trailingMargin) }
}
/**
Creates and returns an array of `NSLayoutConstraint` objects constructed to pin `view` to its respective superview along the provided `axis`. The applied leading and trailing padding is zero.
- parameter view: The view to create the layout constraints for.
- parameter axis: The axis along which to pin `view`.
- returns: An array of `NSLayoutConstraint` objects pinning `view` along `axis`.
*/
public class func constraintsPinningView(_ view: UIView, axis: UILayoutConstraintAxis, toMargins: Bool = false) -> [NSLayoutConstraint] {
if toMargins {
let prefixString = axis == .horizontal ? "H:" : "V:"
let layoutString = prefixString + "|-[view]-|"
return NSLayoutConstraint.constraints(withVisualFormat: layoutString, options: NSLayoutFormatOptions(), metrics: nil, views: ["view" : view])
} else {
return constraintsPinningView(view, axis: axis, leadMargin: 0, trailingMargin: 0)
}
}
/**
Creates and returns an array of `NSLayoutConstraint` objects constructed to pin `view` to its respective superview along the provided `axis`. The view is given margins determined by `leadMargin` and `trailingMargin`.
- parameter view: The view to create the layout constraints for.
- parameter axis: The axis along which to pin `view`.
- parameter leadMargin: The leading margin to apply to the constraints.
- parameter trailingMargin: The trailing margin to apply to the constraints.
- returns: An array of `NSLayoutConstraint` objects pinning `view` along `axis`.
*/
public class func constraintsPinningView(_ view: UIView, axis: UILayoutConstraintAxis, leadMargin: CGFloat, trailingMargin: CGFloat) -> [NSLayoutConstraint] {
let layoutViews = ["view" : view]
let layoutMetrics = ["lead" : leadMargin, "trailing" : trailingMargin]
let prefixString = axis == .horizontal ? "H:" : "V:"
let layoutString = prefixString + "|-lead-[view]-trailing-|"
return NSLayoutConstraint.constraints(withVisualFormat: layoutString, options: NSLayoutFormatOptions(), metrics: layoutMetrics, views: layoutViews)
}
}
|
mit
|
2fc85908e9ed9fb9eacf0f95df4c070f
| 51.333333 | 221 | 0.684881 | 4.975813 | false | false | false | false |
CoderST/DYZB
|
DYZB/DYZB/Class/Home/Model/SearchRoomModel.swift
|
1
|
2047
|
//
// SearchCateModel.swift
// DYZB
//
// Created by xiudou on 2017/6/29.
// Copyright © 2017年 xiudo. All rights reserved.
//
import UIKit
class SearchRoomModel: NSObject {
var tag_id : String = ""
var short_name : String = ""
var tag_name : String = ""
var tag_introduce : String = ""
var pic_name2 : String = ""
var icon_name : String = ""
var small_icon_name : String = ""
var orderdisplay : String = ""
var rank_score : String = ""
var night_rank_score : String = ""
var nums : String = ""
var push_ios : String = ""
var push_home : String = ""
var is_game_cate : String = ""
var cate_id : String = ""
var is_del : String = ""
var push_vertical_screen : String = ""
var push_nearby : String = ""
var push_qqapp : String = ""
var broadcast_limit : String = ""
var vodd_cateids : String = ""
var open_full_screen : String = ""
var pic_url : String = ""
var pic_url2 : String = ""
var url : String = ""
var icon_url : String = ""
var small_icon_url : String = ""
var square_icon_url_w : String = ""
var square_icon_url_m : String = ""
var noRed : String = ""
var nickname : String = ""
var room_name : String = ""
var roomSrc : String = ""
var cateName : String = ""
var icon : String = ""
var nrNickname : String = ""
var avatar : String = ""
var jumpUrl : String = ""
var verticalSrc : String = ""
var room_id : Int = 0
var count : Int = 0
var shownum : Int = 0
var count_ios : Int = 0
var popularity : Int = 0
var follow : Int = 0
var isLive : Int = 0
var isVertical : Int = 0
var tagId : Int = 0
// 记录每一个ITEM的宽高
var width : CGFloat = 0
var height : CGFloat = 0
var reusableViewTitle : String = ""
init(dict : [String : Any]) {
super.init()
setValuesForKeys(dict)
}
override func setValue(_ value: Any?, forUndefinedKey key: String) {
}
}
|
mit
|
2b8f6d7bf43cddb444424c8c84115b00
| 25.337662 | 72 | 0.551775 | 3.654054 | false | false | false | false |
khillman84/music-social
|
music-social/music-social/Post.swift
|
1
|
1712
|
//
// Post.swift
// music-social
//
// Created by Kyle Hillman on 5/6/17.
// Copyright © 2017 Kyle Hillman. All rights reserved.
//
import Foundation
import Firebase
class Post {
private var _caption: String!
private var _imageUrl: String!
private var _likes: Int!
private var _postKey: String!
private var _date : String!
private var _postRef: FIRDatabaseReference!
var caption: String {
return _caption
}
var imageUrl: String {
return _imageUrl
}
var likes: Int {
return _likes
}
var postKey: String {
return _postKey
}
var date: String {
return _date
}
init(caption: String, imageUrl: String, likes: Int) {
self._caption = caption
self._imageUrl = imageUrl
self._likes = likes
}
init(postKey: String, postData: Dictionary<String, Any>) {
self._postKey = postKey
if let caption = postData["caption"] as? String {
self._caption = caption
}
if let imageUrl = postData["imageUrl"] as? String {
self._imageUrl = imageUrl
}
if let likes = postData["likes"] as? Int {
self._likes = likes
}
if let date = postData["date"] as? String {
self._date = date
}
_postRef = DataService.dataService.ref_posts.child(_postKey)
}
func adjustLikes(addLike: Bool) {
if addLike {
_likes = _likes + 1
} else {
_likes = _likes - 1
}
_postRef.child("likes").setValue(_likes)
}
}
|
mit
|
ebfdc1d6adcb9336389adfdd8bdbbfdf
| 15.61165 | 68 | 0.520748 | 4.35369 | false | false | false | false |
mcjcloud/Show-And-Sell
|
Show And Sell/BrowseCollectionViewController.swift
|
1
|
9558
|
//
// BrowseCollectionViewController.swift
// Show And Sell
//
// Created by Brayden Cloud on 2/14/17.
// Copyright © 2017 Brayden Cloud. All rights reserved.
//
import UIKit
import AVFoundation
class BrowseCollectionViewController: UICollectionViewController, StaggeredLayoutDelegate, UISearchResultsUpdating, UISearchControllerDelegate {
@IBOutlet var searchButton: UIBarButtonItem!
// MARK: Properties
var items: [Item] {
get {
return AppData.items ?? [Item]()
}
set {
AppData.items = newValue
}
}
var filteredItems = [Item]()
var loadInterval = 10
var canLoadMore = true
var searchController: UISearchController!
var refreshControl: UIRefreshControl!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
// setup search bar
searchController = SimpleSearchController(searchResultsController: nil)
searchController.searchBar.placeholder = "Filter"
searchController.searchResultsUpdater = self
searchController.hidesNavigationBarDuringPresentation = false
searchController.dimsBackgroundDuringPresentation = false
definesPresentationContext = false
// enable scrolling at all times
collectionView?.alwaysBounceVertical = true
self.collectionView?.panGestureRecognizer.require(toFail: self.navigationController!.interactivePopGestureRecognizer!)
// set delegates
searchController.delegate = self
collectionView?.delegate = self
if let layout = collectionView?.collectionViewLayout as? StaggeredLayout {
layout.delegate = self
}
// refresh control
self.refreshControl = UIRefreshControl()
self.refreshControl.backgroundColor = UIColor(colorLiteralRed: 0.871, green: 0.788, blue: 0.380, alpha: 1.0) // Gold
self.collectionView?.addSubview(self.refreshControl)
refreshControl.addTarget(self, action: #selector(handleRefresh(_:)), for: .valueChanged)
// load all items.
refreshControl.beginRefreshing()
handleRefresh(self.refreshControl)
}
override func viewWillAppear(_ animated: Bool) {
// if there is no data, refresh
if items.count == 0 {
refreshControl?.beginRefreshing()
handleRefresh(self.refreshControl!)
}
// reload the table data
self.reloadData(collectionView)
}
// MARK: Navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
print("PREPARE IN BROWSE")
if let destination = segue.destination as? ItemDetailTableViewController {
// get the item to use for details
if let item = sender as? Item {
destination.item = item
}
else if let cell = sender as? ItemCollectionViewCell {
let indexPath = (collectionView?.indexPath(for: cell))!
let item = (searchController.isActive && searchController.searchBar.text != "") ? filteredItems[indexPath.row] : items[indexPath.row]
// assign the data from the item to the fields in the destination view controller
destination.item = item
}
}
// release searchbar
if searchController.isActive {
displaySearch(searchButton)
}
}
// MARK: UICollectionViewDataSource
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
// return the size of the item array
print("number of section: \(items.count)")
return (searchController.isActive && searchController.searchBar.text != "") ? filteredItems.count : items.count
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
print("cellForItem: \(indexPath.row)")
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "itemCollectionCell", for: indexPath) as! ItemCollectionViewCell
let item = (searchController.isActive && searchController.searchBar.text != "") ? filteredItems[indexPath.row] : items[indexPath.row]
// Configure the cell
cell.backgroundColor = UIColor.black
// convert the image from encoded string to an image.
let imageData = Data(base64Encoded: item.thumbnail)
if let data = imageData {
cell.itemImageView.image = UIImage(data: data)
}
else {
cell.itemImageView.image = UIImage(named: "noimage")
}
cell.priceLabel.text = String(format: " $%.02f ", Double(item.price) ?? 0.0)
return cell
}
//MARK: CollectionView Delegate
override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
// TODO: update with searchbar
let cell = collectionView.cellForItem(at: indexPath) as! ItemCollectionViewCell
self.performSegue(withIdentifier: "browseToDetail", sender: cell)
}
// Implement to load more at bottom.
override func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
// load more items if we're displaying the last one
if indexPath.row == items.count - 1 && canLoadMore {
loadMoreItems()
canLoadMore = false
}
}
override func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
var lastVisible = false
if let cView = collectionView {
for cell in cView.visibleCells {
if cView.indexPath(for: cell)?.row ?? 0 == items.count - 1 {
lastVisible = true
}
}
canLoadMore = !lastVisible
print("didEndDecelerate, canLoadMore: \(canLoadMore)")
}
else {
canLoadMore = false
}
}
// MARK: IBAction
@IBAction func displaySearch(_ sender: UIBarButtonItem) {
if self.navigationItem.titleView == searchController.searchBar {
searchController.searchBar.text = ""
searchController.isActive = false
self.navigationItem.titleView = nil
self.navigationItem.title = "Browse"
}
else {
self.navigationItem.titleView = searchController.searchBar
searchController.searchBar.becomeFirstResponder()
}
}
// MARK: StaggeredLayout Delegate
func collectionView(_ collectionView: UICollectionView, heightForCellAt indexPath: IndexPath, with width: CGFloat) -> CGFloat {
return width
}
// MARK: Helper
// Handles a drag to refresh
func handleRefresh(_ refreshControl: UIRefreshControl) {
print("refreshing")
// get a list of all approved items in the range
HttpRequestManager.allApproved(inRange: 0, to: loadInterval) { itemsArray, response, error in
print("DATA RETURNED")
// set current items to requested items
self.items = itemsArray
// reload data on the main thread.
DispatchQueue.main.async {
self.reloadData(self.collectionView)
self.refreshControl.endRefreshing()
}
print("refresh ending")
}
}
func debugRefresh() {
let item = Item(itemId: "1324", groupId: "1234", ownerId: "1234", name: "Test item", price: "100.00", condition: "New", itemDescription: "New item", thumbnail: "12412412342", approved: true)
self.items = [item]
// reload data on the main thread.
DispatchQueue.main.async {
self.reloadData(self.collectionView)
self.refreshControl.endRefreshing()
}
}
func loadMoreItems() {
print("LOADING MORE TO BROWSE")
HttpRequestManager.allApproved(inRange: self.items.count, to: self.items.count + loadInterval) { items, response, error in
DispatchQueue.main.async {
self.items += items
// if more items were loaded, immedietely make canLoadMore true again.
if items.count > 0 {
self.canLoadMore = true
}
// reload browse
self.reloadData(self.collectionView)
self.refreshControl.endRefreshing()
}
}
}
func reloadData(_ collectionView: UICollectionView?) {
//collectionView?.collectionViewLayout.prepare()
(collectionView?.collectionViewLayout as? StaggeredLayout)?.cache = [UICollectionViewLayoutAttributes]()
collectionView?.collectionViewLayout.invalidateLayout()
collectionView?.reloadData()
}
// MARK: Filtering search results.
func filterItems(for searchText: String) {
filteredItems = items.filter {
return $0.name.lowercased().contains(searchText.lowercased())
}
}
func updateSearchResults(for searchController: UISearchController) {
print("UPDATE SEARCH RESULTS")
filterItems(for: searchController.searchBar.text!)
self.reloadData(self.collectionView)
}
}
|
apache-2.0
|
4ff7eac6cbab45fcfde273580e03c743
| 36.924603 | 198 | 0.624045 | 5.566104 | false | false | false | false |
fromkk/SlackFeedback
|
FeedbackSlack/Views/FSTextView.swift
|
1
|
1244
|
//
// FSTextView.swift
// SlackTest
//
// Created by Ueoka Kazuya on 2016/08/21.
// Copyright © 2016年 fromKK. All rights reserved.
//
import UIKit
class FSTextView: UITextView {
override init(frame: CGRect, textContainer: NSTextContainer?) {
super.init(frame: frame, textContainer: textContainer)
self.inputAccessoryView = self.toolbar
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.inputAccessoryView = self.toolbar
}
lazy var closeButton: UIBarButtonItem = {
return UIBarButtonItem(title: "close", style: UIBarButtonItem.Style.plain, target: self, action: #selector(self.closeButtonDidTapped(_:)))
}()
lazy var toolbar: UIToolbar = {
let spacer: UIBarButtonItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonItem.SystemItem.flexibleSpace, target: nil, action: nil)
let toolbar: UIToolbar = UIToolbar(frame: CGRect(x: 0.0, y: 0.0, width: UIScreen.main.bounds.size.width, height: 44.0))
toolbar.setItems([spacer, self.closeButton], animated: false)
return toolbar
}()
@objc func closeButtonDidTapped(_ button: UIBarButtonItem) {
self.resignFirstResponder()
}
}
|
mit
|
a70986cff86736f44d1655d6f13bbfb0
| 33.472222 | 146 | 0.679291 | 4.400709 | false | false | false | false |
sonsongithub/numsw
|
Sources/numsw/Matrix/MatrixRandom.swift
|
1
|
933
|
import Foundation
extension Matrix where T: FloatingPointFunctions & FloatingPoint {
public static func uniform(low: T = 0, high: T = 1, rows: Int, columns: Int) -> Matrix<T> {
let count = rows * columns
let elements = (0..<count).map { _ in _uniform(low: low, high: high) }
return Matrix<T>(rows: rows,
columns: columns,
elements: elements)
}
}
extension Matrix where T: FloatingPoint & FloatingPointFunctions & Arithmetic {
public static func normal(mu: T = 0, sigma: T = 1, rows: Int, columns: Int) -> Matrix<T> {
// Box-Muller's method
let u1 = uniform(low: T(0), high: T(1), rows: rows, columns: columns)
let u2 = uniform(low: T(0), high: T(1), rows: rows, columns: columns)
let stdNormal = sqrt(-2*log(u1)) .* cos(2*T.pi*u2)
return stdNormal*sigma + mu
}
}
|
mit
|
37931194115cb0ac65642cc800a51796
| 34.884615 | 95 | 0.562701 | 3.717131 | false | false | false | false |
lennet/proNotes
|
app/proNotes/Document/Settings Container/PageInfo/PageInfoLayerTableViewCell.swift
|
1
|
2160
|
//
// PageInfoLayerTableViewCell.swift
// proNotes
//
// Created by Leo Thomas on 11/12/15.
// Copyright © 2015 leonardthomas. All rights reserved.
//
import UIKit
protocol PageInfoLayerTableViewCellDelegate: class {
func didRemovedLayer()
}
class PageInfoLayerTableViewCell: UITableViewCell {
static let identifier = "PageInfoLayerTableViewCellIdentifier"
@IBOutlet weak var visibilityButton: UIButton!
@IBOutlet weak var indexLabel: UILabel!
@IBOutlet weak var typeLabel: UILabel!
weak var documentLayer: DocumentLayer?
weak var delegate: PageInfoLayerTableViewCellDelegate?
func setUpCell(with documentLayer: DocumentLayer) {
self.documentLayer = documentLayer
indexLabel.text = String(documentLayer.index + 1)
typeLabel.text = documentLayer.name
updateVisibilityButton()
accessibilityIdentifier = "LayerTableViewCell"
}
func updateVisibilityButton() {
guard documentLayer != nil else { return }
let buttonImageName = documentLayer!.hidden ? "invisibleIcon" : "visibleIcon"
UIView.animate(withDuration: standardAnimationDuration, delay: 0, options: UIViewAnimationOptions(), animations: {
() -> Void in
self.visibilityButton.setImage(UIImage(named: buttonImageName), for: UIControlState())
}, completion: nil)
}
// MARK: - Actions
@IBAction func handleDeleteButtonPressed(_ sender: AnyObject) {
guard documentLayer != nil else { return }
let index = documentLayer!.docPage.index
PagesTableViewController.sharedInstance?.currentPageView?.removeLayer(documentLayer!)
delegate?.didRemovedLayer()
DocumentInstance.sharedInstance.didUpdatePage(index)
}
@IBAction func handleVisibilityButtonPressed(_ sender: AnyObject) {
guard documentLayer != nil else { return }
let index = documentLayer!.docPage.index
PagesTableViewController.sharedInstance?.currentPageView?.changeLayerVisibility(documentLayer!)
updateVisibilityButton()
DocumentInstance.sharedInstance.didUpdatePage(index)
}
}
|
mit
|
cd6740e4eb6a3324be985caf9d4c738c
| 33.269841 | 122 | 0.709125 | 5.227603 | false | false | false | false |
zning1994/practice
|
Swift学习/code4xcode6/ch8/8.3.2数组拷贝2.playground/section-1.swift
|
1
|
515
|
// Playground - noun: a place where people can play
class Employee {
var name : String // 姓名
var salary : Double // 工资
init (n : String) {
name = n
salary = 0
}
}
var emps = Array<Employee>()
let emp1 = Employee(n: "Amy Lee")
let emp2 = Employee(n: "Harry Hacker")
emps.append(emp1)
emps.append(emp2)
//赋值,发生拷贝
var copyEmps = emps
let copyEmp : Employee! = copyEmps[0]
copyEmp.name = "Gary Cooper"
let emp : Employee! = emps[0]
println(emp.name)
|
gpl-2.0
|
d07d8425e7608b693d031f5b807aff6b
| 18.72 | 51 | 0.618661 | 2.883041 | false | false | false | false |
jaiversin/AppsCatalog
|
AppsCatalog/Modules/AppList/AppListViewController.swift
|
1
|
5576
|
//
// AppListViewController.swift
// AppsCatalog
//
// Created by Jhon López on 5/23/16.
// Copyright © 2016 jaiversin. All rights reserved.
//
import UIKit
import Haneke
var AppListCellIdentifier = "AppListCell"
var AppListGridCellIdentifier = "AppListGridCell"
class AppListViewController: UIViewController, AppListViewInterface, UITableViewDelegate, UITableViewDataSource, UICollectionViewDelegate, UICollectionViewDataSource {
var appListPresenter: AppListPresenter?
var dataSource: [AppListModel]?
@IBOutlet weak var noResultsButton: UIButton!
@IBOutlet var noResultsView: UIView!
@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var collectionView: UICollectionView!
@IBOutlet var detailView: UIView!
@IBOutlet weak var detailImage: UIImageView!
@IBOutlet weak var detailName: UILabel!
@IBOutlet weak var detailPrice: UILabel!
@IBOutlet weak var detailCategory: UILabel!
override func viewDidLoad() {
configureView()
// self.view = noResultsView
}
override func viewWillAppear(animated: Bool) {
self.appListPresenter?.loadAppListForCategory("")
}
func configureView(){
navigationItem.title = "Category List"
let addItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Cancel, target: self, action: #selector(AppListViewController.goBack))
navigationItem.leftBarButtonItem = addItem
}
func goBack () {
self.appListPresenter?.goBack()
}
@IBAction func closeAppList(sender: AnyObject) {
self.appListPresenter?.goBack()
}
// MARK: AppListViewInterface
func showResults(appList: [AppListModel]) {
if appList.count == 0 {
NSLog("No results")
} else {
self.dataSource = appList
self.tableView!.delegate = self
self.tableView!.dataSource = self
self.tableView!.reloadData()
self.collectionView!.delegate = self
self.collectionView!.dataSource = self
self.collectionView!.reloadData()
}
}
func showNoResults() {
NSLog("No results")
}
// MARK: TableView Datasource
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return (dataSource?.count)! | 0
}
func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return "Apps"
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let currentApp = self.dataSource?[indexPath.row]
let cell = tableView.dequeueReusableCellWithIdentifier(AppListCellIdentifier, forIndexPath: indexPath) as UITableViewCell
cell.textLabel?.text = currentApp?.name
cell.detailTextLabel?.text = currentApp?.price
return cell
}
// MARK: TableView Delegate
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let currentApp = self.dataSource?[indexPath.row]
showDetail(currentApp!)
}
// MARK: TableView Datasource
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return (dataSource?.count)!
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let currentApp = self.dataSource?[indexPath.row]
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(AppListGridCellIdentifier, forIndexPath: indexPath) as! AppListGridCell
cell.backgroundColor = UIColor.lightGrayColor()
cell.setNameLabel((currentApp?.name)!)
cell.setPriceLabel((currentApp?.price)!)
cell.setIconImage((currentApp?.iconPath)!)
return cell
}
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
let currentApp = self.dataSource?[indexPath.row]
showDetail(currentApp!)
}
@IBAction func closeDetail(sender: AnyObject) {
UIView.animateWithDuration(1.0, delay: 0.0, usingSpringWithDamping: 0.9, initialSpringVelocity: 10, options: .CurveEaseInOut, animations: {
self.detailView.center = CGPoint(x: self.view.frame.width * 2, y: self.view.frame.height * 2 )
}, completion: {_ in
let delay = 0.1 * Double(NSEC_PER_SEC)
let time = dispatch_time(DISPATCH_TIME_NOW, Int64(delay))
dispatch_after(time, dispatch_get_main_queue()) {
self.detailView.center = CGPoint(x: -500, y: -500)
}
})
}
func showDetail (model: AppListModel!) {
self.view.addSubview(self.detailView)
self.detailImage.hnk_setImageFromURL(NSURL(string:(model?.iconPath)!))
self.detailName.text = (model?.name)!
self.detailPrice.text = (model?.price)!
self.detailCategory.text = (model?.categoryName)!
UIView.animateWithDuration(1.0, delay: 0.0, usingSpringWithDamping: 0.9, initialSpringVelocity: 10, options: .CurveEaseInOut, animations: {
self.detailView.center = self.view.center
}, completion: nil)
}
}
|
mit
|
46ce77259aa7072006eccd60ebe572e5
| 32.781818 | 167 | 0.643524 | 5.253534 | false | false | false | false |
zhihuitang/Apollo
|
Apollo/RxDemoViewController.swift
|
1
|
9521
|
//
// RxDemo.swift
// Apollo
//
// Created by Zhihui Tang on 2017-04-03.
// Copyright © 2017 Zhihui Tang. All rights reserved.
//
import Foundation
import RxSwift
import RxCocoa
import UIKit
import PhotosUI
import Async
import PromiseKit
class RxDemoViewController: BaseViewController {
private let disposeBag = DisposeBag()
@IBOutlet weak var btnAsyncSwift: UIButton!
override var name: String {
return "RxSwift Demo"
}
@IBAction func rxDemo1(_ sender: Any) {
logger.d("RxSwift1")
let _ = Observable.from([1,2,3,4,5])
.flatMap({ (value) -> Observable<String> in
//
sleep(1)
let s = "A+\(value)"
logger.d("Observable flatMap: \(s)")
return Observable.just(s)
})
.subscribe(onNext: { (value) in
logger.d("got \(value)")
}, onError: { (erro) in
//
}, onCompleted: {
//
logger.d("completed😬")
}, onDisposed: {
//
})
}
@IBAction func scan(_ sender: Any) {
//fetchPhoto()
//fetchPhotoCollectionList()
fetchAssetCollection()
}
private func fetchPhoto1(){
let fetchOptions = PHFetchOptions()
let albums = PHAssetCollection.fetchAssetCollections(with: .album, subtype: .any, options: fetchOptions)
logger.d("smartAlbums count \(albums.count)")
albums.enumerateObjects({ (collection, index, stop) in
//
logger.d("index: \(index), \(collection.description)")
})
}
private func fetchAssetCollection(){
let result = PHAssetCollection.fetchAssetCollections(with: .album, subtype: .any, options: nil)
result.enumerateObjects({ (collection, index, stop) in
if let albumName = collection.localizedTitle {
logger.d("Album => \(collection.localIdentifier), \(collection.estimatedAssetCount), \(albumName) ")
}
let assResult = PHAsset.fetchAssets(in: collection, options: nil)
assResult.enumerateObjects({ (asset, index, stop) in
//print("index \(index)")
let options = PHImageRequestOptions()
options.resizeMode = .exact
let scale = UIScreen.main.scale
let dimension = CGFloat(78.0)
// 获取原图
let size = PHImageManagerMaximumSize
options.deliveryMode = .highQualityFormat
options.isSynchronous = true
PHImageManager.default().requestImage(for: asset, targetSize: size, contentMode: .default, options: options) { (image, info) in
if let name = asset.originalFilename {
logger.d("photo \(name) \(index) \(String(describing: image?.size)) ")
}
}
/*
// http://www.hangge.com/blog/cache/detail_1233.html
// 获取原图
*/
/*
PHImageManager.default().requestImageData(for: asset, options: nil, resultHandler: { (data, text, orientation, info) in
if let name = asset.originalFilename {
print("photo \(name) \(asset.localIdentifier)")
}
//
})
*/
/*
PHImageManager.default().requestImageData(for: asset, options: nil, resultHandler: { _, _, _, info in
if let name = (info!["PHImageFileURLKey"] as? NSURL)?.lastPathComponent {
print("photo \(name) \(asset.localIdentifier)")
}
})
*/
})
logger.d("finish")
})
}
private func fetchPhotoCollectionList(){
let result = PHCollectionList.fetchCollectionLists(with: .folder, subtype: .any, options: nil)
logger.d("result \(result.count)")
result.enumerateObjects({ (collectionList, index, stop) in
logger.d("title: \(String(describing: collectionList.localizedTitle))")
})
}
@IBAction func asyncSwiftDemo(_ sender: Any) {
let group = AsyncGroup()
group.background {
logger.d("This is run on the background queue")
sleep(2)
}
group.background {
logger.d("This is also run on the background queue in parallel")
sleep(5)
}
logger.d("waiting......")
group.wait()
logger.d("Both asynchronous blocks are complete")
logger.d("======================================================")
Async.userInitiated {
// 1
return 10
}.main {
// 2
logger.d("got \($0) in main")
}.background {
// 3
sleep(5)
logger.d("got \($0) in background")
}.main {
// 4
let text = "AsyncSwift \($0)"
self.btnAsyncSwift.setTitle(text, for: .normal)
logger.d("got \($0) in main")
}
}
private func fetchPhoto() {
let fetchOptions = PHFetchOptions()
let descriptor = NSSortDescriptor(key: "creationDate", ascending: true)
fetchOptions.sortDescriptors = [descriptor]
let fetchResult = PHAsset.fetchAssets(with: fetchOptions)
guard fetchResult.firstObject != nil else {
return
}
let options = PHImageRequestOptions()
options.resizeMode = .exact
let scale = UIScreen.main.scale
let dimension = CGFloat(78.0)
let size = CGSize(width: dimension * scale, height: dimension * scale)
var count = 0
fetchResult.enumerateObjects({ (asset, index, stop) in
//print("====== \(asset.description) ")
PHImageManager.default().requestImage(for: asset, targetSize: size, contentMode: .aspectFill, options: options) { (image, info) in
count = count + 1
if let name = asset.originalFilename {
logger.d("photo \(count): \(name) ")
}
}
})
}
@IBAction func rxSchedulerTest(_ sender: UIButton) {
logger.d("==UI \(Thread.current)")
Observable.create { (observer: AnyObserver<Int>) -> Disposable in
logger.d("==Observable \(Thread.current)")
observer.onNext(1)
observer.onCompleted()
return Disposables.create()
}
.subscribeOn(ConcurrentDispatchQueueScheduler(qos: .background))
//.subscribeOn(MainScheduler.instance)
.map({ (n) -> Int in
logger.d("==A \(Thread.current)")
return n + 10
})
.observeOn(MainScheduler.instance)
.map({ (m) -> String in
logger.d("==B \(Thread.current)")
return String(m)
})
.observeOn(ConcurrentDispatchQueueScheduler(qos: .utility))
.map({ (text) -> String in
logger.d("==C \(Thread.current)")
return "X" + text
})
.observeOn(MainScheduler.instance)
.subscribe(onNext: { (text) in
logger.d("==D \(Thread.current)")
logger.d("got \(text)")
}, onError: nil, onCompleted: nil, onDisposed: nil)
.addDisposableTo(disposeBag)
}
@IBAction func btnPromiseClicked(_ sender: Any) {
PHPhotoLibrary.requestAuthorization().then { authorized in
logger.d("authorized: \(authorized.rawValue)") // => true or false
}.always {
logger.d("promise finished")
}
/*
firstly {
UIApplication.shared.networkActivityIndicatorVisible = true
}.then {
return CLLocationManager.promise()
}.then { location in
let alert = UIAlertView()
alert.addButton(title: "Proceed!")
alert.addButton(title: "Proceed, but fastest!")
alert.cancelButtonIndex = alert.addButton("Cancel")
return alert.promise()
}.then { dismissedButtonIndex in
//… cancel wasn't pressed
}.always {
// *still* runs if the promise was cancelled
UIApplication.shared.networkActivityIndicatorVisible = false
}.catch { error in
//… cancel wasn't pressed
}
*/
}
}
extension PHAsset {
var originalFilename: String? {
var fname:String?
if #available(iOS 9.0, *) {
let resources = PHAssetResource.assetResources(for: self)
if let resource = resources.first {
fname = resource.originalFilename
}
}
if fname == nil {
// this is an undocumented workaround that works as of iOS 9.1
fname = self.value(forKey: "filename") as? String
}
return fname
}
}
|
apache-2.0
|
d2d9cc3b5dd7c246aa0c1d5b805f0558
| 32.558304 | 143 | 0.505528 | 5.226747 | false | false | false | false |
pigigaldi/Pock
|
Pock/UI/Manager/Controllers/WidgetsInstallViewController/WidgetsInstallViewController.swift
|
1
|
14670
|
//
// WidgetsInstallViewController.swift
// Pock
//
// Created by Pierluigi Galdi on 04/05/21.
//
import Cocoa
// swiftlint:disable file_length
class WidgetsInstallViewController: NSViewController {
// MARK: UI Elements
@IBOutlet private weak var iconView: NSImageView!
@IBOutlet private weak var titleLabel: NSTextField!
@IBOutlet private weak var bodyLabel: NSTextField!
@IBOutlet private weak var progressBar: NSProgressIndicator!
@IBOutlet private weak var changelogStackView: NSStackView!
@IBOutlet private weak var changelogTitleLabel: NSTextField!
@IBOutlet private weak var changelogTextView: NSTextView!
@IBOutlet private weak var cancelButton: NSButton!
@IBOutlet private weak var actionButton: NSButton!
// MARK: State
internal var state: WidgetsInstaller.State = .dragdrop {
didSet {
if isViewLoaded {
updateUIElementsForInstallableWidget()
}
}
}
// MARK: Overrides
override func viewDidLoad() {
super.viewDidDisappear()
configureUIElements()
updateUIElementsForInstallableWidget()
}
override func viewWillAppear() {
super.viewWillAppear()
NSApp.activate(ignoringOtherApps: true)
}
override func viewWillDisappear() {
super.viewWillDisappear()
NSApp.deactivate()
}
deinit {
Roger.debug("[WidgetsManager][Install] - deinit")
}
// MARK: Methods
private func configureUIElements() {
view.window?.styleMask.remove(.resizable)
progressBar.minValue = 0
progressBar.maxValue = 1
changelogTitleLabel.stringValue = "widget.update.changelog.title".localized
}
private func toggleChangelogVisibility(_ visible: Bool, title: String? = nil) {
changelogTitleLabel.stringValue = visible ? "widget.update.changelog.title".localized : (title ?? "")
changelogTitleLabel.isHidden = !visible && title == nil
changelogTextView.enclosingScrollView?.isHidden = !visible
changelogStackView.isHidden = changelogTitleLabel.isHidden
}
private func toggleProgressBarStyle(isIndeterminated: Bool, progress: Double = 0) {
defer {
progressBar.isHidden = false
}
if isIndeterminated {
progressBar.doubleValue = 0
progressBar.isIndeterminate = true
progressBar.startAnimation(nil)
} else {
progressBar.stopAnimation(nil)
progressBar.doubleValue = progress
progressBar.isIndeterminate = false
}
}
// swiftlint:disable cyclomatic_complexity
// swiftlint:disable function_body_length
private func updateUIElementsForInstallableWidget() {
// MARK: State
defer {
setupDraggingHandler()
actionButton.bezelColor = NSColor.controlAccentColor
}
switch state {
case .installDefault:
// MARK: Install default widgets
titleLabel.stringValue = "widget.install.default.title".localized
bodyLabel.stringValue = "widget.install.default.body".localized
progressBar.isHidden = true
toggleChangelogVisibility(false)
cancelButton.title = "general.action.cancel".localized
actionButton.title = "general.action.start".localized
actionButton.isEnabled = true
case .installingDefault(let progress):
// MARK: Installing default widgets
titleLabel.stringValue = "widget.installing.title".localized(progress.name)
bodyLabel.stringValue = "widget.installing.default.body".localized(progress.processed, progress.total)
toggleProgressBarStyle(isIndeterminated: false, progress: progress.progress)
toggleChangelogVisibility(false)
cancelButton.title = "general.action.cancel".localized
actionButton.title = "general.action.downloading".localized
actionButton.isEnabled = false
case .installedDefault(let errors):
// MARK: Installed default widgets
if let errors = errors {
titleLabel.stringValue = "widget.error.title".localized
bodyLabel.stringValue = "widget.error.body".localized(errors)
} else {
titleLabel.stringValue = "widget.install.success.title".localized
bodyLabel.stringValue = "widget.installed.default.success.body".localized
}
actionButton.title = "general.action.relaunch".localized
progressBar.isHidden = true
toggleChangelogVisibility(false)
#if DEBUG
cancelButton.isHidden = false
cancelButton.isEnabled = true
#else
cancelButton.isHidden = true
#endif
actionButton.isEnabled = true
case .dragdrop:
// MARK: Drag&Drop
titleLabel.stringValue = "widget.install.drag-here.title".localized
bodyLabel.stringValue = "widget.install.drag-here.body".localized
progressBar.isHidden = true
toggleChangelogVisibility(false, title: "widget.install.drag-here.valid-formats".localized)
cancelButton.title = "general.action.cancel".localized
actionButton.title = "general.action.choose".localized
actionButton.isEnabled = true
case .remove(let widget):
// MARK: Uninstall
titleLabel.stringValue = "widget.remove.title".localized(widget.name)
bodyLabel.stringValue = "widget.remove.body".localized(widget.name)
progressBar.isHidden = true
toggleChangelogVisibility(false, title: "widget.remove.click-to-continue".localized)
cancelButton.title = "general.action.cancel".localized
actionButton.title = "general.action.remove".localized
actionButton.isEnabled = true
case .install(let widget):
// MARK: Install
titleLabel.stringValue = "widget.install.title".localized(widget.name)
bodyLabel.stringValue = "widget.install.body".localized(widget.name)
progressBar.isHidden = true
toggleChangelogVisibility(false, title: "widget.install.click-to-continue".localized)
cancelButton.title = "general.action.cancel".localized
actionButton.title = "general.action.install".localized
actionButton.isEnabled = true
case .installArchive(let url):
// MARK: Install (archive)
let name = url.deletingPathExtension().lastPathComponent
titleLabel.stringValue = "widget.install.title".localized(name)
bodyLabel.stringValue = "widget.install.body".localized(name)
progressBar.isHidden = true
toggleChangelogVisibility(false, title: "widget.install.click-to-continue".localized)
cancelButton.title = "general.action.cancel".localized
actionButton.title = "general.action.install".localized
actionButton.isEnabled = true
case .update(let widget, let version):
// MARK: Update
titleLabel.stringValue = "widget.update.title".localized(widget.name)
bodyLabel.stringValue = "widget.update.body".localized(widget.fullVersion, version.name)
progressBar.isHidden = true
toggleChangelogVisibility(true)
changelogTextView.string = version.changelog
cancelButton.title = "general.action.later".localized
actionButton.title = "general.action.update".localized
actionButton.isEnabled = true
case .removing(let widget):
// MARK: Uninstalling
titleLabel.stringValue = "widget.removing.title".localized(widget.name)
bodyLabel.stringValue = "widget.removing.body".localized
toggleProgressBarStyle(isIndeterminated: true)
toggleChangelogVisibility(false)
cancelButton.title = "general.action.cancel".localized
actionButton.title = "general.action.removing".localized
actionButton.isEnabled = false
case .installing(let widget):
// MARK: Installing
titleLabel.stringValue = "widget.installing.title".localized(widget.name)
bodyLabel.stringValue = "widget.installing.body".localized
toggleProgressBarStyle(isIndeterminated: true)
toggleChangelogVisibility(false)
cancelButton.title = "general.action.cancel".localized
actionButton.title = "general.action.installing".localized
actionButton.isEnabled = false
case .downloading(let widget, let progress):
// MARK: Downloading
titleLabel.stringValue = "widget.downloading.title".localized(widget.name)
bodyLabel.stringValue = "widget.downloading.body".localized
toggleProgressBarStyle(isIndeterminated: false, progress: progress)
toggleChangelogVisibility(false)
cancelButton.title = "general.action.cancel".localized
actionButton.title = "general.action.downloading".localized
actionButton.isEnabled = false
case .error(let error):
// MARK: Error
titleLabel.stringValue = "widget.error.title".localized
bodyLabel.stringValue = "widget.error.body".localized(error.description)
progressBar.isHidden = true
toggleChangelogVisibility(false)
cancelButton.isHidden = true
actionButton.title = "general.action.close".localized
actionButton.isEnabled = true
case .removed(let widget), .installed(let widget), .updated(let widget):
switch state {
case .removed:
// MARK: Removed
titleLabel.stringValue = "widget.remove.success.title".localized
bodyLabel.stringValue = "widget.remove.success.body".localized(widget.name)
actionButton.title = "general.action.relaunch".localized
case .installed:
// MARK: Installed
titleLabel.stringValue = "widget.install.success.title".localized
bodyLabel.stringValue = "widget.install.success.body".localized(widget.name)
actionButton.title = "general.action.relaunch".localized
case .updated:
// MARK: Updated
titleLabel.stringValue = "widget.update.success.title".localized
bodyLabel.stringValue = "widget.update.success.body".localized(widget.name)
actionButton.title = "general.action.relaunch".localized
default:
return
}
progressBar.isHidden = true
toggleChangelogVisibility(false)
cancelButton.isHidden = true
actionButton.isEnabled = true
}
}
// MARK: Did select action
@IBAction private func didSelectButton(_ button: NSButton) {
// MARK: Actions
switch button {
case actionButton:
switch state {
case .installDefault:
// MARK: Install default widgets
installDefaultWidgets()
case .dragdrop:
// MARK: Drag&Drop
chooseWidgetFile()
case let .remove(widget):
// MARK: Uninstall
state = .removing(widget: widget)
WidgetsInstaller().uninstallWidget(widget) { [weak self] error in
if let error = error {
self?.state = .error(error)
} else {
self?.state = .removed(widget: widget)
}
}
case let .install(widget):
// MARK: Install
#if DEBUG
let removeSource = true
#else
let removeSource = false
#endif
state = .installing(widget: widget)
WidgetsInstaller().installWidget(widget, removeSource: removeSource) { [weak self] _, error in
if let error = error {
self?.state = .error(error)
} else {
self?.state = .installed(widget: widget)
}
}
case let .installArchive(url):
// MARK: Install (archive)
#if DEBUG
let removeSource = true
#else
let removeSource = false
#endif
let name = url.deletingPathExtension().lastPathComponent
WidgetsInstaller().extractAndInstall(name, atLocation: url, removeSource: removeSource) { [weak self] widget, error in
if let error = error {
self?.state = .error(error)
} else if let widget = widget {
self?.state = .installed(widget: widget)
} else {
self?.state = .error(WidgetsInstallerError.invalidBundle(reason: nil))
}
}
case let .update(widget, version):
// MARK: Update
state = .downloading(widget: widget, progress: 0)
WidgetsInstaller().updateWidget(
widget,
version: version,
progress: { [weak self] progress in
self?.state = .downloading(widget: widget, progress: progress)
},
completion: { [weak self] _, error in
if let error = error {
self?.state = .error(error)
} else {
self?.state = .updated(widget: widget)
}
}
)
case .installed, .installedDefault:
// MARK: Relaunch on default widgets installation
AppController.shared.relaunch()
case .removed, .updated:
// MARK: Relaunch
dismiss(nil)
async {
AppController.shared.relaunch()
}
case .error:
// MARK: Error
dismiss(nil)
default:
return
}
case cancelButton:
dismiss(nil)
default:
return
}
}
// swiftlint:enable function_body_length
// swiftlint:enable cyclomatic_complexity
}
extension WidgetsInstallViewController {
// MARK: Install default widgets
private func installDefaultWidgets() {
WidgetsInstaller().installDefaultWidgets(
progress: { [weak self] (widgetName, _, processed, total) in
self?.state = .installingDefault((widgetName, Double(processed) / Double(total), processed, total))
},
completion: { [weak self] errors in
var errorStrings: String?
if errors.values.contains(where: { $0 != nil }) {
errorStrings = ""
for (key, value) in errors {
if let error = value {
errorStrings? += "\(key) \("base.widget".localized): \(error.description)\n"
}
}
}
self?.state = .installedDefault(errorStrings)
})
}
// MARK: Choose / Drag&Drop
private func setupDraggingHandler() {
guard let view = self.view as? DestinationView else {
return
}
switch state {
case .dragdrop:
view.canAcceptDraggedElement = true
view.completion = { [weak self] path in
self?.handleFileAtPath(path)
}
default:
view.canAcceptDraggedElement = false
view.completion = nil
}
}
private func chooseWidgetFile() {
guard let window = self.view.window else {
return
}
let openPanel = NSOpenPanel()
openPanel.directoryURL = FileManager.default.urls(for: .downloadsDirectory, in: .localDomainMask).first
openPanel.canChooseDirectories = true
openPanel.canChooseFiles = true
openPanel.allowsMultipleSelection = false
openPanel.allowedFileTypes = ["pock", "pkarchive"]
openPanel.beginSheetModal(for: window, completionHandler: { [weak self] result in
if result == NSApplication.ModalResponse.OK {
guard let self = self else {
return
}
if let path = openPanel.url {
self.handleFileAtPath(path)
} else {
self.state = .error(WidgetsInstallerError.invalidBundle(reason: "error.unknown".localized))
}
}
})
}
private func handleFileAtPath(_ path: URL) {
var pathURL: URL = path
if path.scheme == nil {
pathURL = URL(fileURLWithPath: path.path)
}
switch pathURL.pathExtension {
case "pock":
do {
let widget = try PKWidgetInfo(path: pathURL)
self.state = .install(widget: widget)
} catch {
Roger.error(error)
self.state = .error(WidgetsInstallerError.invalidBundle(reason: error.localizedDescription))
}
case "pkarchive":
self.state = .installArchive(url: pathURL)
default:
self.state = .error(WidgetsInstallerError.invalidBundle(reason: "error.unknown".localized))
}
}
}
// swiftlint:enable file_length
|
mit
|
5538423f395a69516d7037fe4facb8af
| 32.416856 | 122 | 0.713701 | 3.910957 | false | false | false | false |
gribozavr/swift
|
test/Driver/filelists.swift
|
2
|
5262
|
// UNSUPPORTED: windows
// RUN: %empty-directory(%t)
// RUN: touch %t/a.swift %t/b.swift %t/c.swift
// RUN: (cd %t && %swiftc_driver_plain -driver-use-frontend-path %S/Inputs/filelists/check-filelist-abc.py -emit-module ./a.swift ./b.swift ./c.swift -module-name main -target x86_64-apple-macosx10.9 -driver-filelist-threshold=0 -output-file-map=%S/Inputs/filelists/output.json 2>&1 | %FileCheck %s)
// CHECK-NOT: Handled
// CHECK: Handled a.swift
// CHECK-NEXT: Supplementary swiftdoc: "./a.swiftdoc"
// CHECK-NEXT: Supplementary swiftmodule: "./a.swiftmodule"
// CHECK-NEXT: Supplementary swiftsourceinfo: "./a.swiftsourceinfo"
// CHECK-NEXT: Supplementary "./a.swift":
// CHECK-NEXT: Handled b.swift
// CHECK-NEXT: Supplementary swiftdoc: "./b.swiftdoc"
// CHECK-NEXT: Supplementary swiftmodule: "./b.swiftmodule"
// CHECK-NEXT: Supplementary swiftsourceinfo: "./b.swiftsourceinfo"
// CHECK-NEXT: Supplementary "./b.swift":
// CHECK-NEXT: Handled c.swift
// CHECK-NEXT: Supplementary swiftdoc: "./c.swiftdoc"
// CHECK-NEXT: Supplementary swiftmodule: "./c.swiftmodule"
// CHECK-NEXT: Supplementary swiftsourceinfo: "./c.swiftsourceinfo"
// CHECK-NEXT: Supplementary "./c.swift":
// CHECK-NEXT: Handled modules
// CHECK-NOT: Handled
// RUN: %swiftc_driver_plain -driver-use-frontend-path %S/Inputs/filelists/check-filelist-abc.py -c %t/a.swift %t/b.swift %t/c.swift -module-name main -target x86_64-apple-macosx10.9 -driver-filelist-threshold=0 -force-single-frontend-invocation 2>&1 | %FileCheck -check-prefix=CHECK-WMO %s
// CHECK-WMO-NOT: Handled
// CHECK-WMO: Handled all
// CHECK-WMO: Supplementary object: "main.o"
// CHECK-WMO: Supplementary "{{.*}}/a.swift":
// CHECK-WMO-NOT: output
// CHECK-WMO-NOT: Handled
// RUN: %empty-directory(%t/bin)
// RUN: ln -s %S/Inputs/filelists/fake-ld.py %t/bin/ld
// RUN: (cd %t && %swiftc_driver_plain -driver-use-frontend-path %S/Inputs/filelists/check-filelist-abc.py -c ./a.swift ./b.swift ./c.swift -module-name main -target x86_64-apple-macosx10.9 -driver-filelist-threshold=0 -output-file-map=%S/Inputs/filelists/output.json -force-single-frontend-invocation -num-threads 1 2>&1 | %FileCheck -check-prefix=CHECK-WMO-THREADED %s)
// RUN: (cd %t && %swiftc_driver_plain -driver-use-frontend-path %S/Inputs/filelists/check-filelist-abc.py -c ./a.swift ./b.swift ./c.swift -module-name main -target x86_64-apple-macosx10.9 -driver-filelist-threshold=0 -output-file-map=%S/Inputs/filelists/output.json -force-single-frontend-invocation -num-threads 1 -embed-bitcode 2>&1 | %FileCheck -check-prefix=CHECK-WMO-THREADED %s)
// RUN: %empty-directory(%t/tmp)
// RUN: (cd %t && env TMPDIR="%t/tmp/" %swiftc_driver_plain -driver-use-frontend-path %S/Inputs/filelists/check-filelist-abc.py -c ./a.swift ./b.swift ./c.swift -module-name main -target x86_64-apple-macosx10.9 -driver-filelist-threshold=0 -output-file-map=%S/Inputs/filelists/output.json -force-single-frontend-invocation -num-threads 1 -save-temps 2>&1 | %FileCheck -check-prefix=CHECK-WMO-THREADED %s)
// RUN: ls %t/tmp/sources-* %t/tmp/outputs-*
// CHECK-WMO-THREADED-NOT: Handled
// CHECK-WMO-THREADED: Handled all
// CHECK-WMO-THREADED-NEXT: Supplementary {{object|llvm-bc}}: "{{.*}}/a.{{o|bc}}"
// CHECK-WMO-THREADED-NEXT: Supplementary {{object|llvm-bc}}: "{{.*}}/b.{{o|bc}}"
// CHECK-WMO-THREADED-NEXT: Supplementary {{object|llvm-bc}}: "{{.*}}/c.{{o|bc}}"
// CHECK-WMO-THREADED-NEXT: Supplementary "{{.*}}/a.swift":
// CHECK-WMO-THREADED-NEXT: Supplementary "{{.*}}/b.swift":
// CHECK-WMO-THREADED-NEXT: Supplementary "{{.*}}/c.swift":
// CHECK-WMO-THREADED-NEXT: ...with output!
// CHECK-WMO-THREADED-NOT: Handled
// RUN: mkdir -p %t/tmp-fail/
// RUN: (cd %t && env TMPDIR="%t/tmp-fail/" not %swiftc_driver_plain -driver-use-frontend-path %S/Inputs/fail.py -c ./a.swift ./b.swift ./c.swift -module-name main -target x86_64-apple-macosx10.9 -driver-filelist-threshold=0 -output-file-map=%S/Inputs/filelists/output.json -force-single-frontend-invocation -num-threads 1)
// RUN: not ls %t/tmp-fail/sources-*
// RUN: not ls %t/tmp-fail/outputs-*
// RUN: mkdir -p %t/tmp-crash/
// RUN: (cd %t && env TMPDIR="%t/tmp-crash/" not %swiftc_driver_plain -driver-use-frontend-path %S/Inputs/crash.py -c ./a.swift ./b.swift ./c.swift -module-name main -target x86_64-apple-macosx10.9 -driver-filelist-threshold=0 -output-file-map=%S/Inputs/filelists/output.json -force-single-frontend-invocation -num-threads 1)
// RUN: ls %t/tmp-crash/sources-* %t/tmp-crash/outputs-*
// RUN: (cd %t && env PATH="%t/bin/:$PATH" %swiftc_driver_plain -driver-use-frontend-path %S/Inputs/filelists/check-filelist-abc.py -emit-library ./a.swift ./b.swift ./c.swift -module-name main -target x86_64-apple-macosx10.9 -driver-filelist-threshold=0 -output-file-map=%S/Inputs/filelists/output.json 2>&1 | %FileCheck -check-prefix=CHECK-LINK %s)
// RUN: (cd %t && env PATH="%t/bin/:$PATH" %swiftc_driver_plain -driver-use-frontend-path %S/Inputs/filelists/check-filelist-abc.py -emit-library ./a.swift ./b.swift ./c.swift -module-name main -target x86_64-apple-macosx10.9 -driver-filelist-threshold=0 -output-file-map=%S/Inputs/filelists/output.json -force-single-frontend-invocation -num-threads 1 2>&1 | %FileCheck -check-prefix=CHECK-LINK %s)
// CHECK-LINK: Handled link
|
apache-2.0
|
f34fc65d4f4b084de3dd7bfdb42c9f12
| 72.083333 | 404 | 0.714177 | 2.976244 | false | false | true | false |
nostramap/nostra-sdk-sample-ios
|
SearchSample/Swift/SearchSample/MapResultViewController.swift
|
1
|
3264
|
//
// MapResultViewController.swift
// SearchSample
//
// Copyright © 2559 Globtech. All rights reserved.
//
import UIKit
import NOSTRASDK
import ArcGIS
class MapResultViewController: UIViewController, AGSLayerDelegate, AGSCalloutDelegate, AGSMapViewLayerDelegate {
let referrer = ""
@IBOutlet weak var mapView: AGSMapView!
var result: NTLocationSearchResult!;
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.initializeMap();
}
//MARK: Callout delegate
func callout(_ callout: AGSCallout!, willShowFor feature: AGSFeature!, layer: AGSLayer!, mapPoint: AGSPoint!) -> Bool {
callout.title = result!.name_L;
callout.detail = "\(result!.adminLevel3_L), \(result!.adminLevel2_L), \(result!.adminLevel1_L)"
return true;
}
//MARK: layer delegate
func layerDidLoad(_ layer: AGSLayer!) {
if result != nil {
let point = AGSPoint(x: result.lon, y: result.lat, spatialReference: AGSSpatialReference.wgs84());
let mappoint = AGSPoint(fromDegreesDecimalMinutesString: point?.decimalDegreesString(withNumDigits: 7),
with: AGSSpatialReference.webMercator());
mapView.zoom(toScale: 10000, withCenter: mappoint, animated: true);
let graphicLayer = AGSGraphicsLayer();
mapView.addMapLayer(graphicLayer);
let symbol = AGSPictureMarkerSymbol(imageNamed: "pin_map");
let graphic = AGSGraphic(geometry: mappoint, symbol: symbol, attributes: nil);
graphicLayer.addGraphic(graphic);
mapView.callout.show(at: mappoint, for: graphic, layer: graphicLayer, animated: true);
}
}
func initializeMap() {
mapView.callout.delegate = self;
do {
// Get map permisson.
let resultSet = try NTMapPermissionService.execute();
// Get Street map HD (service id: 2)
if resultSet.results != nil && resultSet.results.count > 0 {
let filtered = resultSet.results.filter({ (mp) -> Bool in
return mp.serviceId == 2;
})
if filtered.count > 0 {
let mapPermisson = filtered.first;
let url = URL(string: mapPermisson!.serviceUrl_L);
let cred = AGSCredential(token: mapPermisson?.serviceToken_L, referer: referrer);
let tiledLayer = AGSTiledMapServiceLayer(url: url, credential: cred)
tiledLayer?.delegate = self;
mapView.addMapLayer(tiledLayer, withName: mapPermisson!.serviceName);
}
}
}
catch let error as NSError {
print("error: \(error)");
}
}
func layer(_ layer: AGSLayer!, didFailToLoadWithError error: Error!) {
print("\(layer.name) failed to load by reason: \(error)");
}
}
|
apache-2.0
|
9534cc3df218f8bdb8287fab9c93e908
| 32.639175 | 123 | 0.560527 | 5.122449 | false | false | false | false |
k0nserv/SwiftTracer
|
Pods/SwiftTracer-Core/Sources/Misc/Color.swift
|
1
|
2722
|
//
// Color.swift
// SwiftTracer
//
// Created by Hugo Tunius on 09/08/15.
// Copyright © 2015 Hugo Tunius. All rights reserved.
//
#if os(Linux)
import Glibc
#else
import Darwin.C
#endif
public typealias Color = UInt32
public extension Color {
public static let Black = Color(r: 0.0, g: 0.0, b: 0.0)
public var r: UInt8 {
get {
return UInt8((self & 0x000000FF) >> 0)
}
}
public var g: UInt8 {
get {
return UInt8((self & 0x0000FF00) >> 8)
}
}
public var b: UInt8 {
get {
return UInt8((self & 0x00FF0000) >> 16)
}
}
public var a: UInt8 {
get {
return UInt8((self & 0xFF000000) >> 24)
}
}
public var rd: Double {
get {
return Double(r) / 255.0
}
}
public var gd: Double {
get {
return Double(g) / 255.0
}
}
public var bd: Double {
get {
return Double(b) / 255.0
}
}
public init(r: UInt8, g: UInt8, b: UInt8) {
self = 0xFF000000
self = self | UInt32(r) << 0
self = self | UInt32(g) << 8
self = self | UInt32(b) << 16
}
public init(r: Double, g: Double, b: Double) {
let rNormalized = Color.clampValue(Int32(255.0 * r))
let gNormalized = Color.clampValue(Int32(255.0 * g))
let bNormalized = Color.clampValue(Int32(255.0 * b))
self.init(r: rNormalized,
g: gNormalized,
b: bNormalized)
}
public init(_ color: UInt32) {
self = color
}
private static func clampValue(value: Int32) -> UInt8 {
if value < 0 {
return 0
}
if value > UINT8_MAX {
return UInt8(UINT8_MAX)
}
return UInt8(value)
}
}
public func *(left: Color, right: Double) -> Color {
return Color(r: Color.clampValue(Int32(Double(left.r) * right)),
g: Color.clampValue(Int32(Double(left.g) * right)),
b: Color.clampValue(Int32(Double(left.b) * right)))
}
public func *(left: Color, right: Color) -> Color {
return Color(r: left.rd * right.rd, g: left.gd * right.gd, b: left.bd * right.bd)
}
public func +(left: Color, right: Color) -> Color {
return Color(r: Color.clampValue(Int32(left.r) + Int32(right.r)), g: Color.clampValue(Int32(left.g) + Int32(right.g)) , b: Color.clampValue(Int32(left.b) + Int32(right.b)))
}
public func -(left: Color, right: Color) -> Color {
return Color(r: Color.clampValue(Int32(left.r) - Int32(right.r)), g: Color.clampValue(Int32(left.g) - Int32(right.g)) , b: Color.clampValue(Int32(left.b) - Int32(right.b)))
}
|
mit
|
63b3cb54a88b241c93298057dde2f187
| 22.66087 | 176 | 0.54208 | 3.201176 | false | false | false | false |
rudkx/swift
|
test/SILGen/existential_parameters.swift
|
1
|
10955
|
// RUN: %target-swift-emit-silgen -module-name parameterized -enable-parameterized-protocol-types %s | %FileCheck %s
protocol P<T, U, V> {}
protocol Q<X, Y, Z> : P {}
struct S: Q {
typealias T = Int
typealias U = String
typealias V = Float
typealias X = Int
typealias Y = String
typealias Z = Float
}
// CHECK-LABEL: sil hidden [ossa] @$s13parameterized6upcastyAA1P_pAA1SVF : $@convention(thin) (S) -> @out P {
func upcast(_ x: S) -> any P {
// CHECK: bb0([[RESULT_PARAM:%.*]] : $*P, [[CONCRETE_VAL:%.*]] : $S):
// CHECK: [[Q_INT_STRING_FLOAT:%.*]] = alloc_stack $Q<Int, String, Float>
// CHECK: [[INIT_Q_INT_STRING_FLOAT:%.*]] = init_existential_addr [[Q_INT_STRING_FLOAT]] : $*Q<Int, String, Float>, $S
// CHECK: store [[CONCRETE_VAL]] to [trivial] [[INIT_Q_INT_STRING_FLOAT]] : $*S
// CHECK: [[OPEN_Q_INT_STRING_FLOAT:%.*]] = open_existential_addr immutable_access [[Q_INT_STRING_FLOAT]] : $*Q<Int, String, Float> to $*[[OPENED_Q_INT_STRING_FLOAT:@opened(.*) Q<Int, String, Float>]]
// CHECK: [[RESULT_INIT:%.*]] = init_existential_addr [[RESULT_PARAM]] : $*P, $[[OPENED_Q_INT_STRING_FLOAT]]
// CHECK: copy_addr [[OPEN_Q_INT_STRING_FLOAT]] to [initialization] [[RESULT_INIT]] : $*[[OPENED_Q_INT_STRING_FLOAT]]
return x as any Q<Int, String, Float> as any P
}
// CHECK-LABEL: sil hidden [ossa] @$s13parameterized12upupupupcastyAA1P_pAA1SVF : $@convention(thin) (S) -> @out P {
func upupupupcast(_ x: S) -> any P {
// CHECK: bb0([[RESULT_PARAM:%.*]] : $*P, [[CONCRETE_VAL:%.*]] : $S):
// CHECK: [[P_INT_STRING_FLOAT:%.*]] = alloc_stack $P<Int, String, Float>
// CHECK: [[INIT_INT_STRING_FLOAT:%.*]] = init_existential_addr [[P_INT_STRING_FLOAT]] : $*P<Int, String, Float>, $S
// CHECK: store [[CONCRETE_VAL]] to [trivial] [[INIT_INT_STRING_FLOAT]] : $*S
// CHECK: [[OPEN_INT_STRING_FLOAT:%.*]] = open_existential_addr immutable_access %3 : $*P<Int, String, Float> to $*[[OPENED_P_INT_STRING_FLOAT:@opened(.*) P<Int, String, Float>]]
// CHECK: [[P_INT_STRING:%.*]] = alloc_stack $P<Int, String>
// CHECK: [[INIT_INT_STRING:%.*]] = init_existential_addr [[P_INT_STRING]] : $*P<Int, String>, $[[OPENED_P_INT_STRING_FLOAT]]
// CHECK: copy_addr [[OPEN_INT_STRING_FLOAT]] to [initialization] [[INIT_INT_STRING]] : $*[[OPENED_P_INT_STRING_FLOAT]]
// CHECK: [[OPEN_INT_STRING:%.*]] = open_existential_addr immutable_access [[P_INT_STRING]] : $*P<Int, String> to $*[[OPENED_P_INT_STRING:@opened(.*) P<Int, String>]]
// CHECK: [[P_INT:%.*]] = alloc_stack $P<Int>
// CHECK: [[INIT_INT:%.*]] = init_existential_addr [[P_INT]] : $*P<Int>, $[[OPENED_P_INT_STRING]]
// CHECK: copy_addr [[OPEN_INT_STRING]] to [initialization] [[INIT_INT]] : $*[[OPENED_P_INT_STRING]]
// CHECK: [[OPEN_INT:%.*]] = open_existential_addr immutable_access [[P_INT]] : $*P<Int> to $*[[OPENED_P_INT:@opened(.*) P<Int>]]
// CHECK: [[RESULT_INIT:%.*]] = init_existential_addr [[RESULT_PARAM]] : $*P, $[[OPENED_P_INT]]
// CHECK: copy_addr [[OPEN_INT]] to [initialization] [[RESULT_INIT]] : $*[[OPENED_P_INT]]
return x as any P<Int, String, Float> as any P<Int, String> as any P<Int> as any P
}
func use(_ k: (S) -> Void) {}
// CHECK-LABEL: sil hidden [ossa] @$s13parameterized11upcastInputyyF : $@convention(thin) () -> () {
func upcastInput() {
// CHECK: [[INT_STRING_FN:%.*]] = function_ref @$s13parameterized11upcastInputyyFyAA1P_pySiSSXPXEfU_ : $@convention(thin) (@in_guaranteed P<Int, String>) -> ()
// CHECK: [[NOESCAPE_INT_STRING_FN:%.*]] = convert_function [[INT_STRING_FN]] : $@convention(thin) (@in_guaranteed P<Int, String>) -> () to $@convention(thin) @noescape (@in_guaranteed P<Int, String>) -> ()
// CHECK: [[THICK_INT_STRING_FN:%.*]] = thin_to_thick_function [[NOESCAPE_INT_STRING_FN]] : $@convention(thin) @noescape (@in_guaranteed P<Int, String>) -> () to $@noescape @callee_guaranteed (@in_guaranteed P<Int, String>) -> ()
// CHECK: [[S_TO_INT_STRING_THUNK_FN:%.*]] = function_ref @$s13parameterized1P_pySiSSXPIgn_AA1SVIegy_TR : $@convention(thin) (S, @noescape @callee_guaranteed (@in_guaranteed P<Int, String>) -> ()) -> ()
// CHECK: [[PARTIAL_INT_STRING_THUNK_FN:%.*]] = partial_apply [callee_guaranteed] [[S_TO_INT_STRING_THUNK_FN]]([[THICK_INT_STRING_FN]]) : $@convention(thin) (S, @noescape @callee_guaranteed (@in_guaranteed P<Int, String>) -> ()) -> ()
// CHECK: [[NOESCAPE_INT_STRING_THUNK_FN:%.*]] = convert_escape_to_noescape [not_guaranteed] [[PARTIAL_INT_STRING_THUNK_FN]] : $@callee_guaranteed (S) -> () to $@noescape @callee_guaranteed (S) -> ()
// CHECK: [[USE_FN:%.*]] = function_ref @$s13parameterized3useyyyAA1SVXEF : $@convention(thin) (@noescape @callee_guaranteed (S) -> ()) -> ()
// CHECK: {{%.*}} = apply [[USE_FN]]([[NOESCAPE_INT_STRING_THUNK_FN]]) : $@convention(thin) (@noescape @callee_guaranteed (S) -> ()) -> ()
use({ (p: any P<Int, String>) -> Void in })
// CHECK: [[INT_FN:%.*]] = function_ref @$s13parameterized11upcastInputyyFyAA1P_pySiXPXEfU0_ : $@convention(thin) (@in_guaranteed P<Int>) -> ()
// CHECK: [[NOESCAPE_INT_FN:%.*]] = convert_function [[INT_FN]] : $@convention(thin) (@in_guaranteed P<Int>) -> () to $@convention(thin) @noescape (@in_guaranteed P<Int>) -> ()
// CHECK: [[THICK_INT_FN:%.*]] = thin_to_thick_function [[NOESCAPE_INT_FN]] : $@convention(thin) @noescape (@in_guaranteed P<Int>) -> () to $@noescape @callee_guaranteed (@in_guaranteed P<Int>) -> ()
// CHECK: [[S_TO_INT_THUNK_FN:%.*]] = function_ref @$s13parameterized1P_pySiXPIgn_AA1SVIegy_TR : $@convention(thin) (S, @noescape @callee_guaranteed (@in_guaranteed P<Int>) -> ()) -> ()
// CHECK: [[PARTIAL_INT_THUNK_FN:%.*]] = partial_apply [callee_guaranteed] [[S_TO_INT_THUNK_FN]]([[THICK_INT_FN]]) : $@convention(thin) (S, @noescape @callee_guaranteed (@in_guaranteed P<Int>) -> ()) -> ()
// CHECK: [[NOESCAPE_INT_THUNK_FN:%.*]] = convert_escape_to_noescape [not_guaranteed] [[PARTIAL_INT_THUNK_FN]] : $@callee_guaranteed (S) -> () to $@noescape @callee_guaranteed (S) -> ()
// CHECK: [[USE_FN:%.*]] = function_ref @$s13parameterized3useyyyAA1SVXEF : $@convention(thin) (@noescape @callee_guaranteed (S) -> ()) -> ()
// CHECK: {{%.*}} = apply [[USE_FN]]([[NOESCAPE_INT_THUNK_FN]]) : $@convention(thin) (@noescape @callee_guaranteed (S) -> ()) -> ()
use({ (p: any P<Int>) -> Void in })
// CHECK: [[P_FN:%.*]] = function_ref @$s13parameterized11upcastInputyyFyAA1P_pXEfU1_ : $@convention(thin) (@in_guaranteed P) -> ()
// CHECK: [[NOESCAPE_P_FN:%.*]] = convert_function [[P_FN]] : $@convention(thin) (@in_guaranteed P) -> () to $@convention(thin) @noescape (@in_guaranteed P) -> ()
// CHECK: [[THICK_P_FN:%.*]] = thin_to_thick_function [[NOESCAPE_P_FN]] : $@convention(thin) @noescape (@in_guaranteed P) -> () to $@noescape @callee_guaranteed (@in_guaranteed P) -> ()
// CHECK: [[S_TO_P_THUNK_FN:%.*]] = function_ref @$s13parameterized1P_pIgn_AA1SVIegy_TR : $@convention(thin) (S, @noescape @callee_guaranteed (@in_guaranteed P) -> ()) -> ()
// CHECK: [[PARTIAL_INT_THUNK_FN:%.*]] = partial_apply [callee_guaranteed] [[S_TO_P_THUNK_FN]]([[THICK_P_FN]]) : $@convention(thin) (S, @noescape @callee_guaranteed (@in_guaranteed P) -> ()) -> ()
// CHECK: [[NOESCAPE_P_THUNK_FN:%.*]] = convert_escape_to_noescape [not_guaranteed] [[PARTIAL_INT_THUNK_FN]] : $@callee_guaranteed (S) -> () to $@noescape @callee_guaranteed (S) -> ()
// CHECK: [[USE_FN:%.*]] = function_ref @$s13parameterized3useyyyAA1SVXEF : $@convention(thin) (@noescape @callee_guaranteed (S) -> ()) -> ()
// CHECK: {{%.*}} = apply [[USE_FN]]([[NOESCAPE_P_THUNK_FN]]) : $@convention(thin) (@noescape @callee_guaranteed (S) -> ()) -> ()
use({ (p: any P) -> Void in })
}
func reuse(_ k: () -> any P<Int, String, Float>) {}
// CHECK-LABEL: sil hidden [ossa] @$s13parameterized12upcastResultyyF : $@convention(thin) () -> () {
func upcastResult() {
// CHECK: [[RES_FN:%.*]] = function_ref @$s13parameterized12upcastResultyyFAA1SVyXEfU_ : $@convention(thin) () -> S
// CHECK: [[NOESCAPE_RES_FN:%.*]] = convert_function [[RES_FN]] : $@convention(thin) () -> S to $@convention(thin) @noescape () -> S
// CHECK: [[THICK_RES_FN:%.*]] = thin_to_thick_function [[NOESCAPE_RES_FN]] : $@convention(thin) @noescape () -> S to $@noescape @callee_guaranteed () -> S
// CHECK: [[S_TO_P_RES_THUNK_FN:%.*]] = function_ref @$s13parameterized1SVIgd_AA1P_pySiSSSfXPIegr_TR : $@convention(thin) (@noescape @callee_guaranteed () -> S) -> @out P<Int, String, Float>
// CHECK: [[PARTIAL_RES_THUNK_FN:%.*]] = partial_apply [callee_guaranteed] [[S_TO_P_RES_THUNK_FN]]([[THICK_RES_FN]]) : $@convention(thin) (@noescape @callee_guaranteed () -> S) -> @out P<Int, String, Float>
// CHECK: [[NOESCAPE_RES_THUNK_FN:%.*]] = convert_escape_to_noescape [not_guaranteed] [[PARTIAL_RES_THUNK_FN]] : $@callee_guaranteed () -> @out P<Int, String, Float> to $@noescape @callee_guaranteed () -> @out P<Int, String, Float>
// CHECK: [[REUSE_FN:%.*]] = function_ref @$s13parameterized5reuseyyAA1P_pySiSSSfXPyXEF : $@convention(thin) (@noescape @callee_guaranteed () -> @out P<Int, String, Float>) -> ()
// CHECK: {{%.*}} = apply [[REUSE_FN]]([[NOESCAPE_RES_THUNK_FN]]) : $@convention(thin) (@noescape @callee_guaranteed () -> @out P<Int, String, Float>) -> ()
reuse({ () -> S in S() })
// CHECK: [[RES_Q_FN:%.*]] = function_ref @$s13parameterized12upcastResultyyFAA1Q_pySiSSSfXPyXEfU0_ : $@convention(thin) () -> @out Q<Int, String, Float>
// CHECK: [[NOESCAPE_RES_Q_FN:%.*]] = convert_function [[RES_Q_FN]] : $@convention(thin) () -> @out Q<Int, String, Float> to $@convention(thin) @noescape () -> @out Q<Int, String, Float>
// CHECK: [[THICK_NOESCAPE_RES_Q_FN:%.*]] = thin_to_thick_function [[NOESCAPE_RES_Q_FN]] : $@convention(thin) @noescape () -> @out Q<Int, String, Float> to $@noescape @callee_guaranteed () -> @out Q<Int, String, Float>
// CHECK: [[P_TO_Q_RES_THUNK_FN:%.*]] = function_ref @$s13parameterized1Q_pySiSSSfXPIgr_AA1P_pySiSSSfXPIegr_TR : $@convention(thin) (@noescape @callee_guaranteed () -> @out Q<Int, String, Float>) -> @out P<Int, String, Float>
// CHECK: [[PARTIAL_P_TO_Q_RES_THUNK_FN:%.*]] = partial_apply [callee_guaranteed] [[P_TO_Q_RES_THUNK_FN]]([[THICK_NOESCAPE_RES_Q_FN]]) : $@convention(thin) (@noescape @callee_guaranteed () -> @out Q<Int, String, Float>) -> @out P<Int, String, Float>
// CHECK: [[NOESCAPE_PARTIAL_P_TO_Q_RES_THUNK_FN:%.*]] = convert_escape_to_noescape [not_guaranteed] [[PARTIAL_P_TO_Q_RES_THUNK_FN]] : $@callee_guaranteed () -> @out P<Int, String, Float> to $@noescape @callee_guaranteed () -> @out P<Int, String, Float>
// CHECK: [[REUSE_FN:%.*]] = function_ref @$s13parameterized5reuseyyAA1P_pySiSSSfXPyXEF : $@convention(thin) (@noescape @callee_guaranteed () -> @out P<Int, String, Float>) -> ()
// CHECK: {{%.*}} = apply [[REUSE_FN]]([[NOESCAPE_PARTIAL_P_TO_Q_RES_THUNK_FN]]) : $@convention(thin) (@noescape @callee_guaranteed () -> @out P<Int, String, Float>) -> ()
reuse({ () -> any Q<Int, String, Float> in S() })
}
|
apache-2.0
|
f15ff82aa747985325fa63d279451b58
| 92.632479 | 255 | 0.624646 | 3.116643 | false | false | false | false |
ahoppen/swift
|
test/Driver/Dependencies/check-interface-implementation-fine.swift
|
14
|
2363
|
/// The fine-grained dependency graph has implicit dependencies from interfaces to implementations.
/// These are not presently tested because depends nodes are marked as depending in the interface,
/// as of 1/9/20. But this test will check fail if those links are not followed.
// RUN: %empty-directory(%t)
// RUN: cp -r %S/Inputs/check-interface-implementation-fine/* %t
// RUN: touch -t 201401240005 %t/*
// RUN: cd %t && %swiftc_driver -c -driver-use-frontend-path "%{python.unquoted};%S/Inputs/update-dependencies.py;%swift-dependency-tool" -output-file-map %t/output.json -incremental -driver-always-rebuild-dependents ./a.swift ./c.swift ./bad.swift -module-name main -j1 -v 2>&1 | %FileCheck -check-prefix=CHECK-FIRST %s
// RUN: %FileCheck -check-prefix=CHECK-RECORD-CLEAN %s < %t/main~buildrecord.swiftdeps
// CHECK-FIRST-NOT: warning
// CHECK-FIRST: Handled a.swift
// CHECK-FIRST: Handled c.swift
// CHECK-FIRST: Handled bad.swift
// CHECK-RECORD-CLEAN-DAG: "{{(./)?}}a.swift": [
// CHECK-RECORD-CLEAN-DAG: "{{(./)?}}bad.swift": [
// CHECK-RECORD-CLEAN-DAG: "{{(./)?}}c.swift": [
// RUN: touch -t 201401240006 %t/a.swift
// RUN: cd %t && not %swiftc_driver -c -driver-use-frontend-path "%{python.unquoted};%S/Inputs/update-dependencies-bad.py;%swift-dependency-tool" -output-file-map %t/output.json -incremental -driver-always-rebuild-dependents ./a.swift ./bad.swift ./c.swift -module-name main -j1 -v -driver-show-incremental > %t/a.txt 2>&1
// RUN: %FileCheck -check-prefix=CHECK-A %s < %t/a.txt
// RUN: %FileCheck -check-prefix=NEGATIVE-A %s < %t/a.txt
// RUN: %FileCheck -check-prefix=CHECK-RECORD-A %s < %t/main~buildrecord.swiftdeps
// CHECK-A: Handled a.swift
// CHECK-A: Handled bad.swift
// NEGATIVE-A-NOT: Handled c.swift
// CHECK-RECORD-A-DAG: "{{(./)?}}a.swift": [
// CHECK-RECORD-A-DAG: "{{(./)?}}bad.swift": !private [
// CHECK-RECORD-A-DAG: "{{(./)?}}c.swift": !private [
// RUN: cd %t && %swiftc_driver -c -driver-use-frontend-path "%{python.unquoted};%S/Inputs/update-dependencies.py;%swift-dependency-tool" -output-file-map %t/output.json -incremental -driver-always-rebuild-dependents ./a.swift ./bad.swift ./c.swift -module-name main -j1 -v -driver-show-incremental 2>&1 | %FileCheck -check-prefix CHECK-BC %s
// CHECK-BC-NOT: Handled a.swift
// CHECK-BC-DAG: Handled bad.swift
// CHECK-BC-DAG: Handled c.swift
|
apache-2.0
|
afad0a5a3ffab9580da0e84f8ae46e33
| 58.075 | 346 | 0.692763 | 3.049032 | false | false | false | false |
andreamontanari/PlaceHolder
|
Placeholder-ios/Placeholder-2309/Placeholder/Placeholder/DetailViewController.swift
|
1
|
8334
|
//
// DetailViewController.swift
// Placeholder
//
// Created by Andrea Montanari on 19/08/16.
// Copyright © 2016 Andrea Montanari. All rights reserved.
//
import Foundation
import Foundation
import UIKit
import RealmSwift
import MapKit
import Social
class DetailViewController: UIViewController {
var currentPlace: Place!
@IBOutlet weak var addressLbl: UILabel!
@IBOutlet weak var coordsLbl: UILabel!
@IBOutlet weak var commentLbl: UILabel!
@IBOutlet weak var shareContainer: UIView!
var defaultMessage: String = ""
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
addressLbl.text = currentPlace.streetName
coordsLbl.text = currentPlace.latlng
let placeholder = NSLocalizedString("PLACE_COMMENT_PLACEHOLDER", comment: "")
if currentPlace.placeComment == nil || currentPlace.placeComment == "" {
commentLbl.text = "\"\(placeholder)\""
defaultMessage = "\(currentPlace.streetName) \(currentPlace.latlng) #placeholder"
} else {
commentLbl.text = "\"\(currentPlace.placeComment!)\""
defaultMessage = "\"\(currentPlace.placeComment!)\" - \(currentPlace.streetName) (\(currentPlace.latlng)) #placeholder"
}
}
@IBAction func goBack(sender: UIBarButtonItem) {
self.navigationController?.popViewControllerAnimated(true)
//dismissViewControllerAnimated(true, completion: nil)
}
@IBAction func editCommentPressed(sender: UIButton) {
//open dialog
let alert = UIAlertController(title: NSLocalizedString("PLACE_COMMENT_TITLE", comment: ""), message: NSLocalizedString("PLACE_COMMENT_MSG", comment: ""), preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: NSLocalizedString("CANCEL", comment: ""), style: UIAlertActionStyle.Cancel, handler:
{ (action: UIAlertAction!) in
alert.dismissViewControllerAnimated(true, completion: nil)
}))
// configure text field
alert.addTextFieldWithConfigurationHandler({(textField: UITextField) in
textField.textColor = UIColor.blackColor()
textField.placeholder = NSLocalizedString("PLACE_COMMENT_HINT", comment: "")
textField.text = self.currentPlace.placeComment
})
alert.addAction(UIAlertAction(title: NSLocalizedString("SAVE", comment: ""), style: UIAlertActionStyle.Default, handler:{ (UIAlertAction)in
//read it
let textField = (alert.textFields?.first)! as UITextField
//save it
// Get the default Realm
// You only need to do this once (per thread)
let realm = try! Realm()
// Add to the Realm inside a transaction
try! realm.write {
self.currentPlace.placeComment = textField.text
}
let placeholder = NSLocalizedString("PLACE_COMMENT_PLACEHOLDER", comment: "")
if textField.text == nil || textField.text == "" {
self.commentLbl.text = "\"\(placeholder)\""
} else {
self.commentLbl.text = "\"\(textField.text!)\""
}
showToast(NSLocalizedString("PLACE_COMMENT_OK_TITLE", comment: ""), message: NSLocalizedString("PLACE_COMMENT_OK_MSG", comment: ""), vc: self)
}))
presentViewController(alert, animated: true, completion: nil)
}
@IBAction func deletePressed(sender: UIButton) {
//open dialog
let alert = UIAlertController(title: NSLocalizedString("DELETE_PLACE_TITLE", comment: ""), message: NSLocalizedString("DELETE_PLACE_MSG", comment: ""), preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: NSLocalizedString("CANCEL", comment: ""), style: UIAlertActionStyle.Cancel, handler:
{ (action: UIAlertAction!) in
alert.dismissViewControllerAnimated(true, completion: nil)
}))
alert.addAction(UIAlertAction(title: NSLocalizedString("DELETE_PLACE_CONFIRM", comment: ""), style: UIAlertActionStyle.Default, handler:{ (UIAlertAction)in
// Get the default Realm
// You only need to do this once (per thread)
let realm = try! Realm()
// Add to the Realm inside a transaction
try! realm.write {
realm.delete(self.currentPlace)
}
self.navigationController?.popViewControllerAnimated(true)
showToast(NSLocalizedString("DELETE_PLACE_OK_TITLE", comment: ""), message: NSLocalizedString("DELETE_PLACE_OK_MSG", comment: ""), vc: self)
}))
presentViewController(alert, animated: true, completion: nil)
}
@IBAction func sharePressed(sender: UIButton) {
shareContainer.hidden = false
}
@IBAction func facebookPressed(sender: UIButton) {
if SLComposeViewController.isAvailableForServiceType(SLServiceTypeFacebook) {
let fbShare:SLComposeViewController = SLComposeViewController(forServiceType: SLServiceTypeFacebook)
fbShare.setInitialText(defaultMessage)
self.presentViewController(fbShare, animated: true, completion: nil)
} else {
let alert = UIAlertController(title: NSLocalizedString("FB_LOGIN_TITLE", comment: ""), message: NSLocalizedString("FB_LOGIN_MSG", comment: ""), preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: nil))
self.presentViewController(alert, animated: true, completion: nil)
}
}
@IBAction func twitterPressed(sender: UIButton) {
if SLComposeViewController.isAvailableForServiceType(SLServiceTypeTwitter) {
let tweetShare:SLComposeViewController = SLComposeViewController(forServiceType: SLServiceTypeTwitter)
tweetShare.setInitialText(defaultMessage)
self.presentViewController(tweetShare, animated: true, completion: nil)
} else {
let alert = UIAlertController(title: NSLocalizedString("TW_LOGIN_TITLE", comment: ""), message: NSLocalizedString("TW_LOGIN_MSG", comment: ""), preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: nil))
self.presentViewController(alert, animated: true, completion: nil)
}
}
@IBAction func shareClosePressed(sender: UIButton) {
shareContainer.hidden = true
}
@IBAction func navigatePressed(sender: UIButton) {
//GoogleMaps
if (UIApplication.sharedApplication().canOpenURL(NSURL(string:"comgooglemaps://")!)) {
UIApplication.sharedApplication().openURL(NSURL(string:
"comgooglemaps://?saddr=&daddr=\(currentPlace.latitude),\(currentPlace.longitude)&directionsmode=walking")!)
} else {
//Apple Maps
let coordinate = CLLocationCoordinate2DMake(CLLocationDegrees(currentPlace.latitude)!, CLLocationDegrees(currentPlace.longitude)!)
let mapItem = MKMapItem(placemark: MKPlacemark(coordinate: coordinate, addressDictionary:nil))
mapItem.name = NSLocalizedString("MAPS_DESTINATION", comment: "")
mapItem.openInMapsWithLaunchOptions([MKLaunchOptionsDirectionsModeKey : MKLaunchOptionsDirectionsModeDriving])
if (UIApplication.sharedApplication().canOpenURL(NSURL(string:"http://maps.apple.com")!)) {
UIApplication.sharedApplication().openURL(NSURL(string:
"http://maps.apple.com/?daddr=\(currentPlace.latitude),\(currentPlace.longitude)")!)
} else {
showToast(NSLocalizedString("ERR_MAPS_TITLE", comment: ""), message: NSLocalizedString("ERR_MAPS_MSG", comment: ""), vc: self)
}
}
}
}
|
mit
|
7410e1afe729282cfbb762bf8bd0a570
| 42.176166 | 207 | 0.635305 | 5.457105 | false | false | false | false |
noprom/Cocktail-Pro
|
smartmixer/smartmixer/Common/PopupView.swift
|
1
|
8392
|
//
// PopupView.swift
// smartmixer
//
// Created by 姚俊光 on 14-9-4.
// Copyright (c) 2014年 Smart Group. All rights reserved.
//
import UIKit
//箭头的方向
enum ArrorDirection{
case left//向左
case right//向右
}
class PopupView: UIView {
//指向的方向 0为left 1为右
var arrorDirection:ArrorDirection = ArrorDirection.left
//父View
@IBOutlet var parentView:UIView!
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)!
//self.alpha = 0.88
}
var closeButton:UIButton! = nil
override init(frame: CGRect) {
super.init(frame: frame)
backgroundColor = UIColor.clearColor()
if(closeButton == nil){
closeButton=UIButton(frame: CGRect(x: self.frame.width-22,y: 2,width: 20,height: 20))
closeButton.setBackgroundImage(UIImage(named: "close-gray"), forState: UIControlState.Normal)
self.addSubview(closeButton)
closeButton.addTarget(self, action: Selector("closeView:"), forControlEvents: UIControlEvents.TouchUpInside)
}
}
//呼叫隐藏视图
func closeView(sender:UIButton){
showOrHideView(false)
}
//显示或隐藏
func showOrHideView(options:Bool){
if(options){
self.alpha = 0
self.hidden = false
UIView.animateWithDuration(0.3, animations: { self.alpha = 1 }, completion: { _ in
self.lockAnimation = false
})
}else{
UIView.animateWithDuration(0.3, animations: {
self.alpha = 0
}, completion: { _ in
self.hidden = true
self.lockAnimation = false
})
}
}
override func drawRect(rect: CGRect) {
super.drawRect(rect)
drawInContext(UIGraphicsGetCurrentContext())
//设置阴影颜色,透明度,偏移量
//self.layer.backgroundColor = UIColor(white: 1, alpha: 0.88).CGColor
self.layer.shadowColor = UIColor.lightGrayColor().CGColor
self.layer.shadowRadius = 3
self.layer.shadowOpacity = 0.55;
self.layer.shadowOffset = CGSizeMake(0.0, 0.0);
}
//箭头距顶端的距离
var arrorPosY:CGFloat = 60
//箭头的宽度,高度为宽度*2
let arrorWidth:CGFloat = 20
//圆弧的角度
let radius:CGFloat = 10
//改变Arrow的计时器
var changeArrorPosTimer:NSTimer!
//当前显示的View
var currentView:UIView?=nil
var arrowInternal:CGFloat = 5
func animateArrorPos(){
if(arrorPosY < newArrorPosY){
arrorPosY += arrowInternal
if(arrorPosY > newArrorPosY){
arrorPosY = newArrorPosY
}
} else if(arrorPosY > newArrorPosY){
arrorPosY -= arrowInternal
if(arrorPosY < newArrorPosY){
arrorPosY = newArrorPosY
}
}else{
self.changeArrorPosTimer.invalidate()
self.changeArrorPosTimer = nil
}
self.setNeedsDisplay()
}
var newArrorPosY:CGFloat=0
//新的需要显示的View
var inewView:UIView? = nil
var lockAnimation:Bool = false
//新建新的View
func showNewView(newView:UIView,pointToItem item:UIView){
if(lockAnimation){ return }
lockAnimation=true
if(self.hidden){
showOrHideView(true)
}
if(self.currentView != newView){
//首先计算出目标的位置
var rect:CGRect = item.bounds
rect = item.convertRect(rect, toView: parentView)
var pointPos:CGFloat = 0
if(rect.height<40){
pointPos = rect.midY
}else{
pointPos = rect.minY + 20
}
var newContainerY = pointPos - 60
//如果需要显示的东西太height
if((newContainerY + newView.frame.height) > 680){
newContainerY = 680 - newView.frame.height
//这就是箭头的偏移值
}
newArrorPosY = pointPos - newContainerY
//新窗口的大小
var newRect = CGRect(x: self.frame.origin.x, y: newContainerY, width: newView.frame.width+40, height: newView.frame.height+20)
//新填充视图的位置
newView.frame = CGRect(x: 30, y: 10, width: newView.frame.width, height: newView.frame.height)
if(arrorDirection == ArrorDirection.right){
newRect = CGRect(x: rect.origin.x - newView.frame.width - 40 , y: newContainerY, width: newView.frame.width+40, height: newView.frame.height+20)
newView.frame = CGRect(x: 10, y: 10, width: newView.frame.width, height: newView.frame.height)
}
arrowInternal = (self.newArrorPosY - self.arrorPosY)/19
if(arrowInternal<0){
arrowInternal = -arrowInternal
}
//self.arrorPosY = self.newArrorPosY
self.changeArrorPosTimer = NSTimer.scheduledTimerWithTimeInterval(0.025, target: self, selector: "animateArrorPos", userInfo: nil, repeats: true)
UIView.animateWithDuration(0.5, animations: {
self.frame = newRect
self.addSubview(newView)
newView.alpha = 1
if(self.currentView != nil){
self.currentView?.alpha = 0
}
if(self.arrorDirection == ArrorDirection.right){
self.closeButton.frame=CGRect(x: 2,y: 2,width: 20,height: 20)
} else if(self.arrorDirection == ArrorDirection.left){
self.closeButton.frame=CGRect(x: newRect.width-22,y: 2,width: 20,height: 20)
}
}, completion: { _ in
self.bringSubviewToFront(self.closeButton)
if(self.currentView != nil){
self.currentView?.removeFromSuperview()
}
self.currentView = newView
self.setNeedsDisplay()
self.lockAnimation = false
})
}
}
func drawInContext(context:CGContext!){
CGContextSetStrokeColorWithColor(context, UIColor.lightGrayColor().CGColor)
CGContextSetLineWidth(context, 1.0)
CGContextSetFillColorWithColor(context, UIColor.whiteColor().CGColor)
let rrect = self.bounds;
var minx = CGRectGetMinX(rrect)
var maxx = CGRectGetMaxX(rrect)
let miny = CGRectGetMinY(rrect)
let maxy = CGRectGetMaxY(rrect)
if(self.arrorDirection == ArrorDirection.left){//向左
minx = minx + arrorWidth
CGContextMoveToPoint(context, minx,arrorWidth+arrorPosY)
CGContextAddLineToPoint(context,minx-arrorWidth, arrorPosY)
CGContextAddLineToPoint(context,minx, arrorPosY-arrorWidth)
CGContextAddArcToPoint(context, minx, miny, maxx, miny, radius)
CGContextAddArcToPoint(context, maxx, miny, maxx, maxy, radius)
CGContextAddArcToPoint(context, maxx, maxy, minx, maxy, radius)
CGContextAddArcToPoint(context, minx, maxy, minx, arrorWidth+arrorPosY, radius)
}else if(self.arrorDirection == ArrorDirection.right){//向右
maxx = maxx - arrorWidth
CGContextMoveToPoint(context, maxx,arrorWidth+arrorPosY)
CGContextAddLineToPoint(context,maxx+arrorWidth, arrorPosY)
CGContextAddLineToPoint(context,maxx, arrorPosY-arrorWidth)
CGContextAddArcToPoint(context, maxx, miny, minx, miny, radius)
CGContextAddArcToPoint(context, minx, miny, minx, maxy, radius)
CGContextAddArcToPoint(context, minx, maxy, maxx, maxy, radius)
CGContextAddArcToPoint(context, maxx, maxy, maxx, arrorWidth+arrorPosY, radius)
}
CGContextClosePath(context)
CGContextDrawPath(context, CGPathDrawingMode.Stroke)
}
}
|
apache-2.0
|
ead160687368ce2761d95fc81f44e1dc
| 33.666667 | 160 | 0.569773 | 4.415895 | false | false | false | false |
rnystrom/GitHawk
|
Pods/Highlightr/Pod/Classes/Highlightr.swift
|
2
|
7937
|
//
// Highlightr.swift
// Pods
//
// Created by Illanes, J.P. on 4/10/16.
//
//
import Foundation
import JavaScriptCore
/// Utility class for generating a highlighted NSAttributedString from a String.
open class Highlightr
{
/// Returns the current Theme.
open var theme : Theme!
{
didSet
{
themeChanged?(theme)
}
}
/// This block will be called every time the theme changes.
open var themeChanged : ((Theme) -> Void)?
fileprivate let jsContext : JSContext
fileprivate let hljs = "window.hljs"
fileprivate let bundle : Bundle
fileprivate let htmlStart = "<"
fileprivate let spanStart = "span class=\""
fileprivate let spanStartClose = "\">"
fileprivate let spanEnd = "/span>"
fileprivate let htmlEscape = try! NSRegularExpression(pattern: "&#?[a-zA-Z0-9]+?;", options: .caseInsensitive)
/**
Default init method.
- returns: Highlightr instance.
*/
public init?()
{
jsContext = JSContext()
jsContext.evaluateScript("var window = {};")
bundle = Bundle(for: Highlightr.self)
guard let hgPath = bundle.path(forResource: "highlight.min", ofType: "js") else
{
return nil
}
let hgJs = try! String.init(contentsOfFile: hgPath)
let value = jsContext.evaluateScript(hgJs)
if !(value?.toBool())!
{
return nil
}
guard setTheme(to: "pojoaque", fontSize: 14) else
{
return nil
}
}
/**
Set the theme to use for highlighting.
- parameter to: Theme name
- returns: true if it was possible to set the given theme, false otherwise
*/
@discardableResult
open func setTheme(to name: String, fontSize: CGFloat) -> Bool
{
guard let defTheme = bundle.path(forResource: name+".min", ofType: "css") else
{
return false
}
let themeString = try! String.init(contentsOfFile: defTheme)
theme = Theme(themeString: themeString, fontSize: fontSize)
return true
}
/**
Takes a String and returns a NSAttributedString with the given language highlighted.
- parameter code: Code to highlight.
- parameter languageName: Language name or alias. Set to `nil` to use auto detection.
- parameter fastRender: Defaults to true - When *true* will use the custom made html parser rather than Apple's solution.
- returns: NSAttributedString with the detected code highlighted.
*/
open func highlight(_ code: String, as languageName: String? = nil, fastRender: Bool = true) -> NSAttributedString?
{
var fixedCode = code.replacingOccurrences(of: "\\",with: "\\\\");
fixedCode = fixedCode.replacingOccurrences(of: "\'",with: "\\\'");
fixedCode = fixedCode.replacingOccurrences(of: "\"", with:"\\\"");
fixedCode = fixedCode.replacingOccurrences(of: "\n", with:"\\n");
fixedCode = fixedCode.replacingOccurrences(of: "\r", with:"");
let command: String
if let languageName = languageName
{
command = String.init(format: "%@.highlight(\"%@\",\"%@\").value;", hljs, languageName, fixedCode)
}else
{
// language auto detection
command = String.init(format: "%@.highlightAuto(\"%@\").value;", hljs, fixedCode)
}
let res = jsContext.evaluateScript(command)
guard var string = res!.toString(), string != "undefined" else
{
return nil
}
let returnString : NSAttributedString
if(fastRender)
{
returnString = processHTMLString(string)!
}else
{
string = "<style>"+theme.lightTheme+"</style><pre><code class=\"hljs\">"+string+"</code></pre>"
let opt: [NSAttributedString.DocumentReadingOptionKey : Any] = [
.documentType: NSAttributedString.DocumentType.html,
.characterEncoding: String.Encoding.utf8
]
let data = string.data(using: String.Encoding.utf8)!
returnString = try! NSMutableAttributedString(data:data, options: opt, documentAttributes:nil)
}
return returnString
}
/**
Returns a list of all the available themes.
- returns: Array of Strings
*/
open func availableThemes() -> [String]
{
let paths = bundle.paths(forResourcesOfType: "css", inDirectory: nil) as [NSString]
var result = [String]()
for path in paths {
result.append(path.lastPathComponent.replacingOccurrences(of: ".min.css", with: ""))
}
return result
}
/**
Returns a list of all supported languages.
- returns: Array of Strings
*/
open func supportedLanguages() -> [String]
{
let command = String.init(format: "%@.listLanguages();", hljs)
let res = jsContext.evaluateScript(command)
return res!.toArray() as! [String]
}
//Private & Internal
fileprivate func processHTMLString(_ string: String) -> NSAttributedString?
{
let scanner = Scanner(string: string)
scanner.charactersToBeSkipped = nil
var scannedString: NSString?
let resultString = NSMutableAttributedString(string: "")
var propStack = ["hljs"]
while !scanner.isAtEnd
{
var ended = false
if scanner.scanUpTo(htmlStart, into: &scannedString)
{
if scanner.isAtEnd
{
ended = true
}
}
if scannedString != nil && scannedString!.length > 0 {
let attrScannedString = theme.applyStyleToString(scannedString! as String, styleList: propStack)
resultString.append(attrScannedString)
if ended
{
continue
}
}
scanner.scanLocation += 1
let string = scanner.string as NSString
let nextChar = string.substring(with: NSMakeRange(scanner.scanLocation, 1))
if(nextChar == "s")
{
scanner.scanLocation += (spanStart as NSString).length
scanner.scanUpTo(spanStartClose, into:&scannedString)
scanner.scanLocation += (spanStartClose as NSString).length
propStack.append(scannedString! as String)
}
else if(nextChar == "/")
{
scanner.scanLocation += (spanEnd as NSString).length
propStack.removeLast()
}else
{
let attrScannedString = theme.applyStyleToString("<", styleList: propStack)
resultString.append(attrScannedString)
scanner.scanLocation += 1
}
scannedString = nil
}
let results = htmlEscape.matches(in: resultString.string,
options: [.reportCompletion],
range: NSMakeRange(0, resultString.length))
var locOffset = 0
for result in results
{
let fixedRange = NSMakeRange(result.range.location-locOffset, result.range.length)
let entity = (resultString.string as NSString).substring(with: fixedRange)
if let decodedEntity = HTMLUtils.decode(entity)
{
resultString.replaceCharacters(in: fixedRange, with: String(decodedEntity))
locOffset += result.range.length-1;
}
}
return resultString
}
}
|
mit
|
c1cd516cd6eb281645fd352ed0c59fd0
| 32.070833 | 130 | 0.559153 | 4.994965 | false | false | false | false |
zhiquan911/CHSlideSwitchView
|
CHSlideSwitchView/Classes/CHSlideItem.swift
|
1
|
1390
|
//
// CHSlideItem.swift
// Pods
//
// Created by Chance on 2017/6/5.
//
//
import Foundation
///
/// 标签元素类型
///
/// - view: 视图
/// - viewController: 视图控制器
public enum CHSlideItemType {
public typealias GetViewController = () -> UIViewController
public typealias GetView = () -> UIView
case view(GetView)
case viewController(GetViewController)
/// 通过block获取实体
var entity: AnyObject {
switch self {
case let .view(block):
return block()
case let .viewController(block):
return block()
}
}
}
/// Tab实体类型
///
/// - text: 文字,组件使用默认的View样式展示文字,默认颜色,选中效果
/// - view: 自定义View
public enum CHSlideTabType {
case text
case view
}
/// 标签元素定义
public class CHSlideItem {
// /// 标签
// public var key: Int = 0
/// 标题
public var title: String = ""
/// 标签View
public var tabView: UIView?
/// 类型
public var content: CHSlideItemType!
public convenience init(title: String = "", tabView: UIView? = nil, content: CHSlideItemType) {
self.init()
// self.key = key
self.title = title
self.tabView = tabView
self.content = content
}
}
|
mit
|
87b7168597dd6701cc58527fd9b4a6a6
| 15.773333 | 99 | 0.556439 | 3.847095 | false | false | false | false |
rgravina/tddtris
|
TddTetris/Components/Game/DefaultActionSelector.swift
|
1
|
1051
|
class DefaultActionSelector: ActionSelector {
let view: GameView
let state: GameState
let tetrominoGenerator: TetrominoGenerator
let collisionDetector: CollisionDetector
init(view: GameView,
state: GameState,
tetrominoGenerator: TetrominoGenerator,
collisionDetector: CollisionDetector
) {
self.view = view
self.state = state
self.tetrominoGenerator = tetrominoGenerator
self.collisionDetector = collisionDetector
}
func next() -> Action {
let maybeTetromino = state.tetromino
if maybeTetromino == nil {
return NextTetrominoAction(
view: view,
state: state,
tetrominoGenerator: tetrominoGenerator
)
}
if collisionDetector.wouldCollide(.down) {
return SettleTetrominoAction(
state: state
)
}
return MoveTetrominoDownOneRowAction(
view: view,
state: state
)
}
}
|
mit
|
b229b18d087ea097de50e4767cd89573
| 25.948718 | 54 | 0.589914 | 5.681081 | false | false | false | false |
reswifq/reswifq
|
Sources/Reswifq/Reswifq.swift
|
1
|
9530
|
//
// Reswifq.swift
// Reswifq
//
// Created by Valerio Mazzeo on 21/02/2017.
// Copyright © 2017 VMLabs Limited. All rights reserved.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
// See the GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//
import Foundation
import RedisClient
public enum ReswifqError: Error {
case unknownJobType(String)
}
// MARK: - Reswifq
public final class Reswifq: Queue {
// MARK: Initialization
public required init(client: RedisClient) {
self.client = client
}
// MARK: Setting and Getting Attributes
public let client: RedisClient
public var jobMap = [String: Job.Type]()
// MARK: Queue
/// Priority not supported at the moment
/// See https://github.com/antirez/redis/issues/1785
public func enqueue(_ job: Job, priority: QueuePriority = .medium, scheduleAt: Date? = nil) throws {
let encodedJob = try JobBox(job, priority: priority).data().string(using: .utf8)
if let scheduledAt = scheduleAt {
// Delayed Job
try self.client.zadd(RedisKey(.queueDelayed).value, values: (score: scheduledAt.timeIntervalSince1970, member: encodedJob))
} else {
// Normal Job
//try self.client.lpush(RedisKey(.queuePending(priority)).value, values: encodedJob)
try self.client.lpush(RedisKey(.queuePending(.medium)).value, values: encodedJob)
}
}
public func dequeue() throws -> PersistedJob? {
guard let encodedJob = try self.client.rpoplpush(
source: RedisKey(.queuePending(.medium)).value,
destination: RedisKey(.queueProcessing).value
) else {
return nil
}
let persistedJob = try self.persistedJob(with: encodedJob)
self.setLock(for: persistedJob)
return persistedJob
}
public func bdequeue() throws -> PersistedJob {
let encodedJob = try self.client.brpoplpush(
source: RedisKey(.queuePending(.medium)).value,
destination: RedisKey(.queueProcessing).value
)
let persistedJob = try self.persistedJob(with: encodedJob)
self.setLock(for: persistedJob)
return persistedJob
}
public func complete(_ identifier: JobID) throws {
try self.client.multi { client, transaction in
try transaction.enqueue {
// Remove the job from the processing queue
try client.lrem(RedisKey(.queueProcessing).value, value: identifier, count: -1)
}
try transaction.enqueue {
// Remove the lock
try client.del(RedisKey(.lock(identifier)).value)
}
try transaction.enqueue {
// Remove any retry attempt
try client.del(RedisKey(.retry(identifier)).value)
}
}
}
}
// MARK: - Queue Status
extension Reswifq {
/**
Fetches any pending job.
- returns: An array of persisted jobs that have been enqueued and are waiting to be processed.
*/
public func pendingJobs() throws -> [JobID] {
return try self.client.lrange(RedisKey(.queuePending(.medium)).value, start: 0, stop: -1)
}
/**
Fetches any processing job.
- returns: An array of persisted jobs that have been dequeued and are being processed.
*/
public func processingJobs() throws -> [JobID] {
return try self.client.lrange(RedisKey(.queueProcessing).value, start: 0, stop: -1)
}
/**
Fetches any delayed job.
- returns: An array of persisted jobs that have been scheduled for delayed execution.
*/
public func delayedJobs() throws -> [JobID] {
return try self.client.zrange(RedisKey(.queueDelayed).value, start: 0, stop: -1)
}
/**
Fetches any overdue job.
- returns: An array of persisted jobs that have been scheduled for delayed execution and are now overdue.
*/
public func overdueJobs() throws -> [JobID] {
return try self.client.zrangebyscore(RedisKey(.queueDelayed).value, min: 0, max: Date().timeIntervalSince1970)
}
public func enqueueOverdueJobs() throws {
let overdueJobs = try self.overdueJobs()
for job in overdueJobs {
try self.client.multi { client, transaction in
try transaction.enqueue {
// Remove the job from the delayed queue
try client.zrem(RedisKey(.queueDelayed).value, member: job)
}
try transaction.enqueue {
// Add the job to the pending queue
// This is not ideal because subsequent delayed jobs would be executed in reverse order,
// but this is the best solution, until we can support queues with different priorities
try client.rpush(RedisKey(.queuePending(.medium)).value, values: job)
}
}
}
}
/**
Determines whether a job has overcome its time to live in the processing queue.
- returns: `true` if the job has expired, `false` otherwise.
*/
public func isJobExpired(_ identifier: JobID) throws -> Bool {
return try self.client.get(RedisKey(.lock(identifier)).value) == nil
}
/**
Fetches the retry attempts for a given job.
- parameter identifier: The identifier of the job to retrieve the retry attempts for.
- returns: The number of retry attempts for the given jobs.
*/
public func retryAttempts(for identifier: JobID) throws -> Int64 {
guard let attempts = try self.client.get(RedisKey(.retry(identifier)).value) else {
return 0
}
return Int64(attempts) ?? 0
}
/**
Moves a job from the processing queue to the pending queue.
The operation is performed in a transaction to ensure the job is in either one of the two queues.
If the job is not expired the move operation is skipped and no error is thrown.
- parameter identifier: The identifier of the job to retry.
- returns: `true` if an retry attempt has been made, `false` otherwise.
*/
@discardableResult
public func retryJobIfExpired(_ identifier: JobID) throws -> Bool {
guard try self.isJobExpired(identifier) else {
return false
}
try self.client.multi { client, transaction in
try transaction.enqueue {
// Remove the job from the processing queue
try client.lrem(RedisKey(.queueProcessing).value, value: identifier, count: -1)
}
try transaction.enqueue {
// Add the job to the pending queue
try client.lpush(RedisKey(.queuePending(.medium)).value, values: identifier)
}
try transaction.enqueue {
// Increment the job's retry attempts
try client.incr(RedisKey(.retry(identifier)).value)
}
}
return true
}
}
// MARK: - Queue Helpers
extension Reswifq {
fileprivate func persistedJob(with encodedJob: String) throws -> PersistedJob {
let jobBox = try JobBox(data: encodedJob.data(using: .utf8))
guard let jobType = self.jobMap[jobBox.type] else {
throw ReswifqError.unknownJobType(jobBox.type)
}
let job = try jobType.init(data: jobBox.job)
return (identifier: encodedJob, job: job)
}
fileprivate func setLock(for persistedJob: PersistedJob) {
try? self.client.setex(
RedisKey(.lock(persistedJob.identifier)).value,
timeout: persistedJob.job.timeToLive,
value: persistedJob.identifier
)
}
}
// MARK: RedisKey
extension Reswifq {
struct RedisKey {
// MARK: Initialization
public init(_ key: RedisKey.Key) {
self.init(key.components)
}
public init(_ components: String...) {
self.init(components)
}
public init(_ components: [String]) {
self.value = components.joined(separator: ":")
}
// MARK: Attributes
public let value: String
}
}
extension Reswifq.RedisKey {
enum Key {
case queuePending(QueuePriority)
case queueProcessing
case queueDelayed
case lock(String)
case retry(String)
}
}
extension Reswifq.RedisKey.Key {
var components: [String] {
switch self {
case .queuePending(let priority):
return ["queue", "pending", priority.rawValue]
case .queueProcessing:
return ["queue", "processing"]
case .queueDelayed:
return ["queue", "delayed"]
case .lock(let value):
return ["lock", value]
case .retry(let value):
return ["retry", value]
}
}
}
|
lgpl-3.0
|
83331e62f2fe6442f2af96683a7b23d1
| 27.444776 | 135 | 0.613181 | 4.413617 | false | false | false | false |
KrishMunot/swift
|
test/Parse/errors.swift
|
2
|
4521
|
// RUN: %target-parse-verify-swift
enum MSV : ErrorProtocol {
case Foo, Bar, Baz
case CarriesInt(Int)
var domain: String { return "" }
var code: Int { return 0 }
}
func opaque_error() -> ErrorProtocol { return MSV.Foo }
func one() {
do {
true ? () : throw opaque_error() // expected-error {{expected expression after '? ... :' in ternary expression}}
} catch _ {
}
do {
} catch { // expected-warning {{'catch' block is unreachable because no errors are thrown in 'do' block}}
let error2 = error
}
do {
} catch where true { // expected-warning {{'catch' block is unreachable because no errors are thrown in 'do' block}}
let error2 = error
} catch {
}
// <rdar://problem/20985280> QoI: improve diagnostic on improper pattern match on type
do {
throw opaque_error()
} catch MSV { // expected-error {{'is' keyword required to pattern match against type name}} {{11-11=is }}
} catch {
}
do {
throw opaque_error()
} catch is ErrorProtocol { // expected-warning {{'is' test is always true}}
}
func foo() throws {}
do {
#if false
try foo()
#endif
} catch { // don't warn, #if code should be scanned.
}
do {
#if false
throw opaque_error()
#endif
} catch { // don't warn, #if code should be scanned.
}
}
func takesAutoclosure(@autoclosure _ fn : () -> Int) {}
func takesThrowingAutoclosure(@autoclosure _ fn : () throws -> Int) {}
func genError() throws -> Int { throw MSV.Foo }
func genNoError() -> Int { return 0 }
func testAutoclosures() throws {
takesAutoclosure(genError()) // expected-error {{call can throw, but it is not marked with 'try' and it is executed in a non-throwing autoclosure}}
takesAutoclosure(genNoError())
try takesAutoclosure(genError()) // expected-error {{call can throw, but it is executed in a non-throwing autoclosure}}
try takesAutoclosure(genNoError()) // expected-warning {{no calls to throwing functions occur within 'try' expression}}
takesAutoclosure(try genError()) // expected-error {{call can throw, but it is executed in a non-throwing autoclosure}}
takesAutoclosure(try genNoError()) // expected-warning {{no calls to throwing functions occur within 'try' expression}}
takesThrowingAutoclosure(try genError())
takesThrowingAutoclosure(try genNoError()) // expected-warning {{no calls to throwing functions occur within 'try' expression}}
try takesThrowingAutoclosure(genError())
try takesThrowingAutoclosure(genNoError()) // expected-warning {{no calls to throwing functions occur within 'try' expression}}
takesThrowingAutoclosure(genError()) // expected-error {{call can throw but is not marked with 'try'}}
takesThrowingAutoclosure(genNoError())
}
struct IllegalContext {
var x: Int = genError() // expected-error {{call can throw, but errors cannot be thrown out of a property initializer}}
func foo(_ x: Int = genError()) {} // expected-error {{call can throw, but errors cannot be thrown out of a default argument}}
func catcher() throws {
do {
try genError()
} catch MSV.CarriesInt(genError()) { // expected-error {{call can throw, but errors cannot be thrown out of a catch pattern}}
} catch MSV.CarriesInt(let i) where i == genError() { // expected-error {{call can throw, but errors cannot be thrown out of a catch guard expression}}
}
}
}
func illformed() throws {
do {
try genError()
// TODO: this recovery is terrible
} catch MSV.CarriesInt(let i) where i == genError()) { // expected-error {{call can throw, but errors cannot be thrown out of a catch guard expression}} expected-error {{expected '{'}} expected-error {{braced block of statements is an unused closure}} expected-error {{expression resolves to an unused function}}
}
}
func postThrows() -> Int throws { // expected-error{{'throws' may only occur before '->'}}{{19-19=throws }}{{25-32=}}
return 5
}
func postRethrows(_ f: () throws -> Int) -> Int rethrows { // expected-error{{'rethrows' may only occur before '->'}}{{42-42=rethrows }}{{48-57=}}
return try f()
}
// rdar://21328447
func fixitThrow0() throw {} // expected-error{{expected throwing specifier; did you mean 'throws'?}} {{20-25=throws}}
func fixitThrow1() throw -> Int {} // expected-error{{expected throwing specifier; did you mean 'throws'?}} {{20-25=throws}}
func fixitThrow2() throws {
var _: (Int)
throw MSV.Foo
var _: Int throw -> Int // expected-error{{expected throwing specifier; did you mean 'throws'?}} {{14-19=throws}}
}
|
apache-2.0
|
0db379f1b5000c9bfa1af952c100e48b
| 35.459677 | 316 | 0.679053 | 4.155331 | false | false | false | false |
qinting513/SwiftNote
|
PullToRefreshKit-master 自定义刷新控件/PullToRefreshKit/DefaultBannerController.swift
|
1
|
2170
|
//
// DefaultBannerController.swift
// PullToRefreshKit
//
// Created by huangwenchen on 16/7/13.
// Copyright © 2016年 Leo. All rights reserved.
//
import Foundation
import UIKit
class DefaultBannerController: UIViewController {
let scrollView = UIScrollView()
override func viewDidLoad() {
super.viewDidLoad()
self.navigationItem.title = "Banners"
self.automaticallyAdjustsScrollViewInsets = false
setUpViews()
_ = scrollView.setUpLeftRefresh { [weak self] in
_ = self?.navigationController?.popViewController(animated: true)
}
_ = scrollView.setUpRightRefresh { [weak self] in
let nvc = DefaultBannerController()
self?.navigationController?.pushViewController(nvc, animated: true)
}
}
func setUpViews(){
view.backgroundColor = UIColor.white
let screenWidth = UIScreen.main.bounds.size.width;
let scrollheight = screenWidth / 8.0 * 5.0
scrollView.frame = CGRect(x: 0, y: 0, width: screenWidth, height: scrollheight)
scrollView.center = self.view.center
self.view.addSubview(scrollView)
let imageView1 = UIImageView(frame:CGRect(x: 0, y: 0, width: screenWidth, height: scrollheight))
imageView1.image = UIImage(named: "banner1.jpg")
scrollView.addSubview(imageView1)
let imageView2 = UIImageView(frame:CGRect(x: screenWidth, y: 0, width: screenWidth, height: scrollheight))
imageView2.image = UIImage(named: "banner2.jpg")
scrollView.addSubview(imageView2)
scrollView.isPagingEnabled = true
scrollView.contentSize = CGSize(width: screenWidth * 2, height: scrollheight)
let desLabel = UILabel().SetUp { (label) in
label.frame = CGRect(x: 0, y: 0, width: screenWidth, height: 40)
label.font = UIFont.systemFont(ofSize: 14)
label.center = CGPoint(x: scrollView.center.x, y: scrollView.center.y - scrollView.frame.width/2 - 20)
label.text = "Scroll left or right"
label.textAlignment = .center
}
view.addSubview(desLabel)
}
}
|
apache-2.0
|
71fba9a09fe547931cef8929cf17d849
| 39.886792 | 115 | 0.649746 | 4.440574 | false | false | false | false |
KrishMunot/swift
|
test/SourceKit/CodeFormat/indent-closure.swift
|
6
|
2268
|
func foo() {
bar() {
var abc = 1
let a: String = {
let b = "asdf"
return b
}()
}
}
class C {
private static let durationTimeFormatter: NSDateComponentsFormatter = {
return timeFormatter
}()
}
func foo1(a: Int, handler : () -> ()) {}
func foo2(handler : () -> ()) {}
func foo3() {
foo1(1)
{
}
}
func foo4() {
test = {
return 0
}()
let test = {
return 0
}()
}
// RUN: %sourcekitd-test -req=format -line=3 -length=1 %s >%t.response
// RUN: %sourcekitd-test -req=format -line=4 -length=1 %s >>%t.response
// RUN: %sourcekitd-test -req=format -line=5 -length=1 %s >>%t.response
// RUN: %sourcekitd-test -req=format -line=6 -length=1 %s >>%t.response
// RUN: %sourcekitd-test -req=format -line=7 -length=1 %s >>%t.response
// RUN: %sourcekitd-test -req=format -line=8 -length=1 %s >>%t.response
// RUN: %sourcekitd-test -req=format -line=14 -length=1 %s >>%t.response
// RUN: %sourcekitd-test -req=format -line=22 -length=1 %s >>%t.response
// RUN: %sourcekitd-test -req=format -line=27 -length=1 %s >>%t.response
// RUN: %sourcekitd-test -req=format -line=28 -length=1 %s >>%t.response
// RUN: %sourcekitd-test -req=format -line=29 -length=1 %s >>%t.response
// RUN: %sourcekitd-test -req=format -line=30 -length=1 %s >>%t.response
// RUN: %sourcekitd-test -req=format -line=31 -length=1 %s >>%t.response
// RUN: %sourcekitd-test -req=format -line=32 -length=1 %s >>%t.response
// RUN: FileCheck --strict-whitespace %s <%t.response
// CHECK: key.sourcetext: " var abc = 1"
// CHECK: key.sourcetext: " let a: String = {"
// CHECK: key.sourcetext: " let b = \"asdf\""
// CHECK: key.sourcetext: " return b"
// CHECK: key.sourcetext: " }()"
// CHECK: key.sourcetext: " }"
// " private static let durationTimeFormatter: NSDateComponentsFormatter = {"
// CHECK: key.sourcetext: " }()"
// " foo1(1)"
// CHECK: key.sourcetext: " {"
// CHECK: key.sourcetext: " test = {"
// CHECK: key.sourcetext: " return 0"
// CHECK: key.sourcetext: " }()"
// CHECK: key.sourcetext: " let test = {"
// CHECK: key.sourcetext: " return 0"
// CHECK: key.sourcetext: " }()"
|
apache-2.0
|
824cd20c04388a0da6b97158ef4519ea
| 31.414286 | 101 | 0.574515 | 3.123967 | false | true | false | false |
bontoJR/Cyclops
|
Polyphemus/Views/InfoView.swift
|
1
|
2006
|
//
// InfoView.swift
// Polyphemus
//
// Created by Junior B. on 04/10/15.
// Copyright © 2015 Bonto.ch. All rights reserved.
//
import Cocoa
class InfoView: NSView {
var textField: NSTextField!
override var allowsVibrancy: Bool { return true }
override var opaque: Bool {return false}
init() {
super.init(frame: NSZeroRect)
translatesAutoresizingMaskIntoConstraints = false
wantsLayer = true
layer?.backgroundColor = NSColor(deviceWhite: 0.9, alpha: 0.7).CGColor
// Add Vibrancy
let background = NSVisualEffectView(frame: NSZeroRect)
background.translatesAutoresizingMaskIntoConstraints = false
background.blendingMode = .BehindWindow
background.state = .Active
background.material = .Light
// Init Text
textField = NSTextField(frame: NSZeroRect)
textField.translatesAutoresizingMaskIntoConstraints = false
textField.alignment = .Center
textField.font = NSFont.systemFontOfSize(32.0)
textField.bezeled = false
textField.editable = false
textField.drawsBackground = false
textField.selectable = false
self.addSubview(textField)
let vertical = NSLayoutConstraint.constraintsWithVisualFormat("V:|-20-[textField]-20-|",
options: NSLayoutFormatOptions(rawValue: 0),
metrics: nil,
views: ["textField": self.textField])
let horizontal = NSLayoutConstraint.constraintsWithVisualFormat("H:|-20-[textField]-20-|",
options: NSLayoutFormatOptions(rawValue: 0),
metrics: nil,
views: ["textField": self.textField])
self.addConstraints(vertical)
self.addConstraints(horizontal)
}
required init?(coder: NSCoder) {
super.init(coder: coder)
}
override func drawRect(dirtyRect: NSRect) {
super.drawRect(dirtyRect)
}
}
|
isc
|
6a0abedeebd8fdfafc5c502071aa551b
| 29.378788 | 98 | 0.630424 | 5.262467 | false | false | false | false |
justinvyu/SwiftyDictionary
|
Pod/Classes/Thesaurus.swift
|
1
|
3186
|
//
// Thesaurus.swift
// Pods
//
// Created by Justin Yu on 11/25/15.
//
//
import Foundation
import Alamofire
import AEXML
public class SwiftyThesaurus: Reference {
// MARK: - Public Methods
public func fetchSynonyms(forWord word: String, callback: ArrayCallback) {
let request = DictionaryRequest(word: word, action: .Thesaurus, key: apiKey)
request.makeAPIRequest() { data in
let synonymArray = self.parseSynonymData(word, data: data)
callback(synonymArray)
}
}
public func fetchSynonyms(forWord word: String, limit: Int, callback: ArrayCallback) {
let request = DictionaryRequest(word: word, action: .Thesaurus, key: apiKey)
request.makeAPIRequest() { data in
let synonymArray = self.parseSynonymData(word, data: data)
callback(Array(synonymArray.prefix(limit > 0 ? limit : 0)))
}
}
// Separates synonyms by different definitions
public func fetchSynonymsWithSeparation(forWord word: String, callback: SeparatedArrayCallback) {
let request = DictionaryRequest(word: word, action: .Thesaurus, key: apiKey)
request.makeAPIRequest { data in
let separatedSynonymArray = self.parseSynonymDataWithSeparation(word, data: data)
callback(separatedSynonymArray)
}
}
// MARK: - Data Extraction
func parseSynonymData(word: String, data: AEXMLDocument) -> [String] {
var synonymArray: [String] = []
// Remove entries that don't match the word
if let relevantWords = data.root["entry"].allWithAttributes([ "id" : word ]) {
for term in relevantWords {
for def in term["sens"].all! {
synonymArray += arrayOfSynonyms(fromDef: def, withWord: word)
}
}
}
return uniq(synonymArray) // remove double entries
}
func parseSynonymDataWithSeparation(word: String, data: AEXMLDocument) -> [[String]] {
var synonymArray: [[String]] = []
if let relevantWords = data.root["entry"].allWithAttributes([ "id" : word ]) {
for term in relevantWords {
for def in term["sens"].all! {
synonymArray.append(arrayOfSynonyms(fromDef: def, withWord: word))
}
}
}
return synonymArray
}
func arrayOfSynonyms(fromDef def: AEXMLElement, withWord word: String) -> [String] {
var synonyms = def["syn"].value?.componentsSeparatedByString(", ")
synonyms = synonyms!.map { synonym in
var split = synonym.componentsSeparatedByString(" ")
// Filter for only words that matter
split = split.filter {
!$0.containsString("(") && !$0.containsString(")")
&& !$0.containsString("[") && !$0.containsString("]")
}
return split.joinWithSeparator(" ")
}
// Need to test again for a word like big(s)
let noRepeat = synonyms!.filter {
$0 != "" && $0 != word && !$0.containsString("(") && !$0.containsString(")")
}
return noRepeat
}
}
|
mit
|
fa2d47ff863217387b2fa08d3684563a
| 32.547368 | 101 | 0.593848 | 4.425 | false | false | false | false |
stormpath/stormpath-swift-example
|
Pods/Stormpath/Stormpath/Networking/APIClient.swift
|
1
|
2915
|
//
// APIClient.swift
// Stormpath
//
// Created by Edward Jiang on 12/2/16.
// Copyright © 2016 Stormpath. All rights reserved.
//
import UIKit
typealias APIRequestCallback = (APIResponse?, NSError?) -> Void
class APIClient {
weak var stormpath: Stormpath?
let session = URLSession(configuration: URLSessionConfiguration.ephemeral)
init(stormpath: Stormpath? = nil) {
self.stormpath = stormpath
}
func execute(request: APIRequest, callback: APIRequestCallback? = nil) {
var request = request
var authenticated = false
// If authenticated, add header
if let accessToken = stormpath?.accessToken {
request.headers["Authorization"] = "Bearer \(accessToken)"
authenticated = true
}
execute(request: request.asURLRequest) { (response, error) in
// Refresh token & retry request if 401
if response?.status == 401 && authenticated {
self.stormpath?.refreshAccessToken { (success, refreshError) in
if success {
if let accessToken = self.stormpath?.accessToken {
request.headers["Authorization"] = "Bearer \(accessToken)"
self.execute(request: request.asURLRequest, callback: callback)
} else {
callback?(response, error)
}
} else {
callback?(nil, error)
}
}
} else {
callback?(response, error)
}
}
}
private func execute(request: URLRequest, callback: APIRequestCallback? = nil) {
let task = session.dataTask(with: request) { (data, response, error) in
guard let data = data,
let response = response as? HTTPURLResponse else {
DispatchQueue.main.async {
callback?(nil, error as? NSError)
}
return
}
var apiResponse = APIResponse(status: response.statusCode)
apiResponse.headers = response.allHeaderFields as NSDictionary as? [String: String] ?? apiResponse.headers
apiResponse.body = data
DispatchQueue.main.async {
if response.statusCode / 100 != 2 {
callback?(nil, StormpathError.error(from: apiResponse))
} else {
callback?(apiResponse, nil)
}
}
}
task.resume()
}
}
enum ContentType: String {
case urlEncoded = "application/x-www-form-urlencoded",
json = "application/json"
}
enum APIRequestMethod: String {
case get = "GET",
post = "POST",
put = "PUT",
delete = "DELETE"
}
|
mit
|
b99dc1377459a50d616a2e165ed824e2
| 32.113636 | 118 | 0.530199 | 5.298182 | false | false | false | false |
muukii/Bulk
|
Sources/Bulk/Core/BulkSink.swift
|
1
|
1574
|
//
// BulkSink.swift
// Bulk
//
// Created by muukii on 2020/02/04.
//
import Foundation
public final class BulkSink<Element>: BulkSinkType {
private let targetQueue = DispatchQueue.init(label: "me.muukii.bulk")
private let targets: [AnyTarget<Element>]
private var timer: BulkBufferTimer!
private let _send: (Element) -> Void
private let _onFlush: () -> Void
private let buffer: AnyBuffer<Element>
public init(
buffer: AnyBuffer<Element>,
debounceDueTime: DispatchTimeInterval = .seconds(10),
targets: [AnyTarget<Element>]
) {
self.buffer = buffer
self.targets = targets
let output: ([Element]) -> Void = { elements in
targets.forEach {
$0.write(items: elements)
}
}
self.timer = BulkBufferTimer(interval: debounceDueTime, queue: targetQueue) {
let elements = buffer.purge()
output(elements)
}
self._send = { [targetQueue] newElement in
targetQueue.async {
switch buffer.write(element: newElement) {
case .flowed(let elements):
// TODO: align interface of Collection
return output(elements.map { $0 })
case .stored:
break
}
}
}
self._onFlush = {
let elements = buffer.purge()
output(elements)
}
}
deinit {
}
public func send(_ element: Element) {
targetQueue.async {
self._send(element)
}
}
public func flush() {
targetQueue.async {
self._onFlush()
}
}
}
|
mit
|
426bedee3a1dfcace5dea95d69f0bda8
| 18.675 | 81 | 0.582592 | 4.088312 | false | false | false | false |
linchaosheng/CSSwiftWB
|
SwiftCSWB 3/SwiftCSWB/Class/Home/C/WBPhotoBrowserViewController.swift
|
1
|
6227
|
//
// WBPhotoBrowserViewController.swift
// SwiftCSWB
//
// Created by LCS on 16/11/14.
// Copyright © 2016年 Apple. All rights reserved.
//
import UIKit
import SDWebImage
class WBPhotoBrowserViewController: UIViewController {
@IBOutlet weak var collectionView: UICollectionView!
@IBOutlet weak var flowLayout: UICollectionViewFlowLayout!
var picsUrl : [URL]?
var index : Int = 0
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor.white
// UI
setupUI()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
let indexPath = IndexPath(item: index, section: 0)
collectionView.scrollToItem(at: indexPath, at: UICollectionViewScrollPosition.left, animated: false)
}
// init(picsUrl : [NSURL], index : Int){
//
// super.init(nibName: nil, bundle: nil)
//
// }
// required init?(coder aDecoder: NSCoder) {
// fatalError("init(coder:) has not been implemented")
// }
fileprivate func setupUI(){
flowLayout.itemSize = UIScreen.main.bounds.size
flowLayout.minimumInteritemSpacing = 0
flowLayout.minimumLineSpacing = 0
collectionView.showsHorizontalScrollIndicator = false
collectionView.isPagingEnabled = true
collectionView.bounces = false
collectionView.register(PhotoBrowserCell.self, forCellWithReuseIdentifier: "PhotoBrowserCell")
}
@IBAction func closeOnclick(_ sender: AnyObject) {
dismiss(animated: true, completion: nil)
}
@IBAction func saveOnclick(_ sender: AnyObject) {
}
}
extension WBPhotoBrowserViewController : UICollectionViewDataSource{
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "PhotoBrowserCell", for: indexPath) as! PhotoBrowserCell
cell.imageUrl = picsUrl![indexPath.item]
return cell
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return picsUrl?.count ?? 0
}
}
extension WBPhotoBrowserViewController : UICollectionViewDelegate{
}
class PhotoBrowserCell : UICollectionViewCell {
var imageUrl : URL?{
didSet{
// 重置cell中控件的属性,解决cell重用时候的bug
resetScrollView()
imageView.sd_setImage(with: imageUrl) { (image, error, _, _) in
guard let image = image else {
CSprint("error\(error)")
return
}
// 获取图片尺寸计算frame
let rate = image.size.width / image.size.height
let imageW = UIScreen.main.bounds.width
let imageH = imageW / rate
// 设置imageView frame
self.imageView.frame = CGRect(x: 0, y: 0, width: imageW, height: imageH)
// 长图处理
if imageH > UIScreen.main.bounds.height{
// 设置contentSize
self.scrollView.contentSize = CGSize(width: 0, height: imageH)
}else{
// 设置contentInset
let insetMargin = (UIScreen.main.bounds.height - imageH) * 0.5
self.scrollView.contentInset = UIEdgeInsetsMake(insetMargin, 0, insetMargin, 0)
// 由于cell重用, 需要设置contentSize
self.scrollView.contentSize = CGSize(width: 0, height: 0)
}
}
}
}
fileprivate lazy var scrollView : UIScrollView = {
let sv = UIScrollView()
sv.maximumZoomScale = 2.0
sv.minimumZoomScale = 0.5
sv.delegate = self
return sv
}()
fileprivate lazy var imageView : UIImageView = UIImageView()
override init(frame: CGRect) {
super.init(frame: frame)
scrollView.backgroundColor = UIColor.purple
contentView.addSubview(scrollView)
scrollView.addSubview(imageView)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func layoutSubviews() {
super.layoutSubviews()
scrollView.frame = UIScreen.main.bounds
}
fileprivate func resetScrollView(){
// 缩放时候系统会改变scrollView的以下属性, 恢复scrollView
scrollView.contentInset = UIEdgeInsets.zero
scrollView.contentOffset = CGPoint.zero
scrollView.contentSize = CGSize.zero
// 缩放时候系统会改变transform, 恢复缩放后的imageView
imageView.transform = CGAffineTransform.identity
}
}
extension PhotoBrowserCell : UIScrollViewDelegate{
// 需要缩放的view
func viewForZooming(in scrollView: UIScrollView) -> UIView? {
return imageView
}
func scrollViewDidZoom(_ scrollView: UIScrollView) {
// 设置contentInset 使缩小时候图片居中
let screenW = UIScreen.main.bounds.width
let screenH = UIScreen.main.bounds.height
// 计算缩放时候的offset
// 注意缩放时frame的值变化,而bounds的值不变。且系统会将scrollView的contentSize设置为该frame
CSprint(imageView.frame)
CSprint(scrollView.contentSize)
var offsetX = (screenW - imageView.frame.width) * 0.5
var offsetY = (screenH - imageView.frame.height) * 0.5
// 当iamgeview放大时,防止offset出现负值导致无法滚动
offsetX = offsetX < 0 ? 0 : offsetX
offsetY = offsetY < 0 ? 0 : offsetY
scrollView.contentInset = UIEdgeInsetsMake(offsetY, offsetX, offsetY, offsetX)
}
}
|
apache-2.0
|
8169c98c196f52dfd5394f2d0238a381
| 30.099476 | 131 | 0.605387 | 5.098712 | false | false | false | false |
kmalkic/MKTween
|
MKTween/Period.swift
|
1
|
6119
|
//
// Period.swift
// MKTween
//
// Created by Kevin Malkic on 08/04/2019.
// Copyright © 2019 Kevin Malkic. All rights reserved.
//
import Foundation
public enum RepeatType {
case once
case pingPong
case forever
case foreverPingPong
}
public class TweenDirection {
public static let forward = TweenDirection(1)
public static let backward = TweenDirection(-1)
public let value: Double
private init(_ value: Double) {
self.value = value
}
public func reverse() -> TweenDirection {
if value == TweenDirection.forward.value {
return TweenDirection.backward
}
return TweenDirection.forward
}
}
public final class Period<T> : BasePeriod where T: Tweenable {
public typealias UpdateBlock = (_ period: Period<T>) -> ()
public typealias CompletionBlock = () -> ()
private(set) public var update: UpdateBlock?
private(set) public var completion: CompletionBlock?
private(set) public var name: String = UUID().uuidString
public let duration: TimeInterval
private(set) public var delay: TimeInterval
private(set) public var start: T
private(set) public var end: T
private(set) public var timingMode: Timing
private(set) public var startTimestamp: TimeInterval
private(set) public var lastTimestamp: TimeInterval
private(set) public var timePassed: TimeInterval = 0
private(set) public var paused: Bool = false
internal(set) public var progress: T = T.defaultValue()
private var didFinish = false
private var direction: TweenDirection
private(set) public var repeatType: RepeatType
private(set) public var repeatCount: Int
public init(start: T, end: T, duration: TimeInterval = 1, delay: TimeInterval = 0.0, timingMode: Timing = .linear) {
let time = Date().timeIntervalSinceReferenceDate
self.startTimestamp = time
self.lastTimestamp = time
self.duration = duration
self.delay = delay
self.start = start
self.end = end
self.timingMode = timingMode
self.direction = .forward
self.repeatType = .once
self.repeatCount = 1
}
public func updateInternal() -> Bool {
if didFinish {
return true
}
let newTime = Date().timeIntervalSinceReferenceDate
var dt = lastTimestamp.deltaTime(from: newTime)
lastTimestamp = newTime
if delay <= 0 && !paused {
dt = dt * direction.value
timePassed += dt
timePassed = timePassed.clamped(to: 0...duration)
progress = T.evaluate(start: start,
end: end,
time: timePassed,
duration: duration,
timingFunction: timingMode.timingFunction())
didFinish = direction.value == TweenDirection.forward.value ? timePassed >= duration : timePassed <= 0
if (didFinish) {
switch repeatType {
case .forever:
timePassed = 0
case .foreverPingPong:
direction = direction.reverse()
case .pingPong:
direction = direction.reverse()
repeatCount -= 1
default:
timePassed = 0
repeatCount -= 1
}
didFinish = repeatCount == 0 || repeatType == .once
}
return didFinish
} else if !paused {
delay -= dt;
}
return false
}
public func reverse() {
let start = self.end
let end = self.start
self.start = end
self.end = start
set(startTimestamp: lastTimestamp - (duration - timePassed + delay))
}
public func tweenValues(_ numberOfIntervals: UInt) -> [T] {
let tweenValues = stride(from: 1, through: Int(numberOfIntervals), by: 1).map { (i) -> T in
T.evaluate(start: start,
end: end,
time: TimeInterval(i) / TimeInterval(numberOfIntervals),
duration: duration,
timingFunction: timingMode.timingFunction())
}
return tweenValues
}
public func callUpdateBlock() {
update?(self)
}
public func callCompletionBlock() {
completion?()
}
public func pause() {
paused = true
}
public func resume() {
paused = false
}
public func set(startTimestamp time: TimeInterval) {
self.startTimestamp = time
self.lastTimestamp = time
}
@discardableResult public func set(name: String) -> Self {
self.name = name
return self
}
@discardableResult public func set(update: UpdateBlock? = nil, completion: CompletionBlock? = nil) -> Period<T> {
self.update = update
self.completion = completion
return self
}
@discardableResult public func set(timingMode: Timing) -> Period<T> {
self.timingMode = timingMode
return self
}
@discardableResult public func set(repeatType: RepeatType) -> Period<T> {
self.repeatType = repeatType
switch repeatType {
case .forever:
repeatCount = -1
case .foreverPingPong:
repeatCount = -1
case .pingPong:
repeatCount *= 2
case .once:
self.repeatCount = 1
}
return self
}
@discardableResult public func set(repeatCount: Int) -> Period<T> {
self.repeatCount = repeatCount
if repeatCount == -1 {
repeatType = .forever
}
switch repeatType {
case .pingPong:
self.repeatCount *= 2
case .once:
self.repeatCount = 1
default:
break
}
return self
}
}
|
mit
|
81921739228bf5295af83d8ff4535192
| 27.723005 | 120 | 0.558679 | 5.081395 | false | false | false | false |
Boilertalk/VaporFacebookBot
|
Sources/VaporFacebookBot/Webhooks/FacebookCallbackEntry.swift
|
1
|
993
|
//
// FacebookCallbackEntry.swift
// VaporFacebookBot
//
// Created by Koray Koska on 24/05/2017.
//
//
import Foundation
import Vapor
public final class FacebookCallbackEntry: JSONConvertible {
public var id: String
public var time: Int
public var messaging: [FacebookMessaging]
public init(json: JSON) throws {
id = try json.get("id")
time = try json.get("time")
if let a = json["messaging"]?.array {
var arr = [FacebookMessaging]()
for e in a {
arr.append(try FacebookMessaging(json: e))
}
messaging = arr
} else {
throw Abort(.badRequest, metadata: "messaging is not set or is not an array in FacebookCallbackEntry")
}
}
public func makeJSON() throws -> JSON {
var json = JSON()
try json.set("id", id)
try json.set("time", time)
try json.set("messaging", messaging.jsonArray())
return json
}
}
|
mit
|
5ff1958f8c340cdb554adca7d5ec3aae
| 22.642857 | 114 | 0.582075 | 4.207627 | false | false | false | false |
zom/Zom-iOS
|
Zom/Zom/Classes/View Controllers/ZomPhotosViewController.swift
|
1
|
1603
|
//
// ZomPhotosViewController.swift
// Zom
//
// Created by N-Pex on 2017-10-27.
//
import UIKit
import ChatSecureCore
import INSPhotoGallery
import MobileCoreServices
public protocol ZomPhotosViewControllerDelegate {
func didDeletePhoto(photo:ZomPhotoStreamImage)
}
open class ZomPhotosViewController: INSPhotosViewController {
open var delegate: ZomPhotosViewControllerDelegate?
open override func viewDidLoad() {
super.viewDidLoad()
super.deletePhotoHandler = {
(photo: INSPhotoViewable?) -> Void in
if let currentPhoto = photo as? ZomPhotoStreamImage {
currentPhoto.releaseImages()
OTRMediaFileManager.shared.deleteData(for: currentPhoto.mediaItem, buddyUniqueId: currentPhoto.message.threadId, completion: { (success, error) in
if success {
OTRDatabaseManager.shared.writeConnection?.asyncReadWrite({ (transaction) in
currentPhoto.mediaItem.transferProgress = 0
currentPhoto.mediaItem.save(with: transaction)
})
if let delegate = self.delegate {
delegate.didDeletePhoto(photo: currentPhoto)
}
}
}, completionQueue: nil)
}
}
if let overlayView = UINib(nibName: "ZomPhotoOverlayView", bundle: nil).instantiate(withOwner: nil, options: nil)[0] as? INSPhotosOverlayViewable {
self.overlayView = overlayView
}
}
}
|
mpl-2.0
|
71b4db489db5155486a693faf4603820
| 34.622222 | 162 | 0.61073 | 5.361204 | false | false | false | false |
STShenZhaoliang/SwiftDrawRect
|
SwiftDrawRect/SwiftDrawRect/LineChart.swift
|
1
|
1068
|
//
// LineChart.swift
// SwiftDrawRect
//
// Created by 沈兆良 on 16/3/8.
// Copyright © 2016年 沈兆良. All rights reserved.
//
import UIKit
class LineChart: UIView {
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
setNeedsDisplay()
}
override func drawRect(rect: CGRect) {
RGB(230, g: 230, b: 230).setFill()
UIRectFill(rect)
let array = Array<Int>.arrayRandom()
let w = rect.width / CGFloat(array.count + 1)
var pointStart = CGPointMake(0, rect.height)
var pointEnd = CGPointZero
for i in 0..<array.count {
pointEnd.x += w
pointEnd.y = (1 - CGFloat(array[i]) / 100.0) * rect.height
let path = UIBezierPath()
path.moveToPoint(pointStart)
path.addLineToPoint(pointEnd)
path.lineWidth = 3
path.lineJoinStyle = CGLineJoin.Round
UIColor.colorRandom().set()
path.stroke()
pointStart = pointEnd
}
}
}
|
apache-2.0
|
54ebcd299f1d9fab9e7eeb16d0437b77
| 23.488372 | 82 | 0.566002 | 4.05 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.