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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
to4iki/conference-app-2017-ios | conference-app-2017/presentation/viewController/FloorMapViewController.swift | 1 | 2331 | import UIKit
final class FloorMapViewController: UIViewController {
@IBOutlet fileprivate weak var scrollView: UIScrollView!
@IBOutlet fileprivate weak var imageView: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
setNoTitleBackButton()
scrollView.delegate = self
let doubleTapGesture = UITapGestureRecognizer(target: self, action: .didScrollViewDoubleTap)
doubleTapGesture.numberOfTapsRequired = 2
scrollView.addGestureRecognizer(doubleTapGesture)
}
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
super.viewWillTransition(to: size, with: coordinator)
resetScrollView()
}
}
extension FloorMapViewController {
static func instantiate() -> FloorMapViewController {
return Storyboard.floorMap.instantiate(type: FloorMapViewController.self)
}
}
extension FloorMapViewController {
func didScrollViewDoubleTap(gesture: UITapGestureRecognizer) {
guard gesture.state == UIGestureRecognizerState.ended else { return }
if scrollView.zoomScale < scrollView.maximumZoomScale {
let zoomedRect = zoomRectForScale(scrollView.maximumZoomScale, center: gesture.location(in: gesture.view))
scrollView.zoom(to: zoomedRect, animated: true)
} else {
scrollView.setZoomScale(1.0, animated: true)
}
}
fileprivate func resetScrollView() {
scrollView.setZoomScale(1.0, animated: true)
scrollView.layer.position = CGPoint(x: self.view.frame.width/2, y: self.view.frame.height/2)
}
private func zoomRectForScale(_ scale: CGFloat, center: CGPoint) -> CGRect {
let size = CGSize(width: scrollView.frame.size.width / scale, height: scrollView.frame.size.height / scale)
let origin = CGPoint(x: center.x - size.width / 2.0, y: center.y - size.height / 2.0)
return CGRect(origin: origin, size: size)
}
}
// MARK: - UIScrollViewDelegate
extension FloorMapViewController: UIScrollViewDelegate {
func viewForZooming(in scrollView: UIScrollView) -> UIView? {
return imageView
}
}
// MARK: - Selector
private extension Selector {
static let didScrollViewDoubleTap = #selector(FloorMapViewController.didScrollViewDoubleTap)
}
| apache-2.0 | f8a6d7cbce05fc1ccc1dd04120cc7664 | 37.213115 | 118 | 0.714715 | 5.012903 | false | false | false | false |
chunzhiying/MeiPaiDemo | MeiPaiDemo/MeiPaiDemo/RecordModel.swift | 1 | 7268 | //
// RecordModel.swift
// MeiPaiDemo
//
// Created by 陈智颖 on 15/10/3.
// Copyright © 2015年 YY. All rights reserved.
//
import Foundation
import AVFoundation
import AssetsLibrary
class RecordModel {
// MARK: - Property
private var outputFilePath: String {
return NSTemporaryDirectory().stringByAppendingString("myMovie\(self.outputFilePathAry.count).mov")
}
var outputFileUrl: NSURL {
return NSURL.fileURLWithPath(self.outputFilePath)
}
private var outputFilePathAry = [String]()
private var outputFileUrlAry: [NSURL] {
return outputFilePathAry.map({
return NSURL.fileURLWithPath($0)
})
}
private var finalUrl = NSURL(fileURLWithPath: NSTemporaryDirectory().stringByAppendingString("myMovieFinal.mov"))
// MARK: - Private Handel Video
func saveToCameraRoll(completion: () -> Void) {
func createEndingVideo() {
}
func mergeVideo() {
guard outputFileUrlAry.count > 0 else {
saveVideo(outputFileUrlAry.first!)
return }
let assertAry: [AVAsset?] = outputFileUrlAry.map({ return AVAsset(URL: $0) })
let mixComposition = AVMutableComposition()
var instructionAry = [AVMutableVideoCompositionLayerInstruction]()
let mainInstruction = AVMutableVideoCompositionInstruction()
// 正片的track
let videoTrack = mixComposition.addMutableTrackWithMediaType(AVMediaTypeVideo, preferredTrackID: kCMPersistentTrackID_Invalid)
var videoTimeDuration = kCMTimeZero
for var i = 0; i < assertAry.count; i++ {
guard let assert = assertAry[i] else { continue }
do {
try videoTrack.insertTimeRange(CMTimeRangeMake(CMTimeMake(1, 15), assert.duration),
ofTrack: assert.tracksWithMediaType(AVMediaTypeVideo).first!,
atTime: videoTimeDuration)
} catch {
continue
}
videoTimeDuration = CMTimeAdd(videoTimeDuration, assert.duration)
}
let instruction = videoCompositionInstructionForTrack(videoTrack, asset:assertAry.first!!)
instruction.setOpacity(0, atTime: videoTimeDuration) //遮挡后面轨道的图像
instructionAry += [instruction]
mainInstruction.timeRange = CMTimeRangeMake(kCMTimeZero, videoTimeDuration)
mainInstruction.layerInstructions = instructionAry
// 处理特效
let mainComposition = AVMutableVideoComposition()
mainComposition.frameDuration = CMTimeMake(1, 30)
mainComposition.instructions = [mainInstruction]
mainComposition.renderSize = UIScreen.mainScreen().bounds.size
let exporter = AVAssetExportSession(asset: mixComposition, presetName: AVAssetExportPresetHighestQuality)
exporter?.outputURL = finalUrl
exporter?.outputFileType = AVFileTypeQuickTimeMovie;
exporter?.shouldOptimizeForNetworkUse = true;
exporter?.videoComposition = mainComposition
exporter?.exportAsynchronouslyWithCompletionHandler() {
dispatch_async(dispatch_get_main_queue()) {
if exporter?.status == .Completed {
saveVideo(exporter!.outputURL!)
}
}
}
}
func saveVideo(url: NSURL) {
ALAssetsLibrary().writeVideoAtPathToSavedPhotosAlbum(url) { (url: NSURL!, error: NSError?) in
if let errorDescription = error?.description {
print("写入错误:\(errorDescription)")
} else {
print("写入成功")
}
self.deleteTempVideo()
completion()
}
}
mergeVideo()
}
func deleteTempVideo() {
let fileManager = NSFileManager.defaultManager()
for path in outputFilePathAry {
do {
try fileManager.removeItemAtPath(path)
} catch {
continue
}
}
do {
try fileManager.removeItemAtPath((finalUrl.path)!)
} catch {}
outputFilePathAry.removeAll()
}
// MARK: - Tool
func videoCompositionInstructionForTrack(track: AVCompositionTrack, asset: AVAsset) -> AVMutableVideoCompositionLayerInstruction {
let instruction = AVMutableVideoCompositionLayerInstruction(assetTrack: track)
let assetTrack = asset.tracksWithMediaType(AVMediaTypeVideo)[0]
let scaleToFitRatio = UIScreen.mainScreen().bounds.width / assetTrack.naturalSize.height
let scaleFactor = CGAffineTransformMakeScale(scaleToFitRatio,scaleToFitRatio)
let rotation = CGAffineTransformRotate(scaleFactor, CGFloat(M_PI_2))
let translation = CGAffineTransformTranslate(rotation,0, -assetTrack.naturalSize.height)
instruction.setTransform(translation, atTime: kCMTimeZero)
return instruction
}
func applyVideoEffectsToComposition(composition: AVMutableVideoComposition, rect: CGRect) {
let videoLayer = CALayer()
let parentLayer = CALayer()
let maskLayer = CALayer()
let textLayer = CATextLayer()
maskLayer.frame = rect
videoLayer.frame = rect
parentLayer.frame = rect
textLayer.string = "chun.."
textLayer.position = CGPointMake(rect.size.width / 2, rect.size.height / 2)
parentLayer.addSublayer(videoLayer)
parentLayer.addSublayer(maskLayer)
parentLayer.addSublayer(textLayer)
composition.animationTool = AVVideoCompositionCoreAnimationTool(postProcessingAsVideoLayer: videoLayer, inLayer: parentLayer)
let contentImage = CIImage(CGImage: (UIImage(named: "Baby-Lufy")?.CGImage)!)
maskLayer.contents = contentImage
// filter
let context = CIContext(options: nil)
let filter = CIFilter(name: "CIGaussianBlur")
filter?.setValue(contentImage, forKey: kCIInputImageKey)
filter?.setValue(2, forKey: "inputRadius")
guard let filterCIImage = filter?.outputImage else { return }
let filterImage = context.createCGImage(filterCIImage, fromRect: filterCIImage.extent)
// animation
let transition = CATransition()
transition.type = kCATransitionFade
transition.duration = 1
maskLayer.addAnimation(transition, forKey: nil)
maskLayer.contents = filterImage
}
// MARK: - Public Method
func addNewVideoFilePath() {
outputFilePathAry += [outputFilePath]
}
}
| apache-2.0 | ffa7c287c9ccd556100f9367bc277adb | 34.348039 | 138 | 0.591457 | 6.03431 | false | false | false | false |
metasmile/DKImagePickerController | DKImagePickerController/View/DKAssetGroupDetailVC.swift | 1 | 28204 | //
// DKAssetGroupDetailVC.swift
// DKImagePickerController
//
// Created by ZhangAo on 15/8/10.
// Copyright (c) 2015年 ZhangAo. All rights reserved.
//
import UIKit
import AVFoundation
import Photos
private let DKImageCameraIdentifier = "DKImageCameraIdentifier"
private let DKImageAssetIdentifier = "DKImageAssetIdentifier"
private let DKMediaAssetIdentifier = "DKMediaAssetIdentifier"
// Show all images in the asset group
internal class DKAssetGroupDetailVC: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource, DKGroupDataManagerObserver {
class DKImageCameraCell: UICollectionViewCell {
var didCameraButtonClicked: (() -> Void)?
private weak var cameraButton: UIButton!
override init(frame: CGRect) {
super.init(frame: frame)
let cameraButton = UIButton(frame: frame)
cameraButton.addTarget(self, action: #selector(DKImageCameraCell.cameraButtonClicked), forControlEvents: .TouchUpInside)
cameraButton.autoresizingMask = [.FlexibleWidth, .FlexibleHeight]
self.contentView.addSubview(cameraButton)
self.cameraButton = cameraButton
self.contentView.backgroundColor = UIColor(white: 0.9, alpha: 1.0)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func setCameraImage(cameraImage: UIImage) {
self.cameraButton.setImage(cameraImage, forState: .Normal)
}
func cameraButtonClicked() {
if let didCameraButtonClicked = self.didCameraButtonClicked {
didCameraButtonClicked()
}
}
} /* DKImageCameraCell */
class DKAssetCell: UICollectionViewCell {
internal var checkedBackgroundColor:UIColor?
internal var uncheckedBackgroundColor:UIColor?
class DKImageCheckView: UIView {
internal lazy var checkImageView: UIImageView = {
let imageView = UIImageView()
return imageView
}()
internal lazy var checkLabel: UILabel = {
let label = UILabel()
label.textAlignment = .Right
return label
}()
override init(frame: CGRect) {
super.init(frame: frame)
self.addSubview(checkImageView)
self.addSubview(checkLabel)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func layoutSubviews() {
super.layoutSubviews()
self.checkImageView.frame = self.bounds
self.checkLabel.frame = CGRect(x: 0, y: 5, width: self.bounds.width - 5, height: 20)
}
} /* DKImageCheckView */
private var asset: DKAsset!
private let thumbnailImageView: UIImageView = {
let thumbnailImageView = UIImageView()
thumbnailImageView.contentMode = .ScaleAspectFill
thumbnailImageView.clipsToBounds = true
return thumbnailImageView
}()
private let checkView = DKImageCheckView()
override var selected: Bool {
didSet {
checkView.hidden = !super.selected
}
}
override init(frame: CGRect) {
super.init(frame: frame)
self.thumbnailImageView.frame = self.bounds
self.contentView.addSubview(self.thumbnailImageView)
self.contentView.addSubview(checkView)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func layoutSubviews() {
super.layoutSubviews()
self.thumbnailImageView.frame = self.bounds
checkView.frame = self.thumbnailImageView.frame
}
} /* DKAssetCell */
private static let TagForDurationLabel:Int = 1
private static let TagForIconImageView:Int = 2
class DKMediaAssetCell: DKAssetCell {
override var asset: DKAsset! {
didSet {
let videoDurationLabel = self.videoInfoView.viewWithTag(TagForDurationLabel) as! UILabel
if self.asset.duration>0 {
let minutes: Int = Int(asset.duration!) / 60
let seconds: Int = Int(round(asset.duration!)) % 60
videoDurationLabel.text = String(format: "\(minutes):%02d", seconds)
videoDurationLabel.hidden = false
}else{
videoDurationLabel.text = nil
videoDurationLabel.hidden = true
}
}
}
private var assetIconImage: UIImage? {
didSet {
self.videoInfoView.hidden = self.assetIconImage == nil
(self.videoInfoView.viewWithTag(TagForIconImageView) as! UIImageView).image = self.assetIconImage
}
}
override var selected: Bool {
didSet {
if super.selected {
self.videoInfoView.backgroundColor = self.checkedBackgroundColor ?? UIColor(red: 20 / 255, green: 129 / 255, blue: 252 / 255, alpha: 1)
} else {
self.videoInfoView.backgroundColor = self.uncheckedBackgroundColor ?? UIColor(white: 0.0, alpha: 0.7)
}
}
}
private lazy var videoInfoView: UIView = {
let mediaInfoView = UIView(frame: CGRect(x: 0, y: 0, width: 100, height: 0))
let mediaIconImageView = UIImageView(image: DKImageResource.videoCameraIcon())
mediaIconImageView.tag = TagForIconImageView
mediaInfoView.addSubview(mediaIconImageView)
mediaIconImageView.center = CGPoint(x: mediaIconImageView.bounds.width / 2 + 7, y: mediaInfoView.bounds.height / 2)
mediaIconImageView.autoresizingMask = [.FlexibleBottomMargin, .FlexibleTopMargin]
mediaIconImageView.contentMode = .ScaleAspectFit
let videoDurationLabel = UILabel()
videoDurationLabel.tag = TagForDurationLabel
videoDurationLabel.textAlignment = .Right
videoDurationLabel.font = UIFont.systemFontOfSize(12)
videoDurationLabel.textColor = UIColor.whiteColor()
mediaInfoView.addSubview(videoDurationLabel)
videoDurationLabel.frame = CGRect(x: 0, y: 0, width: mediaInfoView.bounds.width - 7, height: mediaInfoView.bounds.height)
videoDurationLabel.autoresizingMask = [.FlexibleWidth, .FlexibleHeight]
return mediaInfoView
}()
override init(frame: CGRect) {
super.init(frame: frame)
self.contentView.addSubview(videoInfoView)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func layoutSubviews() {
super.layoutSubviews()
let height: CGFloat = 30
self.videoInfoView.frame = CGRect(x: 0, y: self.contentView.bounds.height - height,
width: self.contentView.bounds.width, height: height)
}
} /* DKMediaAssetCell */
private lazy var selectGroupButton: UIButton = {
let button = UIButton()
let globalTitleColor = UINavigationBar.appearance().titleTextAttributes?[NSForegroundColorAttributeName] as? UIColor
button.setTitleColor(globalTitleColor ?? UIColor.blackColor(), forState: .Normal)
let globalTitleFont = UINavigationBar.appearance().titleTextAttributes?[NSFontAttributeName] as? UIFont
button.titleLabel!.font = globalTitleFont ?? UIFont.systemFontOfSize(18.0)
button.addTarget(self, action: #selector(DKAssetGroupDetailVC.showGroupSelector), forControlEvents: .TouchUpInside)
return button
}()
internal var selectedGroupId: String?
internal weak var imagePickerController: DKImagePickerController!
private var groupListVC: DKAssetGroupListVC!
private var hidesCamera: Bool = false
internal var collectionView: UICollectionView!
private var footerView: UIView?
private var currentViewSize: CGSize!
override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
if let currentViewSize = self.currentViewSize where CGSizeEqualToSize(currentViewSize, self.view.bounds.size) {
return
} else {
currentViewSize = self.view.bounds.size
}
self.collectionView?.collectionViewLayout.invalidateLayout()
}
private lazy var groupImageRequestOptions: PHImageRequestOptions = {
let options = PHImageRequestOptions()
options.deliveryMode = .Opportunistic
options.resizeMode = .Fast
return options
}()
override func viewDidLoad() {
super.viewDidLoad()
let layout = self.imagePickerController.UIDelegate.layoutForImagePickerController(self.imagePickerController).init()
self.collectionView = UICollectionView(frame: CGRectZero, collectionViewLayout: layout)
self.collectionView.backgroundColor = UICollectionView.appearance().backgroundColor
?? self.imagePickerController.UIDelegate.imagePickerControllerCollectionViewBackgroundColor()
self.collectionView.allowsMultipleSelection = true
self.collectionView.delegate = self
self.collectionView.dataSource = self
self.collectionView.registerClass(DKImageCameraCell.self, forCellWithReuseIdentifier: DKImageCameraIdentifier)
self.collectionView.registerClass(DKAssetCell.self, forCellWithReuseIdentifier: DKImageAssetIdentifier)
self.collectionView.registerClass(DKMediaAssetCell.self, forCellWithReuseIdentifier: DKMediaAssetIdentifier)
self.view.addSubview(self.collectionView)
self.footerView = self.imagePickerController.UIDelegate.imagePickerControllerFooterView(self.imagePickerController)
if let footerView = self.footerView {
self.view.addSubview(footerView)
}
self.hidesCamera = self.imagePickerController.sourceType == .Photo
self.checkPhotoPermission()
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
if let footerView = self.footerView {
footerView.frame = CGRectMake(0, self.view.bounds.height - footerView.bounds.height, self.view.bounds.width, footerView.bounds.height)
self.collectionView.frame = CGRectMake(0, 0, self.view.bounds.width, self.view.bounds.height - footerView.bounds.height)
} else {
self.collectionView.frame = self.view.bounds
}
}
func invalidateContents(){
self.selectGroupButton.setAttributedTitle(nil, forState: .Normal)
for cell:DKAssetCell in self.collectionView?.visibleCells() as! [DKAssetCell] {
cell.thumbnailImageView.image = nil
cell.checkView.checkImageView.image = nil;
if cell is DKMediaAssetCell{
(cell as? DKMediaAssetCell)?.assetIconImage = nil
}
}
DKImageManager.sharedInstance.invalidateCaches()
self.invalidateCaches(false)
}
func invalidateCaches(fromMemoryWarning:Bool){
self.invalidateCachedStaticResources()
self.invalidateCachedAssetsOfCurrentGroup()
if fromMemoryWarning{
self.cachedThumbnailImages = nil
}
}
func invalidateCachedStaticResources(){
self.cachedCheckedImage = nil
self.cachedPhotoIconInfo = nil
self.cachedLivePhotoIconInfo = nil
self.cachedVideoIconInfo = nil
}
func invalidateCachedAssetsOfCurrentGroup(){
self.cachedAssets = nil
self.cachedGroups = nil
}
internal func checkPhotoPermission() {
func photoDenied() {
self.view.addSubview(DKPermissionView.permissionView(.Photo))
self.view.backgroundColor = UIColor.blackColor()
self.collectionView?.hidden = true
}
func setup() {
getImageManager().groupDataManager.addObserver(self)
self.groupListVC = DKAssetGroupListVC(selectedGroupDidChangeBlock: { [unowned self] groupId in
self.selectAssetGroup(groupId)
}, defaultAssetGroup: self.imagePickerController.defaultAssetGroup)
let style = DKAssetGroupCellStyle()
style.separatorLineColor = self.imagePickerController.UIDelegate.imagePickerControllerAlbumSelectListSeparatorColor()
style.countLabelColor = self.imagePickerController.UIDelegate.imagePickerControllerAlbumSelectListCountLabelTextColor()
style.nameLabelColor = self.imagePickerController.UIDelegate.imagePickerControllerAlbumSelectListNameLabelTextColor()
style.checkedIconImage = self.imagePickerController.UIDelegate.imagePickerControllerAlbumSelectListCheckedIconImage()
style.checkedIconTintColor = self.imagePickerController.UIDelegate.imagePickerControllerAlbumSelectListTCheckedIconImageTintColor()
self.groupListVC.groupListCellStyle = style
self.groupListVC.loadGroups()
}
DKImageManager.checkPhotoPermission { granted in
granted ? setup() : photoDenied()
}
}
func selectAssetGroup(groupId: String?) {
if self.selectedGroupId == groupId {
return
}
self.selectedGroupId = groupId
self.reloadCollectionViews()
}
func reloadAllCurrentGroupData() {
getImageManager().invalidate()
self.groupListVC.loadGroups()
self.groupListVC.tableView.reloadData()
self.reloadCollectionViews()
}
func reloadCollectionViews(){
self.updateTitleView()
if(self.imagePickerController.deselectAllWhenChangingAlbum
|| self.imagePickerController.allowCirculatingSelection){
self.imagePickerController.deselectAllAssets(false)
}
self.invalidateCachedAssetsOfCurrentGroup()
self.collectionView!.reloadData()
}
func updateTitleView() {
let group = getImageManager().groupDataManager.fetchGroupWithGroupId(self.selectedGroupId!)
self.title = group.groupName
let groupsCount = getImageManager().groupDataManager.groupIds?.count
if groupsCount > 1{
//create pretty arrow
let addingDownArrowStr = " \u{FE40}"
let originalFont = self.selectGroupButton.titleLabel!.font
self.selectGroupButton.setAttributedTitle(nil, forState: .Normal)
self.selectGroupButton.setTitle(group.groupName + addingDownArrowStr, forState: .Normal)
let attributedString = NSMutableAttributedString(attributedString: (self.selectGroupButton.titleLabel?.attributedText)!)
let rangeToApply = NSRange(location: attributedString.string.characters.count-addingDownArrowStr.characters.count, length: addingDownArrowStr.characters.count)
//To beautify overall, like the Apple music app's, size, baseline offset and kerning of the arrow symbol should be smaller than label.
attributedString.enumerateAttribute(NSFontAttributeName, inRange:rangeToApply, options:.LongestEffectiveRangeNotRequired,
usingBlock: { value, range, stop in
let font = value as! UIFont
attributedString.addAttribute(NSFontAttributeName, value:font.fontWithSize(originalFont.pointSize/1.5), range:range)
})
attributedString.addAttribute(NSBaselineOffsetAttributeName, value: -2.5, range: rangeToApply)
attributedString.addAttribute(NSKernAttributeName, value: -1.5, range: rangeToApply)
self.selectGroupButton.setAttributedTitle(attributedString, forState: .Normal)
self.selectGroupButton.titleEdgeInsets = UIEdgeInsetsMake(3, 0, 0, 0)
}else{
self.selectGroupButton.setTitle(group.groupName, forState: .Normal)
self.selectGroupButton.titleEdgeInsets = UIEdgeInsetsZero
}
self.selectGroupButton.sizeToFit()
self.selectGroupButton.enabled = groupsCount > 1
self.navigationItem.titleView = self.selectGroupButton
}
func showGroupSelector() {
DKPopoverViewController.popoverViewController(self.groupListVC, fromView: self.selectGroupButton)
}
// MARK: - Cells
func cameraCellForIndexPath(indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView!.dequeueReusableCellWithReuseIdentifier(DKImageCameraIdentifier, forIndexPath: indexPath) as! DKImageCameraCell
cell.setCameraImage(self.imagePickerController.UIDelegate.imagePickerControllerCameraImage())
cell.didCameraButtonClicked = { [unowned self] in
if UIImagePickerController.isSourceTypeAvailable(.Camera) {
if self.imagePickerController.selectedAssets.count < self.imagePickerController.maxSelectableCount {
self.imagePickerController.presentCamera()
} else {
self.imagePickerController.UIDelegate.imagePickerControllerDidReachMaxLimit(self.imagePickerController)
}
}
}
return cell
}
var cachedCheckedImage:UIImage?
var cachedLivePhotoIconInfo:(String, UIImage?)?
var cachedPhotoIconInfo:(String, UIImage?)?
var cachedVideoIconInfo:(String, UIImage?)?
var cachedGroups:[String:DKAssetGroup]?
var cachedAssets:[String:[Int:DKAsset]]?
var cachedThumbnailImages:[String:UIImage]?
func assetCellForIndexPath(indexPath: NSIndexPath) -> UICollectionViewCell {
let assetIndex = (indexPath.row - (self.hidesCamera ? 0 : 1))
if cachedGroups == nil{
cachedGroups = [:]
}
if cachedGroups!.indexForKey(self.selectedGroupId!) == nil{
self.cachedGroups![self.selectedGroupId!] = getImageManager().groupDataManager.fetchGroupWithGroupId(self.selectedGroupId!)
}
let group = cachedGroups![self.selectedGroupId!]!
if cachedAssets == nil{
cachedAssets = [:]
}
if cachedAssets!.indexForKey(group.groupId) == nil{
self.cachedAssets![group.groupId] = [:]
}
if self.cachedAssets![group.groupId]!.indexForKey(assetIndex) == nil{
self.cachedAssets![group.groupId]![assetIndex] = getImageManager().groupDataManager.fetchAssetWithGroup(group, index: assetIndex)
}
let asset:DKAsset = self.cachedAssets![group.groupId]![assetIndex]!
var cell: DKAssetCell!
let cellSettingsByAsset:(String, UIImage?) = self.cellSettingsByAsset(asset)
let identifier: String! = cellSettingsByAsset.0
let assetIconImage:UIImage? = cellSettingsByAsset.1
//configure initial cell appearance
cell = self.collectionView!.dequeueReusableCellWithReuseIdentifier(identifier, forIndexPath: indexPath) as! DKAssetCell
cell.checkView.checkImageView.tintColor = self.imagePickerController.UIDelegate.imagePickerControllerCheckedImageTintColor()
cell.checkView.checkImageView.image = self.cellCheckedImage()
cell.checkedBackgroundColor = self.imagePickerController.UIDelegate.imagePickerControllerCheckedBackgroundColor()
cell.uncheckedBackgroundColor = self.imagePickerController.UIDelegate.imagePickerControllerUnCheckedBackgroundColor()
cell.checkView.checkLabel.hidden = self.imagePickerController.UIDelegate.imagePickerControllerCheckedNumberHidden()
cell.checkView.checkLabel.font = self.imagePickerController.UIDelegate.imagePickerControllerCheckedNumberFont()
cell.checkView.checkLabel.textColor = self.imagePickerController.UIDelegate.imagePickerControllerCheckedNumberColor()
//set asset's icon image
(cell as? DKMediaAssetCell)?.assetIconImage = assetIconImage
cell.asset = asset
let tag = indexPath.row + 1
cell.tag = tag
let itemSize = self.collectionView!.collectionViewLayout.layoutAttributesForItemAtIndexPath(indexPath)!.size
if cachedThumbnailImages==nil{
cachedThumbnailImages = [:]
}
if cachedThumbnailImages!.indexForKey((asset.originalAsset?.localIdentifier)!) == nil{
//FIXME: huge memory leaks. but why? it just uses pure ios api.
asset.fetchImageWithSize(itemSize.toPixel(), options: self.groupImageRequestOptions, contentMode: .AspectFill) { (image, info) in
if cell.tag == tag {
cell.thumbnailImageView.image = image
}
self.cachedThumbnailImages![(asset.originalAsset?.localIdentifier)!] = image
}
}else{
cell.thumbnailImageView.image = self.cachedThumbnailImages![(asset.originalAsset?.localIdentifier)!]
}
if let index = self.imagePickerController.selectedAssets.indexOf(asset) {
cell.selected = true
cell.checkView.checkLabel.text = "\(index + 1)"
self.collectionView!.selectItemAtIndexPath(indexPath, animated: false, scrollPosition: UICollectionViewScrollPosition.None)
} else {
cell.selected = false
self.collectionView!.deselectItemAtIndexPath(indexPath, animated: false)
}
return cell
}
func cellCheckedImage() -> UIImage?{
if cachedCheckedImage == nil{
cachedCheckedImage = (self.imagePickerController.UIDelegate.imagePickerControllerCheckedImage()
?? DKImageResource.checkedImage()).imageWithRenderingMode(.AlwaysTemplate)
}
return cachedCheckedImage
}
func cellSettingsByAsset(asset: DKAsset) -> (String, UIImage?) {
let originalAsset = asset.originalAsset!
switch (originalAsset.mediaType, originalAsset.mediaSubtypes){
case let (.Image, x) where x.contains(.PhotoLive): //Live Photo
if self.cachedLivePhotoIconInfo == nil{
self.cachedLivePhotoIconInfo = (
DKMediaAssetIdentifier,
self.imagePickerController.UIDelegate.imagePickerControllerAssetLivePhotoIconImage()
)
}
return self.cachedLivePhotoIconInfo!
case (.Image, _):
if self.cachedPhotoIconInfo == nil{
self.cachedPhotoIconInfo = (
DKImageAssetIdentifier,
self.imagePickerController.UIDelegate.imagePickerControllerAssetPhotoIconImage()
)
}
return self.cachedPhotoIconInfo!
case (.Video, _):
if self.cachedVideoIconInfo == nil{
self.cachedVideoIconInfo = (
DKMediaAssetIdentifier,
self.imagePickerController.UIDelegate.imagePickerControllerAssetVideoIconImage()
?? DKImageResource.videoCameraIcon()
)
}
return self.cachedVideoIconInfo!
default:
return (DKImageAssetIdentifier, nil)
}
}
// MARK: - UICollectionViewDelegate, UICollectionViewDataSource methods
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
guard let selectedGroup = self.selectedGroupId else { return 0 }
let group = getImageManager().groupDataManager.fetchGroupWithGroupId(selectedGroup)
return (group.totalCount ?? 0) + (self.hidesCamera ? 0 : 1)
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
if indexPath.row == 0 && !self.hidesCamera {
return self.cameraCellForIndexPath(indexPath)
} else {
return self.assetCellForIndexPath(indexPath)
}
}
func collectionView(collectionView: UICollectionView, shouldSelectItemAtIndexPath indexPath: NSIndexPath) -> Bool {
if let firstSelectedAsset = self.imagePickerController.selectedAssets.first,
selectedAsset = (collectionView.cellForItemAtIndexPath(indexPath) as? DKAssetCell)?.asset
where self.imagePickerController.allowMultipleTypes == false && firstSelectedAsset.isVideo != selectedAsset.isVideo {
let alert = UIAlertController(
title: DKImageLocalizedStringWithKey("selectPhotosOrVideos")
, message: DKImageLocalizedStringWithKey("selectPhotosOrVideosError")
, preferredStyle: .Alert)
alert.addAction(UIAlertAction(title: DKImageLocalizedStringWithKey("ok"), style: .Cancel) { _ in })
self.imagePickerController.presentViewController(alert, animated: true){}
return false
}
let didReachMaxSelectableCount = self.imagePickerController.selectedAssets.count >= self.imagePickerController.maxSelectableCount
if didReachMaxSelectableCount {
if self.imagePickerController.allowCirculatingSelection {
let currentSelectedIndexPaths:[NSIndexPath] = collectionView.indexPathsForSelectedItems()!
let firstSelectedIndexPath:NSIndexPath = currentSelectedIndexPaths.first!
if let removingAsset:DKAsset = (collectionView.cellForItemAtIndexPath(firstSelectedIndexPath) as! DKAssetCell).asset{
self.imagePickerController.deselectImage(removingAsset)
}
UIView.performWithoutAnimation({
collectionView.reloadItemsAtIndexPaths(currentSelectedIndexPaths)
})
return true
}else{
self.imagePickerController.UIDelegate.imagePickerControllerDidReachMaxLimit(self.imagePickerController)
return false
}
}
return true
}
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
let selectedAsset = (collectionView.cellForItemAtIndexPath(indexPath) as? DKAssetCell)?.asset
self.imagePickerController.selectImage(selectedAsset!)
if let cell = collectionView.cellForItemAtIndexPath(indexPath) as? DKAssetCell {
cell.checkView.checkLabel.text = "\(self.imagePickerController.selectedAssets.count)"
}
}
func collectionView(collectionView: UICollectionView, didDeselectItemAtIndexPath indexPath: NSIndexPath) {
if let removedAsset = (collectionView.cellForItemAtIndexPath(indexPath) as? DKAssetCell)?.asset {
let removedIndex = self.imagePickerController.selectedAssets.indexOf(removedAsset)!
/// Minimize the number of cycles.
let indexPathsForSelectedItems = collectionView.indexPathsForSelectedItems() as [NSIndexPath]!
let indexPathsForVisibleItems = collectionView.indexPathsForVisibleItems()
let intersect = Set(indexPathsForVisibleItems).intersect(Set(indexPathsForSelectedItems))
for selectedIndexPath in intersect {
if let selectedCell = (collectionView.cellForItemAtIndexPath(selectedIndexPath) as? DKAssetCell) {
let selectedIndex = self.imagePickerController.selectedAssets.indexOf(selectedCell.asset)!
if selectedIndex > removedIndex {
selectedCell.checkView.checkLabel.text = "\(Int(selectedCell.checkView.checkLabel.text!)! - 1)"
}
}
}
self.imagePickerController.deselectImage(removedAsset)
}
}
// MARK: - DKGroupDataManagerObserver methods
func groupDidUpdate(groupId: String) {
if self.selectedGroupId == groupId {
self.updateTitleView()
}
}
func group(groupId: String, didRemoveAssets assets: [DKAsset]) {
for (_, selectedAsset) in self.imagePickerController.selectedAssets.enumerate() {
for removedAsset in assets {
if selectedAsset.isEqual(removedAsset) {
self.imagePickerController.deselectImage(selectedAsset)
}
}
}
if self.selectedGroupId == groupId {
self.invalidateCachedAssetsOfCurrentGroup()
self.collectionView?.reloadData()
}
}
func group(groupId: String, didInsertAssets assets: [DKAsset]) {
self.invalidateCachedAssetsOfCurrentGroup()
self.collectionView?.reloadData()
}
}
| mit | 857e1d544a265158ae4b3547d86fba28 | 40.050946 | 171 | 0.679314 | 5.607874 | false | false | false | false |
xiaoyouPrince/DYLive | DYLive/DYLive/Classes/Tools/NetworkTools/NetworkTools.swift | 1 | 1895 | //
// NetworkTools.swift
// DYLive
//
// Created by 渠晓友 on 2017/4/10.
// Copyright © 2017年 xiaoyouPrince. All rights reserved.
//
import UIKit
import Alamofire
enum RequestMethod {
case GET
case POST
}
// 封装一个网络请求工具,这里不继承NSObject了,更加简洁一些
class NetworkTools {
// 自定义一个类方法
class func requestData(type:RequestMethod , URLString : String , parameters : [String : Any]? = nil , finishCallBack:@escaping (_ response : AnyObject) -> ()){
// 获取类型
let method = type == .GET ? HTTPMethod.get : HTTPMethod.post
// AF.request(URLString, method: method, parameters: parameters).responseJSON { (response) in
//
// // 1.校验返回值
// guard let result = response.result.value else{
//
// print(response.error!)
// return
// }
//
// // 2.回调正确的返回
// finishCallBack(result as AnyObject)
//
// }
// AF.request(URLString, method: method, parameters: parameters).responseDecodable { <#DataResponse<Decodable, AFError>#> in
// <#code#>
// }
}
// get请求
class func getData(URLString : String , finishCallBack:@escaping (_ response : AnyObject) -> ()) {
// 调用类方法
requestData(type: .GET, URLString: URLString) { (response) in
finishCallBack(response)
}
}
/// post请求
// MARK: - post请求
class func postData(URLString : String , parameters : [String : NSString]? = nil, finishCallBack:@escaping (_ response : AnyObject) -> ()) {
requestData(type:.POST, URLString: URLString, parameters: parameters) { (response) in
finishCallBack(response)
}
}
}
| mit | bf4aac0b69696195917aed8eebb4d0f4 | 25 | 163 | 0.56052 | 4.291262 | false | false | false | false |
mgadda/zig | Sources/zig/CMPEncoder.swift | 1 | 9198 | //
// CMPEncoder.swift
// zig
//
// Created by Matt Gadda on 10/28/17.
//
import Foundation
import CMP
protocol Serializable {
func serialize(encoder: CMPEncoder)
// static func deserialize(with decoder: CMPDecoder) -> Self
init(with decoder: CMPDecoder) throws
}
func cmpWriter(ctx: UnsafeMutablePointer<cmp_ctx_s>!, data: UnsafeRawPointer!, count: Int) -> Int {
let cmpJump = ctx.pointee.buf.bindMemory(to: CMPJump.self, capacity: 1).pointee
if let encoder = cmpJump.encoder {
return encoder.write(data, count)
}
return 0
}
func cmpSkipper(ctx: UnsafeMutablePointer<cmp_ctx_s>!, count: Int) -> Bool {
let cmpJump = ctx.pointee.buf.bindMemory(to: CMPJump.self, capacity: 1).pointee
if let encoder = cmpJump.encoder {
return encoder.skip(count: count)
} else if let decoder = cmpJump.decoder {
return decoder.skip(count: count)
}
return false
}
func cmpReader(ctx: UnsafeMutablePointer<cmp_ctx_s>!, data: UnsafeMutableRawPointer!, limit: Int) -> Bool {
let cmpJump = ctx.pointee.buf.bindMemory(to: CMPJump.self, capacity: 1).pointee
if let decoder = cmpJump.decoder {
return decoder.read(data, count: limit)
}
return false
}
fileprivate struct CMPJump {
var encoder: CMPEncoder?
var decoder: CMPDecoder?
init() {}
}
// TODO: why is this necessary?
class CMPKeyedDecoderContainer {
fileprivate var container: [String : Serializable] = [:]
func write<T: Serializable>(key: String, value: T) {
container[key] = value
}
}
class CMPEncoder {
var context = cmp_ctx_t()
var buffer = Data()
let userContext: Any?
var bufferPosition = 0 // used for reading/skipping
fileprivate var jump: CMPJump
init(userContext: Any? = nil) {
self.userContext = userContext
jump = CMPJump()
jump.encoder = self
// `this` is guaranteed to be as valid as long as `self`
withUnsafeMutablePointer(to: &jump) { (ptr) -> Void in
cmp_init(&context, ptr, nil, cmpSkipper, cmpWriter)
}
}
func read(_ data: UnsafeMutableRawPointer, count: Int) -> Bool {
let range: Range<Int> = bufferPosition..<(bufferPosition + count)
buffer.copyBytes(to: data.bindMemory(to: UInt8.self, capacity: count), from: range)
bufferPosition += count
return true
}
/// Append data to CMPEncoder's internal buffer
func write(_ data: UnsafeRawPointer, _ count: Int) -> Int {
// if this is too slow, we need to blit memory with copyBytes and using bufferPosition
buffer.append(data.bindMemory(to: UInt8.self, capacity: count), count: count)
return count
}
func skip(count: Int) -> Bool {
bufferPosition += count
return true
}
func write(_ value: Int) {
cmp_write_s64(&context, Int64(value))
}
func write(_ value: Int64) {
cmp_write_s64(&context, value)
}
func write(_ value: Double) {
cmp_write_double(&context, value)
}
func write(_ value: Data) {
value.withUnsafeBytes { ptr -> Void in
cmp_write_bin(&context, ptr, UInt32(value.count))
}
}
func write<T: Serializable>(_ value: T) {
value.serialize(encoder: self)
}
func write<T: Serializable>(_ values: [T]) {
cmp_write_array(&context, UInt32(values.count))
values.forEach { value -> Void in
value.serialize(encoder: self)
}
}
func write<T: Serializable>(_ values: [String : T?]) {
cmp_write_map(&context, UInt32(values.count))
values.forEach { (key, value) in
guard value != nil else { return }
key.serialize(encoder: self)
value!.serialize(encoder: self)
}
}
func write(_ value: String) {
let data = value.data(using: .utf8)!
_ = data.withUnsafeBytes({ bytes in
cmp_write_str(&context, bytes, UInt32(data.count))
})
}
func keyedContainer() -> CMPKeyedDecoderContainer {
return CMPKeyedDecoderContainer()
}
func write(_ value: CMPKeyedDecoderContainer) {
cmp_write_map(&context, UInt32(value.container.count))
value.container.forEach { key, value in
write(key)
value.serialize(encoder: self)
}
}
}
class CMPDecoder {
var context = cmp_ctx_t()
var buffer: Data
let userContext: Any?
var bufferPosition = 0 // used for reading/skipping
fileprivate var jump: CMPJump
init(from buffer: Data, userContext: Any? = nil) {
self.buffer = buffer
self.userContext = userContext
jump = CMPJump()
jump.decoder = self
// `this` is guaranteed to be as valid as long as `self`
withUnsafeMutablePointer(to: &jump) { (ptr) -> Void in
cmp_init(&context, ptr, cmpReader, cmpSkipper, nil)
}
}
func read(_ data: UnsafeMutableRawPointer, count: Int) -> Bool {
let range: Range<Int> = bufferPosition..<(bufferPosition + count)
buffer.copyBytes(to: data.bindMemory(to: UInt8.self, capacity: count), from: range)
bufferPosition += count
return true
}
func skip(count: Int) -> Bool {
bufferPosition += count
return true
}
func read() -> Int {
var value: Int64 = 0
cmp_read_s64(&context, &value)
// TODO: correctly handle decoding 64-bit ints on 32-bit systems
return Int(value)
}
func read() -> Int64 {
var value: Int64 = 0
cmp_read_s64(&context, &value)
return value
}
func read() -> Double {
var value: Double = 0.0
cmp_read_double(&context, &value)
return value
}
func read() -> Data {
var size: UInt32 = 0
freezingPosition { cmp_read_bin_size(&context, &size) }
var value = Data(count: Int(size)) // TODO: potential data loss here for values > Int.max and < UInt32.max
let _ = value.withUnsafeMutableBytes { (ptr: UnsafeMutablePointer<UInt8>) -> Bool in
cmp_read_bin(&context, ptr, &size)
}
return value
}
func freezingPosition(fn: () -> Void) {
let oldBufferPosition = bufferPosition
fn()
bufferPosition = oldBufferPosition
}
func read() throws -> String {
var size: UInt32 = 0
freezingPosition { cmp_read_str_size(&context, &size) }
size += 1 // cmp_read_str apparently expects this
var value = Data(count: Int(size)) // TODO: potential data loss here for values > Int.max and < UInt32.max
let result = value.withUnsafeMutableBytes { ptr in
cmp_read_str(&context, ptr, &size)
}
if !result {
throw ZigError.decodingError("Error code \(context.error)")
}
return String(data: value.subdata(in: 0..<(value.count - 1)), encoding: .utf8)!
}
/// Read a homoegeneous array of values
func read<T : Serializable>() throws -> [T] {
var size: UInt32 = 0
cmp_read_array(&context, &size)
return try Array((0..<size)).map { (_) -> T in
try T(with: self)
}
}
/// Read heterogeneous dictionary of Serializable values
func read(_ fields: [String : Serializable.Type]) throws -> [String : Any] {
var size: UInt32 = 0
cmp_read_map(&context, &size)
let keysAndValues = try Array((0..<size)).flatMap { (_) -> (String, Serializable) in
let key = try String(with: self)
let value = (try fields[key]?.init(with: self))!
return (key, value)
}
return Dictionary<String, Serializable>(uniqueKeysWithValues: keysAndValues)
}
/// Deserialize a homogeneous map of String -> T (probably of limited utility)
/// This method should not be confused with a type-less keyed decoding container
func read<T : Serializable>() throws -> [String : T] {
var size: UInt32 = 0
cmp_read_map(&context, &size)
let keysAndValues = try Array((0..<size)).flatMap { (_) -> (String, T) in
(try String(with: self), try T(with: self))
}
return Dictionary<String, T>(uniqueKeysWithValues: keysAndValues)
}
}
extension Data : Serializable {
func serialize(encoder: CMPEncoder) {
encoder.write(self)
}
init(with decoder: CMPDecoder) throws {
self = decoder.read()
}
}
extension String : Serializable {
func serialize(encoder: CMPEncoder) {
encoder.write(self)
}
init(with decoder: CMPDecoder) throws {
self = try decoder.read()
}
}
extension Double : Serializable {
func serialize(encoder: CMPEncoder) {
encoder.write(self)
}
init(with decoder: CMPDecoder) throws {
self = decoder.read()
}
}
extension Int : Serializable {
func serialize(encoder: CMPEncoder) {
encoder.write(self)
}
init(with decoder: CMPDecoder) throws {
self = decoder.read()
}
}
func cmpFileWriter(ctx: UnsafeMutablePointer<cmp_ctx_s>!, data: UnsafeRawPointer!, count: Int) -> Int {
let fileHandlePtr = ctx.pointee.buf.bindMemory(to: FileHandle.self, capacity: 1)
fileHandlePtr.pointee.write(Data(bytes: data, count: count))
return count
}
func cmpFileSkipper(ctx: UnsafeMutablePointer<cmp_ctx_s>!, count: Int) -> Bool {
let fileHandlePtr = ctx.pointee.buf.bindMemory(to: FileHandle.self, capacity: 1)
fileHandlePtr.pointee.seek(toFileOffset: UInt64(count))
return true
}
func cmpFileReader(ctx: UnsafeMutablePointer<cmp_ctx_s>!, data: UnsafeMutableRawPointer!, limit: Int) -> Bool {
let fileHandlePtr = ctx.pointee.buf.bindMemory(to: FileHandle.self, capacity: 1)
fileHandlePtr.pointee
.readData(ofLength: limit)
.copyBytes(to: data.bindMemory(to: UInt8.self, capacity: limit), count: limit)
return true
}
| mit | 8425153a90648d474e1c43e160bb15de | 27.042683 | 111 | 0.664927 | 3.758888 | false | false | false | false |
QuarkX/Quark | Sources/Quark/Core/Reflection/PointerType.swift | 5 | 472 | protocol PointerType : Equatable {
associatedtype Pointee
var pointer: UnsafePointer<Pointee> { get set }
}
extension PointerType {
init<T>(pointer: UnsafePointer<T>) {
func cast<T, U>(_ value: T) -> U {
return unsafeBitCast(value, to: U.self)
}
self = cast(UnsafeRawPointer(pointer).assumingMemoryBound(to: Pointee.self))
}
}
func ==<T : PointerType>(lhs: T, rhs: T) -> Bool {
return lhs.pointer == rhs.pointer
}
| mit | 25be3daedc3d85f013dac0f5c51181ae | 26.764706 | 84 | 0.627119 | 3.933333 | false | false | false | false |
HeartRateLearning/HRLEngine | HRLEngine/Classes/Record.swift | 1 | 2093 | //
// Record.swift
// Pods
//
// Created by Enrique de la Torre (dev) on 22/12/2016.
//
//
import Foundation
import HRLAlgorithms
/// A heart rate record as expected by an `Engine` or a `DataFrame`.
public class Record: NSObject {
fileprivate let values: [HRLValue]
fileprivate static let calendar = defaultCalendar()
/**
Initializes a new heart rate record.
- Parameters:
- date: Date when the heart rate was recorded
- bpm: Beats Per Minute when the heart rate was recorded
- Returns: A new heart rate record.
*/
public init(date: Date, bpm: Float) {
values = [
HRLValue(Record.weekday(from: date)),
HRLValue(Record.timeIntervalFromMidnight(to: date)),
HRLValue(bpm)
]
}
}
extension Record: HRLVector {
public func count() -> HRLSize {
return HRLSize(values.count)
}
public func value(at index: HRLSize) -> HRLValue {
return values[Int(index)]
}
}
private extension Record {
enum Constants {
static let TimeZoneGMT = "GMT"
static let LocalePOSIX = "en_US_POSIX"
}
static func defaultCalendar() -> Calendar {
var calendar = Calendar(identifier: .gregorian)
calendar.timeZone = TimeZone(abbreviation: Constants.TimeZoneGMT)!
calendar.locale = Locale(identifier: Constants.LocalePOSIX)
return calendar
}
static func weekday(from date: Date) -> Int {
return calendar.component(.weekday, from: date)
}
static func timeIntervalFromMidnight(to date: Date) -> TimeInterval {
let midnight = startOfDay(for: date)
return date.timeIntervalSince(midnight)
}
static func startOfDay(for date: Date) -> Date {
var components = calendar.dateComponents([.year, .month, .day, .hour, .minute, .second],
from: date)
components.hour = 0
components.minute = 0
components.second = 0
return calendar.date(from: components)!
}
}
| mit | 3291572b54a2c769302a6e46001ff62b | 25.493671 | 96 | 0.608696 | 4.424947 | false | false | false | false |
Shvier/Dota2Helper | Dota2Helper/Dota2Helper/Base/Controller/DHBaseDetailViewController.swift | 1 | 952 | //
// DHBaseDetailViewController.swift
// Dota2Helper
//
// Created by Shvier on 10/14/16.
// Copyright © 2016 Shvier. All rights reserved.
//
import UIKit
import WebKit
@objc class DHBaseDetailViewController: UIViewController {
func handleNavigationBack() {
let _ = navigationController?.popViewController(animated: true)
}
func initLifeCycle() {
view.backgroundColor = UIColor.white
navigationController?.navigationBar.tintColor = kTabBarItemColor
navigationController?.navigationBar.barTintColor = UIColor.black
navigationItem.title = "详情"
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
handleNavigationBack()
}
override func viewDidLoad() {
super.viewDidLoad()
initLifeCycle()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
| apache-2.0 | cb7e0aea8761c01e6c7f9cfb9bb94507 | 22.675 | 72 | 0.676874 | 5.174863 | false | false | false | false |
swiftix/swift | test/SILGen/unmanaged.swift | 1 | 2583 | // RUN: %target-swift-frontend -emit-sil %s | %FileCheck %s
class C {}
struct Holder {
unowned(unsafe) var value: C
}
_ = Holder(value: C())
// CHECK-LABEL:sil hidden @_T09unmanaged6HolderV{{[_0-9a-zA-Z]*}}fC : $@convention(method) (@owned C, @thin Holder.Type) -> Holder
// CHECK: bb0([[T0:%.*]] : $C,
// CHECK-NEXT: [[T1:%.*]] = ref_to_unmanaged [[T0]] : $C to $@sil_unmanaged C
// CHECK-NEXT: strong_release [[T0]] : $C
// CHECK-NEXT: [[T2:%.*]] = struct $Holder ([[T1]] : $@sil_unmanaged C)
// CHECK-NEXT: return [[T2]] : $Holder
func set(holder holder: inout Holder) {
holder.value = C()
}
// CHECK-LABEL:sil hidden @_T09unmanaged3setyAA6HolderVz6holder_tF : $@convention(thin) (@inout Holder) -> ()
// CHECK: bb0([[ADDR:%.*]] : $*Holder):
// CHECK: [[T0:%.*]] = function_ref @_T09unmanaged1CC{{[_0-9a-zA-Z]*}}fC
// CHECK: [[C:%.*]] = apply [[T0]](
// CHECK-NEXT: [[WRITE:%.*]] = begin_access [modify] [static] [[ADDR]] : $*Holder
// CHECK-NEXT: [[T0:%.*]] = struct_element_addr [[WRITE]] : $*Holder, #Holder.value
// CHECK-NEXT: [[T1:%.*]] = ref_to_unmanaged [[C]]
// CHECK-NEXT: store [[T1]] to [[T0]]
// CHECK-NEXT: strong_release [[C]]
// CHECK-NEXT: end_access [[WRITE]] : $*Holder
// CHECK-NEXT: tuple ()
// CHECK-NEXT: return
func get(holder holder: inout Holder) -> C {
return holder.value
}
// CHECK-LABEL:sil hidden @_T09unmanaged3getAA1CCAA6HolderVz6holder_tF : $@convention(thin) (@inout Holder) -> @owned C
// CHECK: bb0([[ADDR:%.*]] : $*Holder):
// CHECK-NEXT: debug_value_addr %0 : $*Holder, var, name "holder", argno 1
// CHECK-NEXT: [[READ:%.*]] = begin_access [read] [static] [[ADDR]] : $*Holder
// CHECK-NEXT: [[T0:%.*]] = struct_element_addr [[READ]] : $*Holder, #Holder.value
// CHECK-NEXT: [[T1:%.*]] = load [[T0]] : $*@sil_unmanaged C
// CHECK-NEXT: [[T2:%.*]] = unmanaged_to_ref [[T1]]
// CHECK-NEXT: strong_retain [[T2]]
// CHECK-NEXT: end_access [[READ]] : $*Holder
// CHECK-NEXT: return [[T2]]
func project(fn fn: () -> Holder) -> C {
return fn().value
}
// CHECK-LABEL:sil hidden @_T09unmanaged7projectAA1CCAA6HolderVyc2fn_tF : $@convention(thin) (@owned @noescape @callee_owned () -> Holder) -> @owned C
// CHECK: bb0([[FN:%.*]] : $@noescape @callee_owned () -> Holder):
// CHECK: strong_retain [[FN]]
// CHECK-NEXT: [[T0:%.*]] = apply [[FN]]()
// CHECK-NEXT: [[T1:%.*]] = struct_extract [[T0]] : $Holder, #Holder.value
// CHECK-NEXT: [[T2:%.*]] = unmanaged_to_ref [[T1]]
// CHECK-NEXT: strong_retain [[T2]]
// CHECK-NEXT: strong_release [[FN]]
// CHECK-NEXT: return [[T2]]
| apache-2.0 | e77eaf10b4fa666c067061529e3b838e | 44.315789 | 150 | 0.586914 | 2.921946 | false | false | false | false |
davidstump/SwiftPhoenixClient | Sources/SwiftPhoenixClient/TimeoutTimer.swift | 1 | 4080 | // Copyright (c) 2021 David Stump <[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.
/// Creates a timer that can perform calculated reties by setting
/// `timerCalculation` , such as exponential backoff.
///
/// ### Example
///
/// let reconnectTimer = TimeoutTimer()
///
/// // Receive a callbcak when the timer is fired
/// reconnectTimer.callback.delegate(to: self) { (_) in
/// print("timer was fired")
/// }
///
/// // Provide timer interval calculation
/// reconnectTimer.timerCalculation.delegate(to: self) { (_, tries) -> TimeInterval in
/// return tries > 2 ? 1000 : [1000, 5000, 10000][tries - 1]
/// }
///
/// reconnectTimer.scheduleTimeout() // fires after 1000ms
/// reconnectTimer.scheduleTimeout() // fires after 5000ms
/// reconnectTimer.reset()
/// reconnectTimer.scheduleTimeout() // fires after 1000ms
import Foundation
// sourcery: AutoMockable
class TimeoutTimer {
/// Callback to be informed when the underlying Timer fires
var callback = Delegated<(), Void>()
/// Provides TimeInterval to use when scheduling the timer
var timerCalculation = Delegated<Int, TimeInterval>()
/// The work to be done when the queue fires
var workItem: DispatchWorkItem? = nil
/// The number of times the underlyingTimer hass been set off.
var tries: Int = 0
/// The Queue to execute on. In testing, this is overridden
var queue: TimerQueue = TimerQueue.main
/// Resets the Timer, clearing the number of tries and stops
/// any scheduled timeout.
func reset() {
self.tries = 0
self.clearTimer()
}
/// Schedules a timeout callback to fire after a calculated timeout duration.
func scheduleTimeout() {
// Clear any ongoing timer, not resetting the number of tries
self.clearTimer()
// Get the next calculated interval, in milliseconds. Do not
// start the timer if the interval is returned as nil.
guard let timeInterval
= self.timerCalculation.call(self.tries + 1) else { return }
let workItem = DispatchWorkItem {
self.tries += 1
self.callback.call()
}
self.workItem = workItem
self.queue.queue(timeInterval: timeInterval, execute: workItem)
}
/// Invalidates any ongoing Timer. Will not clear how many tries have been made
private func clearTimer() {
self.workItem?.cancel()
self.workItem = nil
}
}
/// Wrapper class around a DispatchQueue. Allows for providing a fake clock
/// during tests.
class TimerQueue {
// Can be overriden in tests
static var main = TimerQueue()
func queue(timeInterval: TimeInterval, execute: DispatchWorkItem) {
// TimeInterval is always in seconds. Multiply it by 1000 to convert
// to milliseconds and round to the nearest millisecond.
let dispatchInterval = Int(round(timeInterval * 1000))
let dispatchTime = DispatchTime.now() + .milliseconds(dispatchInterval)
DispatchQueue.main.asyncAfter(deadline: dispatchTime, execute: execute)
}
}
| mit | bbddd8a9c29486fb7157252a49f8aeec | 34.478261 | 90 | 0.701961 | 4.563758 | false | false | false | false |
jedlewison/AsyncOpKit | AsyncOp.swift | 1 | 11777 | //
// AsyncOp.swift
//
// Created by Jed Lewison
// Copyright (c) 2015 Magic App Factory. MIT License.
import Foundation
/// AsyncOp is an NSOperation subclass that supports a generic output type and takes care of the boiler plate necessary for asynchronous execution of NSOperations.
/// You can subclass AsyncOp, but because it's a generic subclass and provides convenient closures for performing work as well has handling cancellation, results, and errors, in many cases you may not need to.
public class AsyncOp<InputType, OutputType>: NSOperation {
@nonobjc public required override init() {
super.init()
}
public var input: AsyncOpValue<InputType> {
get {
return _input
}
set {
guard state == .Initial else { debugPrint(WarnSetInput); return }
_input = newValue
}
}
public private(set) final var output: AsyncOpValue<OutputType> = .None(.NoValue)
// Closures
public typealias AsyncOpClosure = (asyncOp: AsyncOp<InputType, OutputType>) -> Void
public typealias AsyncOpThrowingClosure = (asyncOp: AsyncOp<InputType, OutputType>) throws -> Void
public typealias AsyncOpPreconditionEvaluator = () throws -> AsyncOpPreconditionInstruction
// MARK: Implementation details
override public final func start() {
state = .Executing
if !cancelled {
main()
} else {
preconditionEvaluators.removeAll()
implementationHandler = nil
finish(with: .None(.Cancelled))
}
}
override public final func main() {
// Helper functions to decompose the work
func main_prepareInput() {
if let handlerForAsyncOpInputRequest = handlerForAsyncOpInputRequest {
_input = handlerForAsyncOpInputRequest()
self.handlerForAsyncOpInputRequest = nil
}
}
func main_evaluatePreconditions() -> AsyncOpPreconditionInstruction {
var errors = [ErrorType]()
var preconditionInstruction = AsyncOpPreconditionInstruction.Continue
for evaluator in preconditionEvaluators {
do {
let evaluatorInstruction = try evaluator()
switch evaluatorInstruction {
case .Cancel where errors.count == 0:
preconditionInstruction = .Cancel
case .Fail(let error):
errors.append(error)
preconditionInstruction = AsyncOpPreconditionInstruction(errors: errors)
case .Continue, .Cancel:
break
}
} catch {
errors.append(error)
preconditionInstruction = AsyncOpPreconditionInstruction(errors: errors)
}
}
preconditionEvaluators.removeAll()
return preconditionInstruction
}
func main_performImplementation() {
if let implementationHandler = self.implementationHandler {
self.implementationHandler = nil
do {
try implementationHandler(asyncOp: self)
} catch {
finish(with: error)
}
} else {
finish(with: AsyncOpError.UnimplementedOperation)
}
}
// The actual implementation
autoreleasepool {
main_prepareInput()
switch main_evaluatePreconditions() {
case .Continue:
main_performImplementation() // happy path
case .Cancel:
implementationHandler = nil
cancel()
finish(with: .Cancelled)
case .Fail(let error):
cancel()
implementationHandler = nil
finish(with: error)
}
}
}
override public final func cancel() {
performOnce(onceAction: .cancel) {
super.cancel()
self.cancellationHandler?(asyncOp: self)
self.cancellationHandler = nil
}
}
public private(set) final var paused: Bool = false {
willSet {
guard state == .Initial else { return }
if paused != newValue {
willChangeValueForKey("isReady")
}
}
didSet {
guard state == .Initial else { return }
if paused != oldValue {
didChangeValueForKey("isReady")
}
}
}
private var state = AsyncOpState.Initial {
willSet {
if newValue != state {
willChangeValueForState(newValue)
willChangeValueForState(state)
}
}
didSet {
if oldValue != state {
didChangeValueForState(oldValue)
didChangeValueForState(state)
}
}
}
/// Overrides for required NSOperation properties
override public final var asynchronous: Bool { return true }
override public final var executing: Bool { return state == .Executing }
override public final var finished: Bool { return state == .Finished }
override public var ready: Bool {
guard state == .Initial else { return true }
guard super.ready else { return false }
return !paused
}
// MARK: Private storage
private typealias AsyncInputRequest = () -> AsyncOpValue<InputType>
private var handlerForAsyncOpInputRequest: AsyncInputRequest?
private var preconditionEvaluators = [AsyncOpPreconditionEvaluator]()
private var implementationHandler: AsyncOpThrowingClosure?
private var completionHandler: AsyncOpClosure?
private var completionHandlerQueue: NSOperationQueue?
private var cancellationHandler: AsyncOpClosure?
// Convenience for performing cancel and finish actions once
private var onceGuards: [OnceAction : Bool] = Dictionary(minimumCapacity: OnceAction.count)
private let performOnceGuardQ = NSQualityOfService.UserInitiated.createSerialDispatchQueue("asyncOpKit.performOnceGuardQ")
private func performOnce(onceAction onceAction: OnceAction, @noescape action: () -> ()) {
var canPerformAction: Bool?
dispatch_sync(performOnceGuardQ) {
canPerformAction = self.onceGuards[onceAction] ?? true
self.onceGuards[onceAction] = false
}
if canPerformAction == true {
action()
}
}
private var _input: AsyncOpValue<InputType> = AsyncOpValue.None(.NoValue)
}
extension AsyncOp {
public func onStart(implementationHandler: AsyncOpThrowingClosure) {
guard state == .Initial else { return }
self.implementationHandler = implementationHandler
}
public func whenFinished(whenFinishedQueue completionHandlerQueue: NSOperationQueue = NSOperationQueue.mainQueue(), completionHandler: AsyncOpClosure) {
performOnce(onceAction: .whenFinished) {
guard self.completionHandler == nil else { return }
if self.finished {
completionHandlerQueue.addOperationWithBlock {
completionHandler(asyncOp: self)
}
} else {
self.completionHandlerQueue = completionHandlerQueue
self.completionHandler = completionHandler
}
}
}
public func onCancel(cancellationHandler: AsyncOpClosure) {
guard state == .Initial else { return }
self.cancellationHandler = cancellationHandler
}
}
extension AsyncOp where OutputType: AsyncVoidConvertible {
public final func finishWithSuccess() {
finish(with: .Some(OutputType(asyncVoid: .Void)))
}
}
// MARK: Functions for finishing operation
extension AsyncOp {
public final func finish(with value: OutputType) {
finish(with: .Some(value))
}
public final func finish(with asyncOpValueError: AsyncOpValueErrorType) {
finish(with: .None(asyncOpValueError))
}
public final func finish(with failureError: ErrorType) {
finish(with: .None(.Failed(failureError)))
}
public final func finish(with asyncOpValue: AsyncOpValue<OutputType>) {
guard executing else { return }
performOnce(onceAction: .finish) {
self.output = asyncOpValue
self.state = .Finished
guard let completionHandler = self.completionHandler else { return }
self.completionHandler = nil
self.implementationHandler = nil
self.cancellationHandler = nil
self.handlerForAsyncOpInputRequest = nil
self.preconditionEvaluators.removeAll()
guard let completionHandlerQueue = self.completionHandlerQueue else { return }
self.completionHandlerQueue = nil
completionHandlerQueue.addOperationWithBlock {
completionHandler(asyncOp: self)
}
}
}
}
extension AsyncOp {
/// Has no effect on operation readiness once it begins executing
public final func pause() {
paused = true
}
/// Has no effect on operation readiness once it begins executing
public final func resume() {
paused = false
}
}
extension AsyncOp: AsyncOpInputProvider {
public func addPreconditionEvaluator(evaluator: AsyncOpPreconditionEvaluator) {
guard state == .Initial else { debugPrint(WarnSetInput); return }
preconditionEvaluators.append(evaluator)
}
public func setInputProvider<T where T: AsyncOpInputProvider, T.ProvidedInputValueType == InputType>(inputProvider: T) {
guard state == .Initial else { debugPrint(WarnSetInput); return }
if let inputProvider = inputProvider as? NSOperation {
addDependency(inputProvider)
}
handlerForAsyncOpInputRequest = inputProvider.provideAsyncOpInput
}
public typealias ProvidedInputValueType = OutputType
public func provideAsyncOpInput() -> AsyncOpValue<OutputType> {
return output
}
public func setInput(value: InputType, andResume resume: Bool = false) {
setInput(AsyncOpValue.Some(value), andResume: resume)
}
public func setInput(input: AsyncOpValue<InputType>, andResume resume: Bool = false) {
guard state == .Initial else { debugPrint(WarnSetInput); return }
self.input = input
if resume {
self.resume()
}
}
}
extension AsyncOp {
public var resultStatus: AsyncOpResultStatus {
guard state == .Finished else { return .Pending }
guard !cancelled else { return .Cancelled }
switch output {
case .None:
return .Failed
case .Some:
return .Succeeded
}
}
}
private extension AsyncOp {
func willChangeValueForState(state: AsyncOpState) {
guard let key = state.key else { return }
willChangeValueForKey(key)
}
func didChangeValueForState(state: AsyncOpState) {
guard let key = state.key else { return }
didChangeValueForKey(key)
}
}
private let WarnSetInput = "Setting input without manual mode automatic or when operation has started has no effect"
private enum AsyncOpState {
case Initial
case Executing
case Finished
var key: String? {
switch self {
case .Executing:
return "isExecuting"
case .Finished:
return "isFinished"
case .Initial:
return nil
}
}
}
private enum OnceAction: Int {
case whenFinished
case finish
case cancel
static let count = 3
} | mit | 3175da914df66128afd8b0264c7009db | 31.180328 | 209 | 0.619343 | 5.659298 | false | false | false | false |
Gathros/algorithm-archive | contents/verlet_integration/code/swift/verlet.swift | 1 | 1624 | func verlet(pos: Double, acc: Double, dt: Double) -> Double {
var pos = pos
var temp_pos, time: Double
var prev_pos = pos
time = 0.0
while (pos > 0) {
time += dt
temp_pos = pos
pos = pos*2 - prev_pos + acc * dt * dt
prev_pos = temp_pos
}
return time
}
func stormerVerlet(pos: Double, acc: Double, dt: Double) -> (time: Double, vel: Double) {
var pos = pos
var temp_pos, time, vel: Double
var prev_pos = pos
vel = 0
time = 0
while (pos > 0) {
time += dt
temp_pos = pos
pos = pos*2 - prev_pos + acc * dt * dt
prev_pos = temp_pos
vel += acc*dt
}
return (time:time, vel:vel)
}
func velocityVerlet(pos: Double, acc: Double, dt: Double) -> (time: Double, vel: Double) {
var pos = pos
var time, vel : Double
vel = 0
time = 0
while (pos > 0) {
time += dt
pos += vel*dt + 0.5*acc * dt * dt
vel += acc*dt
}
return (time:time, vel:vel)
}
func main() {
let verletTime = verlet(pos: 5.0, acc: -10.0, dt: 0.01)
print("Time for Verlet integration is: \(verletTime)")
let stormer = stormerVerlet(pos: 5.0, acc: -10.0, dt: 0.01);
print("Time for Stormer Verlet integration is: \(stormer.time)")
print("Velocity for Stormer Verlet integration is: \(stormer.vel)")
let velVerlet = velocityVerlet(pos: 5.0, acc: -10, dt: 0.01)
print("Time for velocity Verlet integration is: \(velVerlet.time)")
print("Velocity for velocity Verlet integration is: \(velVerlet.vel)")
}
main()
| mit | 76e1ef5597c873c74efcacbe362aca35 | 24.375 | 90 | 0.55234 | 3.307536 | false | false | false | false |
huonw/swift | stdlib/public/core/AnyHashable.swift | 1 | 12690 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
/// A value that has a custom representation in `AnyHashable`.
///
/// `Self` should also conform to `Hashable`.
public protocol _HasCustomAnyHashableRepresentation {
/// Returns a custom representation of `self` as `AnyHashable`.
/// If returns nil, the default representation is used.
///
/// If your custom representation is a class instance, it
/// needs to be boxed into `AnyHashable` using the static
/// type that introduces the `Hashable` conformance.
///
/// class Base : Hashable {}
/// class Derived1 : Base {}
/// class Derived2 : Base, _HasCustomAnyHashableRepresentation {
/// func _toCustomAnyHashable() -> AnyHashable? {
/// // `Derived2` is canonicalized to `Derived1`.
/// let customRepresentation = Derived1()
///
/// // Wrong:
/// // return AnyHashable(customRepresentation)
///
/// // Correct:
/// return AnyHashable(customRepresentation as Base)
/// }
func _toCustomAnyHashable() -> AnyHashable?
}
@usableFromInline // FIXME(sil-serialize-all)
internal protocol _AnyHashableBox {
func _unbox<T : Hashable>() -> T?
/// Determine whether values in the boxes are equivalent.
///
/// - Returns: `nil` to indicate that the boxes store different types, so
/// no comparison is possible. Otherwise, contains the result of `==`.
func _isEqual(to: _AnyHashableBox) -> Bool?
var _hashValue: Int { get }
func _hash(into hasher: inout Hasher)
var _base: Any { get }
func _downCastConditional<T>(into result: UnsafeMutablePointer<T>) -> Bool
}
@_fixed_layout // FIXME(sil-serialize-all)
@usableFromInline // FIXME(sil-serialize-all)
internal struct _ConcreteHashableBox<Base : Hashable> : _AnyHashableBox {
@usableFromInline // FIXME(sil-serialize-all)
internal var _baseHashable: Base
@inlinable // FIXME(sil-serialize-all)
internal init(_ base: Base) {
self._baseHashable = base
}
@inlinable // FIXME(sil-serialize-all)
internal func _unbox<T : Hashable>() -> T? {
return (self as _AnyHashableBox as? _ConcreteHashableBox<T>)?._baseHashable
}
@inlinable // FIXME(sil-serialize-all)
internal func _isEqual(to rhs: _AnyHashableBox) -> Bool? {
if let rhs: Base = rhs._unbox() {
return _baseHashable == rhs
}
return nil
}
@inlinable // FIXME(sil-serialize-all)
internal var _hashValue: Int {
return _baseHashable.hashValue
}
@inlinable // FIXME(sil-serialize-all)
func _hash(into hasher: inout Hasher) {
_baseHashable.hash(into: &hasher)
}
@inlinable // FIXME(sil-serialize-all)
internal var _base: Any {
return _baseHashable
}
@inlinable // FIXME(sil-serialize-all)
internal
func _downCastConditional<T>(into result: UnsafeMutablePointer<T>) -> Bool {
guard let value = _baseHashable as? T else { return false }
result.initialize(to: value)
return true
}
}
#if _runtime(_ObjC)
// Retrieve the custom AnyHashable representation of the value after it
// has been bridged to Objective-C. This mapping to Objective-C and back
// turns a non-custom representation into a custom one, which is used as
// the lowest-common-denominator for comparisons.
@inlinable // FIXME(sil-serialize-all)
internal func _getBridgedCustomAnyHashable<T>(_ value: T) -> AnyHashable? {
let bridgedValue = _bridgeAnythingToObjectiveC(value)
return (bridgedValue as?
_HasCustomAnyHashableRepresentation)?._toCustomAnyHashable()
}
#endif
/// A type-erased hashable value.
///
/// The `AnyHashable` type forwards equality comparisons and hashing operations
/// to an underlying hashable value, hiding its specific underlying type.
///
/// You can store mixed-type keys in dictionaries and other collections that
/// require `Hashable` conformance by wrapping mixed-type keys in
/// `AnyHashable` instances:
///
/// let descriptions: [AnyHashable: Any] = [
/// AnyHashable("😄"): "emoji",
/// AnyHashable(42): "an Int",
/// AnyHashable(Int8(43)): "an Int8",
/// AnyHashable(Set(["a", "b"])): "a set of strings"
/// ]
/// print(descriptions[AnyHashable(42)]!) // prints "an Int"
/// print(descriptions[AnyHashable(43)]) // prints "nil"
/// print(descriptions[AnyHashable(Int8(43))]!) // prints "an Int8"
/// print(descriptions[AnyHashable(Set(["a", "b"]))]!) // prints "a set of strings"
@_fixed_layout // FIXME(sil-serialize-all)
public struct AnyHashable {
@usableFromInline // FIXME(sil-serialize-all)
internal var _box: _AnyHashableBox
@usableFromInline // FIXME(sil-serialize-all)
internal var _usedCustomRepresentation: Bool
/// Creates a type-erased hashable value that wraps the given instance.
///
/// The following example creates two type-erased hashable values: `x` wraps
/// an `Int` with the value 42, while `y` wraps a `UInt8` with the same
/// numeric value. Because the underlying types of `x` and `y` are
/// different, the two variables do not compare as equal despite having
/// equal underlying values.
///
/// let x = AnyHashable(Int(42))
/// let y = AnyHashable(UInt8(42))
///
/// print(x == y)
/// // Prints "false" because `Int` and `UInt8` are different types
///
/// print(x == AnyHashable(Int(42)))
/// // Prints "true"
///
/// - Parameter base: A hashable value to wrap.
@inlinable // FIXME(sil-serialize-all)
public init<H : Hashable>(_ base: H) {
if let customRepresentation =
(base as? _HasCustomAnyHashableRepresentation)?._toCustomAnyHashable() {
self = customRepresentation
self._usedCustomRepresentation = true
return
}
self._box = _ConcreteHashableBox(0 as Int)
self._usedCustomRepresentation = false
_makeAnyHashableUpcastingToHashableBaseType(
base,
storingResultInto: &self)
}
@inlinable // FIXME(sil-serialize-all)
internal init<H : Hashable>(_usingDefaultRepresentationOf base: H) {
self._box = _ConcreteHashableBox(base)
self._usedCustomRepresentation = false
}
/// The value wrapped by this instance.
///
/// The `base` property can be cast back to its original type using one of
/// the casting operators (`as?`, `as!`, or `as`).
///
/// let anyMessage = AnyHashable("Hello world!")
/// if let unwrappedMessage = anyMessage.base as? String {
/// print(unwrappedMessage)
/// }
/// // Prints "Hello world!"
@inlinable // FIXME(sil-serialize-all)
public var base: Any {
return _box._base
}
/// Perform a downcast directly on the internal boxed representation.
///
/// This avoids the intermediate re-boxing we would get if we just did
/// a downcast on `base`.
@inlinable // FIXME(sil-serialize-all)
internal
func _downCastConditional<T>(into result: UnsafeMutablePointer<T>) -> Bool {
// Attempt the downcast.
if _box._downCastConditional(into: result) { return true }
#if _runtime(_ObjC)
// If we used a custom representation, bridge to Objective-C and then
// attempt the cast from there.
if _usedCustomRepresentation {
if let value = _bridgeAnythingToObjectiveC(_box._base) as? T {
result.initialize(to: value)
return true
}
}
#endif
return false
}
}
extension AnyHashable : Equatable {
/// Returns a Boolean value indicating whether two type-erased hashable
/// instances wrap the same type and value.
///
/// Two instances of `AnyHashable` compare as equal if and only if the
/// underlying types have the same conformance to the `Equatable` protocol
/// and the underlying values compare as equal.
///
/// The following example creates two type-erased hashable values: `x` wraps
/// an `Int` with the value 42, while `y` wraps a `UInt8` with the same
/// numeric value. Because the underlying types of `x` and `y` are
/// different, the two variables do not compare as equal despite having
/// equal underlying values.
///
/// let x = AnyHashable(Int(42))
/// let y = AnyHashable(UInt8(42))
///
/// print(x == y)
/// // Prints "false" because `Int` and `UInt8` are different types
///
/// print(x == AnyHashable(Int(42)))
/// // Prints "true"
///
/// - Parameters:
/// - lhs: A type-erased hashable value.
/// - rhs: Another type-erased hashable value.
@inlinable // FIXME(sil-serialize-all)
public static func == (lhs: AnyHashable, rhs: AnyHashable) -> Bool {
// If they're equal, we're done.
if let result = lhs._box._isEqual(to: rhs._box) { return result }
#if _runtime(_ObjC)
// If one used a custom representation but the other did not, bridge
// the one that did *not* use the custom representation to Objective-C:
// if the bridged result has a custom representation, compare those custom
// custom representations.
if lhs._usedCustomRepresentation != rhs._usedCustomRepresentation {
// If the lhs used a custom representation, try comparing against the
// custom representation of the bridged rhs (if there is one).
if lhs._usedCustomRepresentation {
if let customRHS = _getBridgedCustomAnyHashable(rhs._box._base) {
return lhs._box._isEqual(to: customRHS._box) ?? false
}
return false
}
// Otherwise, try comparing the rhs against the custom representation of
// the bridged lhs (if there is one).
if let customLHS = _getBridgedCustomAnyHashable(lhs._box._base) {
return customLHS._box._isEqual(to: rhs._box) ?? false
}
return false
}
#endif
return false
}
}
extension AnyHashable : Hashable {
/// The hash value.
@inlinable
public var hashValue: Int {
return _box._hashValue
}
/// 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) {
_box._hash(into: &hasher)
}
}
extension AnyHashable : CustomStringConvertible {
@inlinable // FIXME(sil-serialize-all)
public var description: String {
return String(describing: base)
}
}
extension AnyHashable : CustomDebugStringConvertible {
@inlinable // FIXME(sil-serialize-all)
public var debugDescription: String {
return "AnyHashable(" + String(reflecting: base) + ")"
}
}
extension AnyHashable : CustomReflectable {
@inlinable // FIXME(sil-serialize-all)
public var customMirror: Mirror {
return Mirror(
self,
children: ["value": base])
}
}
/// Returns a default (non-custom) representation of `self`
/// as `AnyHashable`.
///
/// Completely ignores the `_HasCustomAnyHashableRepresentation`
/// conformance, if it exists.
/// Called by AnyHashableSupport.cpp.
@_silgen_name("_swift_makeAnyHashableUsingDefaultRepresentation")
internal func _makeAnyHashableUsingDefaultRepresentation<H : Hashable>(
of value: H,
storingResultInto result: UnsafeMutablePointer<AnyHashable>
) {
result.pointee = AnyHashable(_usingDefaultRepresentationOf: value)
}
/// Provided by AnyHashable.cpp.
@usableFromInline // FIXME(sil-serialize-all)
@_silgen_name("_swift_makeAnyHashableUpcastingToHashableBaseType")
internal func _makeAnyHashableUpcastingToHashableBaseType<H : Hashable>(
_ value: H,
storingResultInto result: UnsafeMutablePointer<AnyHashable>
)
@inlinable // FIXME(sil-serialize-all)
public // COMPILER_INTRINSIC
func _convertToAnyHashable<H : Hashable>(_ value: H) -> AnyHashable {
return AnyHashable(value)
}
/// Called by the casting machinery.
@_silgen_name("_swift_convertToAnyHashableIndirect")
internal func _convertToAnyHashableIndirect<H : Hashable>(
_ value: H,
_ target: UnsafeMutablePointer<AnyHashable>
) {
target.initialize(to: AnyHashable(value))
}
/// Called by the casting machinery.
@_silgen_name("_swift_anyHashableDownCastConditionalIndirect")
internal func _anyHashableDownCastConditionalIndirect<T>(
_ value: UnsafePointer<AnyHashable>,
_ target: UnsafeMutablePointer<T>
) -> Bool {
return value.pointee._downCastConditional(into: target)
}
| apache-2.0 | b64bb8815ae393f8566f9a04a7d47b48 | 33.569482 | 87 | 0.669741 | 4.276036 | false | false | false | false |
spark/photon-tinker-ios | Photon-Tinker/Mesh/StepEnsureCorrectSelectedNetworkPassword.swift | 1 | 2058 | //
// Created by Raimundas Sakalauskas on 2019-03-08.
// Copyright (c) 2019 Particle. All rights reserved.
//
import Foundation
class StepEnsureCorrectSelectedNetworkPassword : Gen3SetupStep {
override func start() {
guard let context = self.context else {
return
}
if (self.context?.selectedNetworkPassword == nil) {
context.delegate.gen3SetupDidRequestToEnterSelectedNetworkPassword(self)
} else {
self.stepCompleted()
}
}
func setSelectedNetworkPassword(_ password: String, onComplete:@escaping (Gen3SetupFlowError?) -> ()) {
guard let context = self.context else {
onComplete(nil)
return
}
guard Gen3SetupStep.validateNetworkPassword(password) else {
onComplete(.PasswordTooShort)
return
}
/// NOT_FOUND: The device is not a member of a network
/// NOT_ALLOWED: Invalid commissioning credential
context.commissionerDevice!.transceiver?.sendAuth(password: password) { [weak self, weak context] result in
guard let self = self, let context = context, !context.canceled else {
return
}
self.log("trying password with character count: \(password.count)")
self.log("commissionerDevice.sendAuth: \(result.description())")
if (result == .NONE) {
self.log("password set with character count: \(password.count)")
context.selectedNetworkPassword = password
onComplete(nil)
self.stepCompleted()
} else if (result == .NOT_ALLOWED) {
onComplete(.WrongNetworkPassword)
} else {
onComplete(.BluetoothTimeout)
}
}
}
override func rewindTo(context: Gen3SetupContext) {
super.rewindTo(context: context)
guard let context = self.context else {
return
}
context.selectedNetworkPassword = nil
}
}
| apache-2.0 | ba1943ac7404158a8abc984084c91dfa | 29.716418 | 115 | 0.594266 | 5.170854 | false | false | false | false |
PigDogBay/Food-Hygiene-Ratings | Food Hygiene Ratings/UIViewControllerExtensions.swift | 1 | 2025 | //
// Alerts.swift
// Food Hygiene Ratings
//
// Created by Mark Bailey on 22/02/2017.
// Copyright © 2017 MPD Bailey Technology. All rights reserved.
//
import UIKit
import MessageUI
extension UIViewController
{
public func mpdbShowErrorAlert(_ title: String, msg : String)
{
let action = UIAlertAction(title: "OK", style: UIAlertAction.Style.default, handler: nil)
let controller = UIAlertController(title: title, message: msg, preferredStyle: UIAlertController.Style.alert)
controller.addAction(action)
self.present(controller, animated: true, completion: nil)
}
public func mpdbShowAlert(_ title: String, msg : String)
{
let action = UIAlertAction(title: "OK", style: UIAlertAction.Style.default, handler: nil)
let controller = UIAlertController(title: title, message: msg, preferredStyle: UIAlertController.Style.alert)
controller.addAction(action)
self.present(controller, animated: true, completion: nil)
}
public func mpdbCheckIsFirstTime()->Bool
{
let key = "HasWelcomeShown"
let defaults = UserDefaults.standard
let firstTimeSetting = defaults.object(forKey: key) as? Bool
if firstTimeSetting == nil
{
defaults.set(true, forKey: key)
defaults.synchronize()
return true
}
return false
}
public func mpdbSendEmail(recipients: [String], subject: String, body: String ){
if !MFMailComposeViewController.canSendMail()
{
self.mpdbShowErrorAlert("No Email", msg: "This device is not configured for sending emails.")
return
}
let mailVC = MFMailComposeViewController()
mailVC.mailComposeDelegate = self as? MFMailComposeViewControllerDelegate
mailVC.setSubject(subject)
mailVC.setToRecipients(recipients)
mailVC.setMessageBody(body, isHTML: false)
self.present(mailVC, animated: true, completion: nil)
}
}
| apache-2.0 | 5c510c26cf44ae0b2bf485abb173ba57 | 35.142857 | 117 | 0.664032 | 4.717949 | false | false | false | false |
sberrevoets/SDCAlertView | Source/Text Fields/TextFieldsViewController.swift | 1 | 1929 | import UIKit
private let kTextFieldCellIdentifier = "textFieldCell"
@available(iOSApplicationExtension, unavailable)
final class TextFieldsViewController: UIViewController {
var requiredHeight: CGFloat {
return self.tableView.rowHeight * CGFloat(self.tableView.numberOfRows(inSection: 0))
}
var visualStyle: AlertVisualStyle? {
didSet { self.tableView.rowHeight = visualStyle?.textFieldHeight ?? self.tableView.rowHeight }
}
private let tableView = UITableView(frame: .zero, style: .plain)
fileprivate let textFields: [UITextField]
init(textFields: [UITextField]) {
self.textFields = textFields
super.init(nibName: nil, bundle: nil)
}
required init?(coder aDecoder: NSCoder) {
self.textFields = []
super.init(nibName: nil, bundle: nil)
return nil
}
override func loadView() {
let nibName = String(describing: TextFieldCell.self)
let cellNib = UINib(nibName: nibName, bundle: Bundle.resourceBundle)
self.tableView.register(cellNib, forCellReuseIdentifier: kTextFieldCellIdentifier)
self.tableView.dataSource = self
self.tableView.separatorStyle = .none
self.tableView.isScrollEnabled = false
self.view = tableView
}
}
@available(iOSApplicationExtension, unavailable)
extension TextFieldsViewController: UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.textFields.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath)
-> UITableViewCell
{
let cell = tableView.dequeueReusableCell(withIdentifier: kTextFieldCellIdentifier,
for: indexPath) as? TextFieldCell
cell?.textField = self.textFields[(indexPath as NSIndexPath).row]
cell?.visualStyle = self.visualStyle
return cell!
}
}
| mit | 838b1772bb08f24416030d89366e82be | 32.258621 | 102 | 0.701918 | 5.062992 | false | false | false | false |
pomu0325/Swiftx | SwiftxTests/EitherSpec.swift | 3 | 2111 | //
// EitherSpec.swift
// Swiftx
//
// Created by Robert Widmann on 7/16/15.
// Copyright © 2015 TypeLift. All rights reserved.
//
import Swiftx
import XCTest
import SwiftCheck
extension Either where L : Arbitrary, R : Arbitrary {
static var arbitrary : Gen<Either<L, R>> {
return Gen.oneOf([
Either.Left <^> L.arbitrary,
Either.Right <^> R.arbitrary,
])
}
static func shrink(e : Either<L, R>) -> [Either<L, R>] {
switch e {
case .Left(let x):
return L.shrink(x).map(Either.Left)
case .Right(let x):
return R.shrink(x).map(Either.Right)
}
}
}
// Heterogenous equality
public func == <L : Equatable, R, S>(lhs : Either<L, R>, rhs : Either<L, S>) -> Bool {
switch (lhs, rhs) {
case let (.Left(l), .Left(r)) where l == r:
return true
default:
return false
}
}
public func == <L, R : Equatable, S>(lhs : Either<L, R>, rhs : Either<S, R>) -> Bool {
switch (lhs, rhs) {
case let (.Right(l), .Right(r)) where l == r:
return true
default:
return false
}
}
class EitherSpec : XCTestCase {
func testProperties() {
property("isLeft behaves") <- forAllShrink(Either<Int, Int>.arbitrary, shrinker: Either.shrink) { e in
return e.isLeft == e.fold(true, f: const(false))
}
property("isRight behaves") <- forAllShrink(Either<Int, Int>.arbitrary, shrinker: Either.shrink) { e in
return e.isRight == e.fold(false, f: const(true))
}
property("either is equivalent to explicit case analysis") <- forAllShrink(Either<Int, Int>.arbitrary, shrinker: Either.shrink) { e in
return forAll { (f : ArrowOf<Int, String>) in
let s : String
switch e {
case .Left(let x):
s = f.getArrow(x)
case .Right(let x):
s = f.getArrow(x)
}
return e.either(onLeft: f.getArrow, onRight: f.getArrow) == s
}
}
property("flatMap preserves .Left") <- forAllShrink(Either<String, Int>.arbitrary, shrinker: Either.shrink) { e in
return forAll { (f : ArrowOf<Int, UInt>) in
switch e {
case .Left(_):
return e.flatMap(Either<String, UInt>.Right • f.getArrow) == e
case .Right(_):
return Discard()
}
}
}
}
}
| bsd-3-clause | 27f6ebfacd1987de7e1beeff07f924d0 | 24.095238 | 136 | 0.628558 | 3.011429 | false | false | false | false |
robertherdzik/RHPreviewCell | Example/RHPreviewCellExample/RHPreviewCellExample/DetailsViewController.swift | 1 | 1535 | import UIKit
class DetailsViewController: UIViewController {
fileprivate let image: UIImage
init(withImage image: UIImage) {
self.image = image
super.init(nibName: nil, bundle: nil)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func loadView() {
view = DetailsView()
}
func castView() -> DetailsView {
return view as! DetailsView
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
showImage()
}
func showImage() {
castView().imageView.alpha = 0
castView().setImage(image)
UIView.animate(withDuration: 0.2, animations: { [weak self] in
self?.castView().imageView.alpha = 1
})
}
}
class DetailsView: UIView {
fileprivate let imageView = UIImageView()
init() {
super.init(frame: CGRect.zero)
backgroundColor = UIColor.white
addSubview(imageView)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func layoutSubviews() {
super.layoutSubviews()
let edgeSize = CGFloat(300)
imageView.frame = CGRect(x: 0, y: 0, width: edgeSize, height: edgeSize)
imageView.center = center
}
func setImage(_ image: UIImage) {
imageView.image = image
}
}
| mit | 66cb600ea22fe4b95710b32d10cc160f | 21.910448 | 79 | 0.576547 | 4.842271 | false | false | false | false |
kesun421/firefox-ios | Account/FxAPushMessageHandler.swift | 1 | 10985 | /* 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 Deferred
import Shared
import SwiftyJSON
let PendingAccountDisconnectedKey = "PendingAccountDisconnect"
/// This class provides handles push messages from FxA.
/// For reference, the [message schema][0] and [Android implementation][1] are both useful resources.
/// [0]: https://github.com/mozilla/fxa-auth-server/blob/master/docs/pushpayloads.schema.json#L26
/// [1]: https://dxr.mozilla.org/mozilla-central/source/mobile/android/services/src/main/java/org/mozilla/gecko/fxa/FxAccountPushHandler.java
/// The main entry points are `handle` methods, to accept the raw APNS `userInfo` and then to process the resulting JSON.
class FxAPushMessageHandler {
let profile: Profile
init(with profile: Profile) {
self.profile = profile
}
}
extension FxAPushMessageHandler {
/// Accepts the raw Push message from Autopush.
/// This method then decrypts it according to the content-encoding (aes128gcm or aesgcm)
/// and then effects changes on the logged in account.
@discardableResult func handle(userInfo: [AnyHashable: Any]) -> PushMessageResult {
guard let subscription = profile.getAccount()?.pushRegistration?.defaultSubscription else {
return deferMaybe(PushMessageError.notDecrypted)
}
guard let encoding = userInfo["con"] as? String, // content-encoding
let payload = userInfo["body"] as? String else {
return handleVerification()
}
// ver == endpointURL path, chid == channel id, aps == alert text and content_available.
let plaintext: String?
if let cryptoKeyHeader = userInfo["cryptokey"] as? String, // crypto-key
let encryptionHeader = userInfo["enc"] as? String, // encryption
encoding == "aesgcm" {
plaintext = subscription.aesgcm(payload: payload, encryptionHeader: encryptionHeader, cryptoHeader: cryptoKeyHeader)
} else if encoding == "aes128gcm" {
plaintext = subscription.aes128gcm(payload: payload)
} else {
plaintext = nil
}
guard let string = plaintext else {
return deferMaybe(PushMessageError.notDecrypted)
}
return handle(plaintext: string)
}
func handle(plaintext: String) -> PushMessageResult {
return handle(message: JSON(parseJSON: plaintext))
}
/// The main entry point to the handler for decrypted messages.
func handle(message json: JSON) -> PushMessageResult {
if !json.isDictionary() || json.isEmpty {
return handleVerification()
}
let rawValue = json["command"].stringValue
guard let command = PushMessageType(rawValue: rawValue) else {
print("Command \(rawValue) received but not recognized")
return deferMaybe(PushMessageError.messageIncomplete)
}
let result: PushMessageResult
switch command {
case .deviceConnected:
result = handleDeviceConnected(json["data"])
case .deviceDisconnected:
result = handleDeviceDisconnected(json["data"])
case .profileUpdated:
result = handleProfileUpdated()
case .passwordChanged:
result = handlePasswordChanged()
case .passwordReset:
result = handlePasswordReset()
case .collectionChanged:
result = handleCollectionChanged(json["data"])
case .accountVerified:
result = handleVerification()
}
return result
}
}
extension FxAPushMessageHandler {
func handleVerification() -> PushMessageResult {
// What we'd really like to be able to start syncing immediately we receive this
// message, but this method is run by the extension, so we can't do it here.
return deferMaybe(.accountVerified)
}
// This will be executed by the app, not the extension.
// This isn't guaranteed to be run (when the app is backgrounded, and the user
// doesn't tap on the notification), but that's okay because:
// We'll naturally be syncing shortly after startup.
func postVerification() -> Success {
if let account = profile.getAccount(),
let syncManager = profile.syncManager {
return account.advance().bind { _ in
return syncManager.syncEverything(why: .didLogin)
} >>> succeed
}
return succeed()
}
}
/// An extension to handle each of the messages.
extension FxAPushMessageHandler {
func handleDeviceConnected(_ data: JSON?) -> PushMessageResult {
guard let deviceName = data?["deviceName"].string else {
return messageIncomplete(.deviceConnected)
}
let message = PushMessage.deviceConnected(deviceName)
return deferMaybe(message)
}
}
extension FxAPushMessageHandler {
func handleDeviceDisconnected(_ data: JSON?) -> PushMessageResult {
guard let deviceId = data?["id"].string else {
return messageIncomplete(.deviceDisconnected)
}
if let ourDeviceId = self.getOurDeviceId(), deviceId == ourDeviceId {
// We can't disconnect the device from the account until we have
// access to the application, so we'll handle this properly in the AppDelegate,
// by calling the FxALoginHelper.applicationDidDisonnect(application).
profile.prefs.setBool(true, forKey: PendingAccountDisconnectedKey)
return deferMaybe(PushMessage.thisDeviceDisconnected)
}
guard let profile = self.profile as? BrowserProfile else {
// We can't look up a name in testing, so this is the same as
// not knowing about it.
return deferMaybe(PushMessage.deviceDisconnected(nil))
}
let clients = profile.remoteClientsAndTabs
let getClient = clients.getClient(fxaDeviceId: deviceId)
return getClient >>== { device in
let message = PushMessage.deviceDisconnected(device?.name)
if let id = device?.guid {
return clients.deleteClient(guid: id) >>== { _ in deferMaybe(message) }
}
return deferMaybe(message)
}
}
fileprivate func getOurDeviceId() -> String? {
return profile.getAccount()?.deviceRegistration?.id
}
}
extension FxAPushMessageHandler {
func handleProfileUpdated() -> PushMessageResult {
return unimplemented(.profileUpdated)
}
}
extension FxAPushMessageHandler {
func handlePasswordChanged() -> PushMessageResult {
return unimplemented(.passwordChanged)
}
}
extension FxAPushMessageHandler {
func handlePasswordReset() -> PushMessageResult {
return unimplemented(.passwordReset)
}
}
extension FxAPushMessageHandler {
func handleCollectionChanged(_ data: JSON?) -> PushMessageResult {
guard let collections = data?["collections"].arrayObject as? [String] else {
print("collections_changed received but incomplete: \(data ?? "nil")")
return deferMaybe(PushMessageError.messageIncomplete)
}
// Possible values: "addons", "bookmarks", "history", "forms", "prefs", "tabs", "passwords", "clients"
// syncManager will only do a subset; others will be ignored.
return profile.syncManager.syncNamedCollections(why: .push, names: collections) >>== { deferMaybe(.collectionChanged(collections: collections)) }
}
}
/// Some utility methods
fileprivate extension FxAPushMessageHandler {
func unimplemented(_ messageType: PushMessageType, with param: String? = nil) -> PushMessageResult {
if let param = param {
print("\(messageType) message received with parameter = \(param), but unimplemented")
} else {
print("\(messageType) message received, but unimplemented")
}
return deferMaybe(PushMessageError.unimplemented(messageType))
}
func messageIncomplete(_ messageType: PushMessageType) -> PushMessageResult {
print("\(messageType) message received, but incomplete")
return deferMaybe(PushMessageError.messageIncomplete)
}
}
enum PushMessageType: String {
case deviceConnected = "fxaccounts:device_connected"
case deviceDisconnected = "fxaccounts:device_disconnected"
case profileUpdated = "fxaccounts:profile_updated"
case passwordChanged = "fxaccounts:password_changed"
case passwordReset = "fxaccounts:password_reset"
case collectionChanged = "sync:collection_changed"
// This isn't a real message type, just the absence of one.
case accountVerified = "account_verified"
}
enum PushMessage: Equatable {
case deviceConnected(String)
case deviceDisconnected(String?)
case profileUpdated
case passwordChanged
case passwordReset
case collectionChanged(collections: [String])
case accountVerified
// This is returned when we detect that it is us that has been disconnected.
case thisDeviceDisconnected
var messageType: PushMessageType {
switch self {
case .deviceConnected(_):
return .deviceConnected
case .deviceDisconnected(_):
return .deviceDisconnected
case .thisDeviceDisconnected:
return .deviceDisconnected
case .profileUpdated:
return .profileUpdated
case .passwordChanged:
return .passwordChanged
case .passwordReset:
return .passwordReset
case .collectionChanged(collections: _):
return .collectionChanged
case .accountVerified:
return .accountVerified
}
}
public static func ==(lhs: PushMessage, rhs: PushMessage) -> Bool {
guard lhs.messageType == rhs.messageType else {
return false
}
switch (lhs, rhs) {
case (.deviceConnected(let lName), .deviceConnected(let rName)):
return lName == rName
case (.collectionChanged(let lList), .collectionChanged(let rList)):
return lList == rList
default:
return true
}
}
}
typealias PushMessageResult = Deferred<Maybe<PushMessage>>
enum PushMessageError: MaybeErrorType {
case notDecrypted
case messageIncomplete
case unimplemented(PushMessageType)
case timeout
case accountError
case noProfile
public var description: String {
switch self {
case .notDecrypted: return "notDecrypted"
case .messageIncomplete: return "messageIncomplete"
case .unimplemented(let what): return "unimplemented=\(what)"
case .timeout: return "timeout"
case .accountError: return "accountError"
case .noProfile: return "noProfile"
}
}
}
| mpl-2.0 | 7ef555c8e39b4a73338c166e0b5171ab | 36.363946 | 153 | 0.661538 | 5.201231 | false | false | false | false |
bitboylabs/selluv-ios | selluv-ios/selluv-ios/Classes/Controller/UI/Seller/SLV_812_UserPageItem.swift | 1 | 12363 | //
// SLV_812_UserPageItem.swift
// selluv-ios
//
// Created by 조백근 on 2017. 1. 31..
// Copyright © 2017년 BitBoy Labs. All rights reserved.
//
import Foundation
import UIKit
import SwifterSwift
import PullToRefresh
class SLV_812_UserPageItem: UICollectionViewController {
let refresher = PullToRefresh()
var itemInfo: IndicatorInfo = IndicatorInfo(title: "아이템 0")//tab 정보
let selluvWaterFallCellIdentify = "userPageItemWaterFallCellIdentify"
var itemList: [SLVDetailProduct] = []
let delegateHolder = SLVTabContainNavigationControllerDelegate()
weak var delegate: SLVButtonBarDelegate?// 델리게이트.
weak var myNavigationDelegate: SLVNavigationControllerDelegate?// push를 위한 네비게이션
override func viewDidLoad() {
super.viewDidLoad()
self.prepare()
self.setupLongPress()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func linkDelegate(controller: AnyObject) {
self.delegate = controller as? SLVButtonBarDelegate
// self.myNavigationDelegate = controller as? SLVNavigationControllerDelegate
}
func prepare() {
self.navigationController!.delegate = delegateHolder
self.view.backgroundColor = UIColor.clear
self.automaticallyAdjustsScrollViewInsets = false
self.loadProducts(isContinue: false)
let collection :UICollectionView = collectionView!;
collection.remembersLastFocusedIndexPath = true
collection.frame = screenBounds
collection.setCollectionViewLayout(CHTCollectionViewWaterfallLayout(), animated: false)
collection.backgroundColor = UIColor.clear
collection.register(UINib(nibName: "SLVUserProductCell", bundle: nil), forCellWithReuseIdentifier: selluvWaterFallCellIdentify)
collection.reloadData()
refresher.position = .bottom
collection.addPullToRefresh(refresher) {
self.loadProducts(isContinue: true)
}
}
func setupLongPress() {
let overlay = GHContextMenuView()
overlay.delegate = self
overlay.dataSource = self
let selector = #selector(GHContextMenuView.longPressDetected(_:))
let longPress = UILongPressGestureRecognizer(target: overlay, action: selector)
self.collectionView?.addGestureRecognizer(longPress)
}
deinit {
self.collectionView?.removePullToRefresh((self.collectionView?.bottomPullToRefresh!)!)
}
override func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
let parent = self.delegate as! SLV_800_UserPageController
let definer = parent.myCustomBar?.behaviorDefiner
definer?.scrollViewDidEndDecelerating(scrollView)
}
override func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
let parent = self.delegate as! SLV_800_UserPageController
let definer = parent.myCustomBar?.behaviorDefiner
definer?.scrollViewDidEndDragging(scrollView, willDecelerate: decelerate)
}
override func scrollViewDidScroll(_ scrollView: UIScrollView) {
let parent = self.delegate as! SLV_800_UserPageController
let definer = parent.myCustomBar?.behaviorDefiner
definer?.scrollViewDidScroll(scrollView)
parent.updateSubScrollViewDidScroll(scrollView)
if scrollView == self.collectionView {
let off = scrollView.contentOffset
if off.y > 0 {
// hide
self.delegate?.hideByScroll()
} else {
//show
self.delegate?.showByScroll()
}
}
}
//MARK: DataCalling
func loadProducts(isContinue: Bool) {
let parent = self.delegate as! SLV_800_UserPageController
let user = parent.sellerId//BBAuthToken.shared.name()
ProductsModel.shared.productsForSeller(userId: user!, kind: "items", isSame: isContinue) { (success, products) in
if let products = products {
self.itemList.append(contentsOf: products)
parent.delay(time: 0.2) {
self.collectionView?.reloadData()
}
}
}
}
}
// MARK: - IndicatorInfoProvider
extension SLV_812_UserPageItem: IndicatorInfoProvider {
func indicatorInfo(for pagerTabStripController: PagerTabStripViewController) -> IndicatorInfo {
return itemInfo
}
}
// MARK: - Collection View
extension SLV_812_UserPageItem {
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let collectionCell: SLVUserProductCell = collectionView.dequeueReusableCell(withReuseIdentifier: selluvWaterFallCellIdentify, for: indexPath as IndexPath) as! SLVUserProductCell
collectionCell.delegate = self
let item = self.itemList[indexPath.row]
collectionCell.setupData(item: item)
return collectionCell
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int{
return self.itemList.count
}
override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let cell = collectionView.cellForItem(at: indexPath) as! SLVUserProductCell
collectionView.setToIndexPath(indexPath: indexPath as NSIndexPath)
let board = UIStoryboard(name:"Main", bundle: nil)
let productController = board.instantiateViewController(withIdentifier: "SLV_501_ProcuctDetailController") as! SLV_501_ProcuctDetailController
productController.listProductInfo = cell.info
productController.parentCellImage = cell.imageViewContent!.image
productController.imagePath = indexPath as NSIndexPath?
navigationController?.pushViewController(productController, animated: true)
}
func pageViewControllerLayout () -> UICollectionViewFlowLayout {
let flowLayout = UICollectionViewFlowLayout()
let itemSize = self.navigationController!.isNavigationBarHidden ?
CGSize(width: screenWidth, height: screenHeight+20) : CGSize(width: screenWidth, height: screenHeight-navigationHeaderAndStatusbarHeight)
flowLayout.itemSize = itemSize
flowLayout.minimumLineSpacing = 0
flowLayout.minimumInteritemSpacing = 0
flowLayout.scrollDirection = .horizontal
return flowLayout
}
}
extension SLV_812_UserPageItem: CHTCollectionViewDelegateWaterfallLayout, SLVCollectionTransitionProtocol {
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
var itemSize = DEFAULT_PHOTO_SIZE
var isFinish = true
if self.itemList.count > 0 && self.itemList.count >= indexPath.row + 1 {
let info = self.itemList[indexPath.row]
var name = ""
if info.photos != nil {
if (info.photos?.count)! > 0 {
name = (info.photos?.first)!
}
}
if name != "" {
let from = URL(string: "\(dnProduct)\(name)")
isFinish = false
ImageScout.shared.scoutImage(url: from!) { error, size, type in
isFinish = true
if let error = error {
print(error.code)
} else {
print("Size: \(size)")
print("Type: \(type.rawValue)")
itemSize = size
}
}
}
}
var cnt: Int = 0
var sec: Double = 0
while(isFinish == false && 2 < sec ) {
RunLoop.current.run(until: Date(timeIntervalSinceNow: 0.01))
cnt = cnt + 1
sec = Double(cnt) * Double(0.01)
}
let imageHeight = itemSize.height*gridWidth/itemSize.width + SLVUserProductCell.infoHeight + SLVUserProductCell.humanHeight
log.debug("remote image calc cell width: \(gridWidth) , height: \(imageHeight)")
return CGSize(width: gridWidth, height: imageHeight)
}
func transitionTabCollectionView() -> UICollectionView!{
return collectionView
}
}
extension SLV_812_UserPageItem: SLVCollectionLinesDelegate {
// 스타일 영역을 터치한다.
func didTouchedStyleThumbnail(info: AnyObject) {
}
// 좋아요를 터치한다.
func didTouchedLikeButton(info: AnyObject) {
}
func didTouchedItemDescription(info: AnyObject) {
}
func didTouchedUserDescription(info: AnyObject) {
}
}
extension SLV_812_UserPageItem: GHContextOverlayViewDataSource, GHContextOverlayViewDelegate {
func shouldShowMenu(at point: CGPoint) -> Bool {
let path = self.collectionView?.indexPathForItem(at: point)
if path != nil {
let cell = self.collectionView?.cellForItem(at: path!)
return cell != nil
}
return false
}
func shouldShowMenuOnParentImage(at point: CGPoint) -> UIImage! {
let path = self.collectionView?.indexPathForItem(at: point)
if path != nil {
let cell = self.collectionView?.cellForItem(at: path!) as? SLVUserProductCell
if cell != nil {
let image = cell!.imageViewContent?.image
return image
}
}
return nil
}
func shouldShowMenuParentImageFrame(at point: CGPoint) -> CGRect {
let path = self.collectionView?.indexPathForItem(at: point)
if path != nil {
let cell = self.collectionView?.cellForItem(at: path!) as? SLVUserProductCell
if cell != nil {
let frame = cell?.imageViewContent?.frame
var newFrame = self.view?.convert(frame!, to: nil)
let x = ((screenWidth/2) > point.x) ? 17:(screenWidth/2 + 5)
newFrame?.origin.x = x
return newFrame!
}
}
return .zero
}
func numberOfMenuItems() -> Int {
return 4
}
func itemInfoForItem(at index: Int) -> GHContextItemView! {
let itemView = GHContextItemView()
switch index {
case 0:
itemView.typeDesc = "좋아요"
itemView.baseImage = UIImage(named: "longpress-like-nor.png")
itemView.selectedImage = UIImage(named: "longpress-like-focus.png")
// itemView.baseImage = UIImage(named: "longpress-like-not-nor.png")
// itemView.selectedImage = UIImage(named: "longpress-like-not-focus.png")
break
case 1:
itemView.typeDesc = "피드"
itemView.baseImage = UIImage(named: "longpress-feed-nor.png")
itemView.selectedImage = UIImage(named: "longpress-feed-focus.png")
break
case 2:
itemView.typeDesc = "공유"
itemView.baseImage = UIImage(named: "longpress-share-nor.png")
itemView.selectedImage = UIImage(named: "longpress-share-focus.png")
break
case 3:
itemView.typeDesc = "더보기"
itemView.baseImage = UIImage(named: "longpress-more-nor.png")
itemView.selectedImage = UIImage(named: "longpress-more-focus.png")
break
default:
break
}
return itemView
}
func didSelectItem(at selectedIndex: Int, forMenuAt point: CGPoint) {
// let path = self.collectionView?.indexPathForItem(at: point)
var message = ""
switch selectedIndex {
case 0:
message = "좋아요 selected"
break
case 1:
message = "피드 selected"
break
case 2:
message = "공유 selected"
break
case 3:
message = "더보기 selected"
break
default:
break
}
AlertHelper.alert(message: message)
}
}
| mit | adb138db1864233df16a069d0f554ee9 | 35.873494 | 185 | 0.626287 | 5.348187 | false | false | false | false |
mscline/BarGraph | LifespanPlanning/BarGraph.swift | 1 | 17289 | //
// BarGraph.swift
// Lifespan
//
// Created by Monsoon Co on 6/2/15.
// Copyright (c) 2015 Monsoon Co. All rights reserved.
//
import UIKit
class BarGraph: UICollectionView, UICollectionViewDelegateFlowLayout, UICollectionViewDataSource {
// data arrays
var dataSetFromUser:Array<Array<BarGraphDataItem>>? // format dataSet[category][column]
var dataSetForDisplay:Array<Array<BarGraphDataItem>>? // flips x and y coords of input matrix, giving us dataSet[column][category]
var linearVersionOfDataSetForCollectionView:Array<BarGraphDataItem>?
// settings
var showColumnTotals:Bool = false
var showColumnSubTotals:Bool = false
// AutoCalc / set by Parent View
var maxValue:CGFloat = 0 // will be = last value in y-Axis values
var widthOfCell:CGFloat = 0
var yScaleFactor:CGFloat = 1.0
// Touches
var delegateForTouches:BarGraphItemWasTouchedProtocol?
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setupCollectionView()
}
override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
super.init(frame: frame, collectionViewLayout: layout)
setupCollectionView()
}
// MARK: COLLECTION VIEW - SETUP
// here we are not going to create a full custom layout, we are just going to use a layout flow and override some of its delegate methods
// - a cell / data item stores the color and its height values
func setupCollectionView(){
dataSource = self
delegate = self
// register collection view cell so can create programatically
self.registerClass(BarGraphColumnCell.classForCoder(), forCellWithReuseIdentifier: "barGraphDataCell")
// set scroll direction and set collection view delegate
let layout = UICollectionViewFlowLayout()
layout.scrollDirection = UICollectionViewScrollDirection.Horizontal // a horizontal scroll gives you a vertical layout !!!
collectionViewLayout = layout // this will automatically set the flowLayout delegate to be the same as the collectionView.delegate
// add gestures to cv (not going to use didSelect delegate method because harder to implement various touches)
addGestures()
}
// MARK: LOAD DATA
func loadDataForCollectionView(#arraysOfCategoryItemsNestedInsideOneBigArray:Array<Array<BarGraphDataItem>>, widthOfColumn:CGFloat) {
// set variables
self.widthOfCell = widthOfColumn
self.dataSetFromUser = arraysOfCategoryItemsNestedInsideOneBigArray
// reorganize data matrix
let dataSetWithPaddingCells = addRowToMatrixToCreateTopSpace(&dataSetFromUser!)
self.dataSetForDisplay = flipXYCoordinatesInMatrix(inputMatrix:dataSetWithPaddingCells)
// calculate element heights
setScaledHeight()
clipColumnItemsHeightIfGoingOffScreen_andSetSpacerValueWhichWillBeUsedAsTitle()
// covert data matrix into array and display
self.linearVersionOfDataSetForCollectionView = convertMatrixIntoSingleArray(dataSetForDisplay: dataSetForDisplay!)
self.reloadData()
}
// MARK: COLLECTION VIEW - DATASOURCE
func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
return 1;
}
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
if linearVersionOfDataSetForCollectionView == nil { return 0; }
return linearVersionOfDataSetForCollectionView!.count
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let barItem = linearVersionOfDataSetForCollectionView![indexPath.row]
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("barGraphDataCell", forIndexPath: indexPath) as! BarGraphColumnCell
cell.backgroundColor = barItem.color
cell.layer.borderColor = UIColor.blackColor().CGColor
addColumnSubTotalsIfRequired(dataObject: barItem, cell: cell, indexPath: indexPath)
formatCell(dataObject: barItem, cell: cell, indexPath: indexPath)
return cell
}
func formatCell(#dataObject:BarGraphDataItem, cell:BarGraphColumnCell, indexPath:NSIndexPath){
// fail ???
// if collection view being reloaded due to a layout change, it is necessary to update subview sizes
cell.label.frame = CGRectMake(0, 0, self.frame.size.width, self.frame.size.height)
cell.bottomLabel = UILabel(frame: CGRectMake(0, self.frame.size.height - 14, self.frame.size.width, 14))
// format based on whether spacer, normal item, selected item
if isASpacerCell(indexPath) {
cell.layer.borderWidth = 0
}else if dataObject.isSelected == true {
cell.layer.borderWidth = 2.5
}else{
cell.layer.borderWidth = 0.5
}
}
func addColumnSubTotalsIfRequired(#dataObject:BarGraphDataItem, cell:BarGraphColumnCell, indexPath:NSIndexPath){
var textString = ""
let isAHeaderCell = isASpacerCell(indexPath)
// add total sums
if isAHeaderCell && showColumnTotals {
let text = String("\(dataObject.value_akaHeightOfBar)")
cell.bottomLabel.attributedText = TextFormatter.createAttributedString(text, withFont: nil, fontSize: nil, fontColor: nil, nsTextAlignmentStyle: NSTextAlignment.Center)
} else {
cell.bottomLabel.attributedText = TextFormatter.createAttributedString("", withFont: nil, fontSize: nil, fontColor: nil, nsTextAlignmentStyle: NSTextAlignment.Center)
}
// add subCategory Totals
if !isAHeaderCell && showColumnSubTotals {
let text = String("\(dataObject.value_akaHeightOfBar)")
var attributedText = TextFormatter.createAttributedString(text, withFont: nil, fontSize: nil, fontColor: nil, nsTextAlignmentStyle: NSTextAlignment.Center)
cell.label.attributedText = attributedText
} else {
cell.label.attributedText = TextFormatter.createAttributedString("", withFont: nil, fontSize: nil, fontColor: nil, nsTextAlignmentStyle: NSTextAlignment.Center)
}
}
func isASpacerCell(indexPath:NSIndexPath) -> Bool {
let numberOfItemsInColumn = dataSetForDisplay![0].count
let rowNumber = indexPath.row % numberOfItemsInColumn
if rowNumber == 0 {
return true
} else {
return false
}
}
// MARK: COLLECTION VIEW - LAYOUT
// set size of cell
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
let barItem = linearVersionOfDataSetForCollectionView![indexPath.row]
let height = barItem.scaledHeight
return CGSizeMake(widthOfCell, height)
}
// spacing between columns
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAtIndex section: Int) -> CGFloat {
return 0
}
// spacing between items within column
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAtIndex section: Int) -> CGFloat {
return 0
}
// MARK: SETUP GESTURES
func addGestures() {
var tapGestureRecognizer = UITapGestureRecognizer(target: self, action: Selector("handleTap:"))
addGestureRecognizer(tapGestureRecognizer)
var doubleTapGestureRecognizer = UITapGestureRecognizer(target: self, action: Selector("handleDoubleTap:"))
doubleTapGestureRecognizer.numberOfTapsRequired = 2
addGestureRecognizer(doubleTapGestureRecognizer)
var longPressGestureRecognizer = UILongPressGestureRecognizer(target: self, action: Selector("handleLongTap:"))
addGestureRecognizer(longPressGestureRecognizer)
var panGestureRecognizer = UIPanGestureRecognizer(target: self, action: Selector("handlePan:"))
addGestureRecognizer(panGestureRecognizer)
tapGestureRecognizer.requireGestureRecognizerToFail(doubleTapGestureRecognizer)
tapGestureRecognizer.requireGestureRecognizerToFail(longPressGestureRecognizer)
tapGestureRecognizer.requireGestureRecognizerToFail(panGestureRecognizer)
}
func handleTap(sender:UIGestureRecognizer){
if sender.state == UIGestureRecognizerState.Ended
{
forwardGestureToUser(sender, touchType: TouchType.singleTap)
}
}
func handleDoubleTap(sender:UITapGestureRecognizer){
if sender.state == UIGestureRecognizerState.Ended
{
forwardGestureToUser(sender, touchType: TouchType.doubleTap)
}
}
func handleLongTap(sender:UILongPressGestureRecognizer){
if sender.state == UIGestureRecognizerState.Ended {
forwardGestureToUser(sender, touchType: TouchType.longPress)
}
}
func handlePan(sender:UIPanGestureRecognizer){
if sender.state == UIGestureRecognizerState.Began {
forwardGestureToUser(sender, touchType: TouchType.dragStart)
} else if sender.state == UIGestureRecognizerState.Changed {
forwardGestureToUser(sender, touchType: TouchType.dragInProgress)
} else if sender.state == UIGestureRecognizerState.Ended {
forwardGestureToUser(sender, touchType: TouchType.dragEnd)
}
}
// MARK: HANDLE GESTURES
func forwardGestureToUser(sender:UIGestureRecognizer, touchType:TouchType){
let pointTouched = sender.locationInView(self)
let locationOfTouchInGraph = sender.locationInView(self.superview)
let touchInfo = returnCorrected_touchOrigin_column_category_andConfirmIsValid(pointTouched: pointTouched)
// if invalid touch, exit (This shouldn't happen unless dragging object)
if touchInfo.3 == false {
delegateForTouches?.graphReceivedTouch(touchOrigin: TouchOrigin.outOfBounds, touchType: touchType, columnTouched: 0, subCategory: 0, locationOfTouchOnGraph: locationOfTouchInGraph)
return
}
// forward info to user
delegateForTouches?.graphReceivedTouch(touchOrigin: touchInfo.0, touchType: touchType, columnTouched: touchInfo.1, subCategory: touchInfo.2, locationOfTouchOnGraph: locationOfTouchInGraph)
}
// MARK: helpers
func returnCorrected_touchOrigin_column_category_andConfirmIsValid(#pointTouched:CGPoint) -> (TouchOrigin, Int, Int, Bool) {
var touchOrigin = TouchOrigin.barGraphItem
let tupleWith_isValid_column_subCategory = getIndexForTouchPointAndConvertIntoTupleWithIsValid_column_subCategory(pointTouched: pointTouched)
let column = tupleWith_isValid_column_subCategory.1
// if touch is not on a cell, then exit (this should never happen)
if tupleWith_isValid_column_subCategory.0 == false {
return (touchOrigin, 0, 0, false);
}
// if touch on spacer cell, then change touch origin
// (that is, we want to know if it is in subCategory index == 0)
if tupleWith_isValid_column_subCategory.2 == 0 {
touchOrigin = TouchOrigin.aboveBarGraphColumn
}
// the subCategory row numbers are in reverse order for display, fix it
let currentSubCategoryIndex = tupleWith_isValid_column_subCategory.2
let correctedSubcategory = currentSubCategoryIndex - 1 // don't include the cell used for padding
return (touchOrigin, column, correctedSubcategory, true)
}
func getIndexForTouchPointAndConvertIntoTupleWithIsValid_column_subCategory(#pointTouched:CGPoint) -> (Bool, Int, Int) {
let index = self.indexPathForItemAtPoint(pointTouched)?.row
if index == nil { return (false,0,0); }
let numberOfItemsInColumn = dataSetForDisplay![0].count
let column = Int(index! / numberOfItemsInColumn)
let subCategory = index! % numberOfItemsInColumn
return (true, column, subCategory)
}
// MARK: DATA MANIPULATION
func checkDatasetsDataIntegrity(){
}
func flipXYCoordinatesInMatrix(#inputMatrix:Array<Array<BarGraphDataItem>>) -> Array<Array<BarGraphDataItem>> {
// PART 1: build an empty output matrix of same size as input matrix but with flipped x and y components
var outputArray = [Array<BarGraphDataItem>]()
// for each item in a row of our input array, we will create a column for our output array
var row = inputMatrix[0]
for item in row {
var column = [BarGraphDataItem]()
outputArray.append(column)
}
// PART 2: iterate through each item in the input array and set the proper value in the output array (it is the inverse)
let numberOfRows = inputMatrix.count
let numberOfColumns = inputMatrix[0].count
for var row = 0; row < numberOfRows; row++ {
for var column = 0; column < numberOfColumns; column++ {
let objectFromInputArray = inputMatrix[row][column]
outputArray[column].append(objectFromInputArray)
}
}
return outputArray
}
func convertMatrixIntoSingleArray(#dataSetForDisplay:Array<Array<BarGraphDataItem>>!) -> Array <BarGraphDataItem> {
var outputArray = [BarGraphDataItem]()
for nestedArray in dataSetForDisplay {
outputArray = outputArray + nestedArray
}
return outputArray
}
func addRowToMatrixToCreateTopSpace(inout inputMatrix:Array<Array<BarGraphDataItem>>) -> Array<Array<BarGraphDataItem>> {
// create a new row to insert our values in
var addRowToArray = [BarGraphDataItem]()
// for each column in our matrix, insert a black colored barItem
let row = inputMatrix[0]
for column in row {
var blackBarItem = BarGraphDataItem(columnName: "spacer", subCategoryName: "spacer", value: 100000, color: UIColor.clearColor())
addRowToArray.append(blackBarItem)
}
// add the new row and return the value
inputMatrix.insert(addRowToArray, atIndex: 0)
return inputMatrix
}
func setScaledHeight(){
// iterate thru all items and add scaled height
for column in dataSetForDisplay! {
for item in column {
item.scaledHeight = item.value_akaHeightOfBar * yScaleFactor
}
}
}
func clipColumnItemsHeightIfGoingOffScreen_andSetSpacerValueWhichWillBeUsedAsTitle(){
for column in dataSetForDisplay! {
let maxPossibleValue = self.frame.height
var sumOfColumnHeightsSoFar:CGFloat = 0
// for each item in column, starting with the last
for var i = column.count - 1; i > -1; i-- {
var item = column[i]
if sumOfColumnHeightsSoFar + item.scaledHeight > maxPossibleValue {
item.scaledHeight = maxPossibleValue - sumOfColumnHeightsSoFar
}
sumOfColumnHeightsSoFar = sumOfColumnHeightsSoFar + item.scaledHeight
}
column[0].value_akaHeightOfBar = (sumOfColumnHeightsSoFar - column[0].scaledHeight) / yScaleFactor
}
}
// OTHER
func printDataSet(inputMatrix:Array<Array<BarGraphDataItem>>){
for array in inputMatrix {
println(); println(); println()
print("[")
for item in array {
print(" \(item.subCategoryName)/\(item.value_akaHeightOfBar)/\(item.scaledHeight), ")
}
print("]")
}
}
}
| mit | dc3cae1823dd7285d9a524d0e4d0ff34 | 34.068966 | 196 | 0.636937 | 5.947368 | false | false | false | false |
red-spotted-newts-2014/Im-In | im-in-ios/im-in-ios/untitled folder/APIInvitedEventController.swift | 1 | 1447 | //
// APIController.swift
// helloworld
//
// Created by fahia mohamed on 2014-08-14.
// Copyright (c) 2014 fahia mohamed. All rights reserved.
//
import Foundation
protocol APIInvitedEventControllerProtocol {
func didReceiveAPIResults(results: NSDictionary)
}
class APIInvitedEventController {
var delegate: APIInvitedEventControllerProtocol?
init() {
}
func loadAllEvents() {
println("APIController#loadAllEvents")
let urlPath = "http://10.0.2.26:3000/events.json"
let url: NSURL = NSURL(string: urlPath)
let session = NSURLSession.sharedSession()
let task = session.dataTaskWithURL(url, completionHandler: {data, response, error -> Void in
println("Task completed")
if(error) {
// If there is an error in the web request, print it to the console
println(error.localizedDescription)
}
var err: NSError?
var jsonResult = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: &err) as NSDictionary
if(err != nil) {
// If there is an error parsing JSON, print it to the console
println("JSON Error \(err!.localizedDescription)")
}
self.delegate?.didReceiveAPIResults(jsonResult) // THIS IS THE NEW LINE!!
})
task.resume()
}
} | mit | faf0cbcc8dc50765099f91456d084207 | 31.177778 | 151 | 0.62405 | 4.823333 | false | false | false | false |
CatchChat/Yep | Yep/ViewControllers/Register/RegisterSelectSkillsLayout.swift | 1 | 3189 | //
// RegisterSelectSkillsLayout.swift
// Yep
//
// Created by NIX on 15/7/9.
// Copyright (c) 2015年 Catch Inc. All rights reserved.
//
import UIKit
final class RegisterSelectSkillsLayout: UICollectionViewFlowLayout {
let leftEdgeInset: CGFloat = registerPickSkillsLayoutLeftEdgeInset
override func layoutAttributesForElementsInRect(rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
let layoutAttributes = super.layoutAttributesForElementsInRect(rect)
// 先按照每个 item 的 centerY 分组
var rowCollections = [CGFloat: [UICollectionViewLayoutAttributes]]()
if let layoutAttributes = layoutAttributes {
for (_, attributes) in layoutAttributes.enumerate() {
let centerY = CGRectGetMidY(attributes.frame)
if let rowCollection = rowCollections[centerY] {
var rowCollection = rowCollection
rowCollection.append(attributes)
rowCollections[centerY] = rowCollection
} else {
rowCollections[centerY] = [attributes]
}
}
}
// 再调整每一行的 item 的 frame
for (_, rowCollection) in rowCollections {
let rowItemsCount = rowCollection.count
// 每一行总的 InteritemSpacing
//let aggregateInteritemSpacing = minimumInteritemSpacing * CGFloat(rowItemsCount - 1)
// 每一行所有 items 的宽度
var aggregateItemsWidth: CGFloat = 0
for attributes in rowCollection {
aggregateItemsWidth += CGRectGetWidth(attributes.frame)
}
// 计算出有效的 width 和需要偏移的 offset
//let alignmentWidth = aggregateItemsWidth + aggregateInteritemSpacing
//let alignmentOffsetX = (CGRectGetWidth(collectionView!.bounds) - alignmentWidth) / 2
// 调整每个 item 的 origin.x 即可
var previousFrame = CGRectZero
let rowFullWidth: CGFloat = rowCollection.map({ $0.frame.width }).reduce(0, combine: +) + CGFloat(rowItemsCount - 1) * minimumInteritemSpacing
let firstOffset: CGFloat
if let collectionView = collectionView {
firstOffset = (collectionView.frame.width - rowFullWidth) / 2
} else {
fatalError("not collectionView")
}
for attributes in rowCollection {
var itemFrame = attributes.frame
if attributes.representedElementCategory == .Cell {
if CGRectEqualToRect(previousFrame, CGRectZero) {
itemFrame.origin.x = firstOffset //+ leftEdgeInset
} else {
itemFrame.origin.x = CGRectGetMaxX(previousFrame) + minimumInteritemSpacing
}
attributes.frame = itemFrame
}
previousFrame = itemFrame
}
}
return layoutAttributes
}
override func shouldInvalidateLayoutForBoundsChange(newBounds: CGRect) -> Bool {
return true
}
}
| mit | 0f7fdaacbdb230358873f8436acfafb4 | 33.344444 | 154 | 0.599806 | 5.99031 | false | false | false | false |
manavgabhawala/swift | test/SILGen/function_conversion_objc.swift | 1 | 6117 | // RUN: %target-swift-frontend -Xllvm -new-mangling-for-tests -sdk %S/Inputs %s -I %S/Inputs -enable-source-import -emit-silgen -verify | %FileCheck %s
import Foundation
// REQUIRES: objc_interop
// ==== Metatype to object conversions
// CHECK-LABEL: sil hidden @_T024function_conversion_objc20convMetatypeToObjectySo8NSObjectCmADcF
func convMetatypeToObject(_ f: @escaping (NSObject) -> NSObject.Type) {
// CHECK: function_ref @_T0So8NSObjectCABXMTIxxd_ABs9AnyObject_pIxxo_TR
// CHECK: partial_apply
let _: (NSObject) -> AnyObject = f
}
// CHECK-LABEL: sil shared [transparent] [reabstraction_thunk] @_T0So8NSObjectCABXMTIxxd_ABs9AnyObject_pIxxo_TR : $@convention(thin) (@owned NSObject, @owned @callee_owned (@owned NSObject) -> @thick NSObject.Type) -> @owned AnyObject {
// CHECK: apply %1(%0)
// CHECK: thick_to_objc_metatype {{.*}} : $@thick NSObject.Type to $@objc_metatype NSObject.Type
// CHECK: objc_metatype_to_object {{.*}} : $@objc_metatype NSObject.Type to $AnyObject
// CHECK: return
@objc protocol NSBurrito {}
// CHECK-LABEL: sil hidden @_T024function_conversion_objc31convExistentialMetatypeToObjectyAA9NSBurrito_pXpAaC_pcF
func convExistentialMetatypeToObject(_ f: @escaping (NSBurrito) -> NSBurrito.Type) {
// CHECK: function_ref @_T024function_conversion_objc9NSBurrito_pAaB_pXmTIxxd_AaB_ps9AnyObject_pIxxo_TR
// CHECK: partial_apply
let _: (NSBurrito) -> AnyObject = f
}
// CHECK-LABEL: sil shared [transparent] [reabstraction_thunk] @_T024function_conversion_objc9NSBurrito_pAaB_pXmTIxxd_AaB_ps9AnyObject_pIxxo_TR : $@convention(thin) (@owned NSBurrito, @owned @callee_owned (@owned NSBurrito) -> @thick NSBurrito.Type) -> @owned AnyObject
// CHECK: apply %1(%0)
// CHECK: thick_to_objc_metatype {{.*}} : $@thick NSBurrito.Type to $@objc_metatype NSBurrito.Type
// CHECK: objc_existential_metatype_to_object {{.*}} : $@objc_metatype NSBurrito.Type to $AnyObject
// CHECK: return
// CHECK-LABEL: sil hidden @_T024function_conversion_objc28convProtocolMetatypeToObjectyAA9NSBurrito_pmycF
func convProtocolMetatypeToObject(_ f: @escaping () -> NSBurrito.Protocol) {
// CHECK: function_ref @_T024function_conversion_objc9NSBurrito_pXMtIxd_So8ProtocolCIxo_TR
// CHECK: partial_apply
let _: () -> Protocol = f
}
// CHECK-LABEL: sil shared [transparent] [reabstraction_thunk] @_T024function_conversion_objc9NSBurrito_pXMtIxd_So8ProtocolCIxo_TR : $@convention(thin) (@owned @callee_owned () -> @thin NSBurrito.Protocol) -> @owned Protocol
// CHECK: apply %0() : $@callee_owned () -> @thin NSBurrito.Protocol
// CHECK: objc_protocol #NSBurrito : $Protocol
// CHECK: copy_value
// CHECK: return
// ==== Representation conversions
// CHECK-LABEL: sil hidden @_T024function_conversion_objc11funcToBlockyyXByycF : $@convention(thin) (@owned @callee_owned () -> ()) -> @owned @convention(block) () -> ()
// CHECK: [[BLOCK_STORAGE:%.*]] = alloc_stack $@block_storage
// CHECK: [[BLOCK:%.*]] = init_block_storage_header [[BLOCK_STORAGE]]
// CHECK: [[COPY:%.*]] = copy_block [[BLOCK]] : $@convention(block) () -> ()
// CHECK: return [[COPY]]
func funcToBlock(_ x: @escaping () -> ()) -> @convention(block) () -> () {
return x
}
// CHECK-LABEL: sil hidden @_T024function_conversion_objc11blockToFuncyycyyXBF : $@convention(thin) (@owned @convention(block) () -> ()) -> @owned @callee_owned () -> ()
// CHECK: bb0([[ARG:%.*]] : $@convention(block) () -> ()):
// CHECK: [[COPIED:%.*]] = copy_block [[ARG]]
// CHECK: [[BORROWED_COPIED:%.*]] = begin_borrow [[COPIED]]
// CHECK: [[COPIED_2:%.*]] = copy_value [[BORROWED_COPIED]]
// CHECK: [[THUNK:%.*]] = function_ref @_T0IyB_Ix_TR
// CHECK: [[FUNC:%.*]] = partial_apply [[THUNK]]([[COPIED_2]])
// CHECK: end_borrow [[BORROWED_COPIED]] from [[COPIED]]
// CHECK: destroy_value [[COPIED]]
// CHECK: destroy_value [[ARG]]
// CHECK: return [[FUNC]]
func blockToFunc(_ x: @escaping @convention(block) () -> ()) -> () -> () {
return x
}
// ==== Representation change + function type conversion
// CHECK-LABEL: sil hidden @_T024function_conversion_objc22blockToFuncExistentialypycSiyXBF : $@convention(thin) (@owned @convention(block) () -> Int) -> @owned @callee_owned () -> @out Any
// CHECK: function_ref @_T0SiIyBd_SiIxd_TR
// CHECK: partial_apply
// CHECK: function_ref @_T0SiIxd_ypIxr_TR
// CHECK: partial_apply
// CHECK: return
func blockToFuncExistential(_ x: @escaping @convention(block) () -> Int) -> () -> Any {
return x
}
// CHECK-LABEL: sil shared [transparent] [reabstraction_thunk] @_T0SiIyBd_SiIxd_TR : $@convention(thin) (@owned @convention(block) () -> Int) -> Int
// CHECK-LABEL: sil shared [transparent] [reabstraction_thunk] @_T0SiIxd_ypIxr_TR : $@convention(thin) (@owned @callee_owned () -> Int) -> @out Any
// C function pointer conversions
class A : NSObject {}
class B : A {}
// CHECK-LABEL: sil hidden @_T024function_conversion_objc18cFuncPtrConversionyAA1BCXCyAA1ACXCF
func cFuncPtrConversion(_ x: @escaping @convention(c) (A) -> ()) -> @convention(c) (B) -> () {
// CHECK: convert_function %0 : $@convention(c) (A) -> () to $@convention(c) (B) -> ()
// CHECK: return
return x
}
func cFuncPtr(_ a: A) {}
// CHECK-LABEL: sil hidden @_T024function_conversion_objc19cFuncDeclConversionyAA1BCXCyF
func cFuncDeclConversion() -> @convention(c) (B) -> () {
// CHECK: function_ref @_T024function_conversion_objc8cFuncPtryAA1ACFTo : $@convention(c) (A) -> ()
// CHECK: convert_function %0 : $@convention(c) (A) -> () to $@convention(c) (B) -> ()
// CHECK: return
return cFuncPtr
}
func cFuncPtrConversionUnsupported(_ x: @escaping @convention(c) (@convention(block) () -> ()) -> ())
-> @convention(c) (@convention(c) () -> ()) -> () {
return x // expected-error{{C function pointer signature '@convention(c) (@convention(block) () -> ()) -> ()' is not compatible with expected type '@convention(c) (@convention(c) () -> ()) -> ()'}}
}
| apache-2.0 | 88de7fa72a6cf471aecdce711b0b7e32 | 51.282051 | 269 | 0.653588 | 3.467687 | false | false | false | false |
sviatoslav/EndpointProcedure | Examples/Using DefaultConfigurationProvider and HTTPRequestDataBuidlerProvider.playground/Sources/Errors.swift | 2 | 5028 | //
// ProcedureKit
//
// Copyright © 2016 ProcedureKit. All rights reserved.
//
/// A type which has an associated error type
public protocol AssociatedErrorProtocol {
/// The type of associated error
associatedtype AssociatedError: Error
}
public protocol ProcedureKitComponent {
var name: String { get }
}
public struct ProcedureKitError: Error, Equatable, CustomStringConvertible {
public static func == (lhs: ProcedureKitError, rhs: ProcedureKitError) -> Bool {
return lhs.context == rhs.context
}
public enum CapabilityError: Error {
case unavailable, unauthorized
}
public enum Context: Equatable {
public static func == (lhs: Context, rhs: Context) -> Bool {
switch (lhs, rhs) {
case let (.capability(lhs), .capability(rhs)):
return lhs == rhs
case let (.component(lhs), .component(rhs)):
return lhs.name == rhs.name
case let (.programmingError(lhs), .programmingError(rhs)):
return lhs == rhs
case let (.timedOut(lhs), .timedOut(rhs)):
return lhs == rhs
case (.conditionFailed, .conditionFailed),
(.dependenciesFailed, .dependenciesFailed),
(.dependenciesCancelled, .dependenciesCancelled),
(.dependencyFinishedWithErrors, .dependencyFinishedWithErrors),
(.dependencyCancelledWithErrors, .dependencyCancelledWithErrors),
(.noQueue, .noQueue),
(.parentCancelledWithErrors, .parentCancelledWithErrors),
(.requirementNotSatisfied, .requirementNotSatisfied),
(.unknown, .unknown):
return true
default:
return false
}
}
case capability(CapabilityError)
case component(ProcedureKitComponent)
case conditionFailed
case dependenciesFailed
case dependenciesCancelled
case dependencyFinishedWithErrors
case dependencyCancelledWithErrors
case noQueue
case parentCancelledWithErrors
case programmingError(String)
case requirementNotSatisfied
case timedOut(Delay)
case unknown
}
public static func capabilityUnavailable() -> ProcedureKitError {
return ProcedureKitError(context: .capability(.unavailable), errors: [])
}
public static func capabilityUnauthorized() -> ProcedureKitError {
return ProcedureKitError(context: .capability(.unauthorized), errors: [])
}
public static func component(_ component: ProcedureKitComponent, error: Error?) -> ProcedureKitError {
return ProcedureKitError(context: .component(component), errors: error.map { [$0] } ?? [])
}
public static func conditionFailed(withErrors errors: [Error] = []) -> ProcedureKitError {
return ProcedureKitError(context: .conditionFailed, errors: errors)
}
public static func dependenciesFailed() -> ProcedureKitError {
return ProcedureKitError(context: .dependenciesFailed, errors: [])
}
public static func dependenciesCancelled() -> ProcedureKitError {
return ProcedureKitError(context: .dependenciesCancelled, errors: [])
}
public static func dependency(finishedWithErrors errors: [Error]) -> ProcedureKitError {
return ProcedureKitError(context: .dependencyFinishedWithErrors, errors: errors)
}
public static func dependency(cancelledWithErrors errors: [Error]) -> ProcedureKitError {
return ProcedureKitError(context: .dependencyCancelledWithErrors, errors: errors)
}
public static func noQueue() -> ProcedureKitError {
return ProcedureKitError(context: .noQueue, errors: [])
}
public static func parent(cancelledWithErrors errors: [Error]) -> ProcedureKitError {
return ProcedureKitError(context: .parentCancelledWithErrors, errors: errors)
}
public static func programmingError(reason: String) -> ProcedureKitError {
return ProcedureKitError(context: .programmingError(reason), errors: [])
}
public static func requirementNotSatisfied() -> ProcedureKitError {
return ProcedureKitError(context: .requirementNotSatisfied, errors: [])
}
public static func timedOut(with delay: Delay) -> ProcedureKitError {
return ProcedureKitError(context: .timedOut(delay), errors: [])
}
public static let unknown = ProcedureKitError(context: .unknown, errors: [])
public let context: Context
public let errors: [Error]
// Swift 3.0 Leak Fix:
//
// As of Swift 3.0.1 & Xcode 8.1, ProcedureKitError leaks memory when converted to a string
// unless it conforms to CustomStringConvertible and provides its own `description`
// implementation.
//
// Symptoms: Malloc 48 byte leaks
//
public var description: String {
return "ProcedureKitError(context: \(context), errors: \(errors))"
}
}
| mit | 91b3c78b1059fa46ac0ad45d3128b767 | 35.427536 | 106 | 0.662423 | 5.604236 | false | false | false | false |
brave/browser-ios | brave/src/sync/SyncResponse.swift | 2 | 2262 | /* This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
import Shared
import SwiftyJSON
/*
* Due to sync's 'callbacks' running through the same function, parameters are reused
* for ever single function call, resulting in a complex web of peculiar naming.
*
* Direct key mappings are using to pluck the variable names from the data, and an attempt
* to make them more native feeling (e.g. descriptive names) has been made. In some cases
* variable names are still generic due to the extreme usage of them (i.e. no nice way to make non-generic)
*
* At some point a switch to fullblown generic names may need necessary, but this hybrid approach seemed best
* at the time of building it
*/
typealias SyncDefaultResponseType = SyncRecord
final class SyncResponse {
// MARK: Declaration for string constants to be used to decode and also serialize.
fileprivate struct SerializationKeys {
static let arg2 = "arg2"
static let message = "message"
static let arg1 = "arg1"
static let arg3 = "arg3"
static let arg4 = "arg4" // isTruncated
}
// MARK: Properties
// TODO: rename this property
var rootElements: JSON? // arg2
var message: String?
var arg1: String?
var lastFetchedTimestamp: Int? // arg3
var isTruncated: Bool? // arg4
/// Initiates the instance based on the object.
///
/// - parameter object: The object of either Dictionary or Array kind that was passed.
/// - returns: An initialized instance of the class.
convenience init(object: String) {
self.init(json: JSON(parseJSON: object))
}
/// Initiates the instance based on the JSON that was passed.
///
/// - parameter json: JSON object from SwiftyJSON.
required init(json: JSON?) {
rootElements = json?[SerializationKeys.arg2]
message = json?[SerializationKeys.message].string
arg1 = json?[SerializationKeys.arg1].string
lastFetchedTimestamp = json?[SerializationKeys.arg3].int
isTruncated = json?[SerializationKeys.arg4].bool
}
}
| mpl-2.0 | 119ee36bc4539a01e74f312f7c7e171e | 38 | 198 | 0.687445 | 4.325048 | false | false | false | false |
DylanModesitt/Verb | Verb/Verb/ServerRequests.swift | 1 | 22046 | //
// ServerRequests.swift
// Verb
//
// Created by dcm on 12/8/15.
// Copyright © 2015 Verb. All rights reserved.
//
import Foundation
import Parse
/*
@brief General server requests for contacting the PARSE RestAPI
*/
class ServerRequests {
/*
@brief Save relational data
@discussion ServerRequests().saveRelationalData("parent","fff1222", "children", childObject)
@param parentClassName The parent class where the children belong to
@param parentObjectID The objectId of the parent
@param relationalKey The key the relation is under
@param relationalData The data to be added to the relation
*/
func saveRelationalData(parentClass: String, parentObejctId: String, relationalKey: String, relationalData: PFObject) {
let query = PFQuery(className: parentClass)
query.getObjectInBackgroundWithId(parentObejctId) { (object: PFObject?, error: NSError?) -> Void in
let relation = object?.relationForKey(relationalKey)
relation?.addObject(relationalData)
do {
try object?.save()
} catch {
print(error)
object?.saveEventually()
}
}
}
// same as above but the data is removed
func removeRelationalData(parentClass: String, parentObejctId: String, relationalKey: String, relationalData: PFObject) {
let query = PFQuery(className: parentClass)
query.getObjectInBackgroundWithId(parentObejctId) { (object: PFObject?, error: NSError?) -> Void in
let relation = object?.relationForKey(relationalKey)
relation?.removeObject(relationalData)
do {
try object?.save()
} catch {
print(error)
object?.saveEventually()
}
}
}
/*
@brief get relational data
@discussion ServerRequests().getRelationalData("parent","fff1222", "children")
@param parentClassName The parent class where the children belong to
@param parentObjectID The objectId of the parent
@param relationalKey The key the relation is under
@return The relational data under the relation key
*/
func getRelationalData(parentClass: String, parentObejctId: String, relationalKey: String, completionHandler : (relationalData : [PFObject])-> Void) throws {
let query = PFQuery(className: parentClass)
query.getObjectInBackgroundWithId(parentObejctId) { (object: PFObject?, error: NSError?) -> Void in
let relation = object?.relationForKey(relationalKey)
relation?.query().findObjectsInBackgroundWithBlock({ (relationalData: [PFObject]?, error: NSError?) -> Void in
completionHandler(relationalData: relationalData!)
})
}
}
/*
@brief get relational data
@discussion ServerRequests().getRelationalData("parent", "fff1222", "children", "key")
@param parentClassName The parent class where the children belong to
@param parentObjectID The objectId of the parent
@param relationalKey The key the relation is under
@param keyDesired The key that houses the desired values from the related objects
@return The values from the related data that match the relationalKey
*/
func getValuesFromRelationalData(parentClass: String, parentObejctId: String, relationalKey: String, keyDesired: String, completionHandler : (relationalData : [AnyObject])-> Void) throws {
let query = PFQuery(className: parentClass)
query.getObjectInBackgroundWithId(parentObejctId) { (object: PFObject?, error: NSError?) -> Void in
let relation = object?.relationForKey(relationalKey)
relation?.query().findObjectsInBackgroundWithBlock({ (relationalData: [PFObject]?, error: NSError?) -> Void in
var values: [AnyObject] = []
for object in relationalData! {
values.append(object[keyDesired])
}
completionHandler(relationalData: values)
})
}
}
// same as the above pair of functions, but supporting a query limit
func getRelationalDataInBatches(parentClass: String, parentObejctId: String, relationalKey: String, batchesToSkip: Int, querySize: Int, completionHandler : (relationalData : [PFObject])-> Void) throws {
let query = PFQuery(className: parentClass)
query.getObjectInBackgroundWithId(parentObejctId) { (object: PFObject?, error: NSError?) -> Void in
let relation = object?.relationForKey(relationalKey).query()
relation!.limit = querySize
relation!.skip = batchesToSkip*querySize
relation?.findObjectsInBackgroundWithBlock({ (relationalData: [PFObject]?, error: NSError?) -> Void in
completionHandler(relationalData: relationalData!)
})
}
}
func getValuesFromRelationalDataInBatches(parentClass: String, parentObejctId: String, relationalKey: String, keyDesired: String, batchesToSkip: Int, querySize: Int, completionHandler : (relationalData : [AnyObject])-> Void) throws {
let query = PFQuery(className: parentClass)
query.limit = querySize
query.skip = batchesToSkip*querySize
query.getObjectInBackgroundWithId(parentObejctId) { (object: PFObject?, error: NSError?) -> Void in
let relation = object?.relationForKey(relationalKey).query()
relation!.limit = querySize
relation!.skip = batchesToSkip*querySize
relation?.findObjectsInBackgroundWithBlock({ (relationalData: [PFObject]?, error: NSError?) -> Void in
var values: [AnyObject] = []
for object in relationalData! {
values.append(object[keyDesired])
}
print(values)
completionHandler(relationalData: values)
})
}
}
// same as the initial pair of functions, but with a predicate
func getRelationalDataWithPredicate(parentClass: String, parentObejctId: String, relationalKey: String, keyForPredicate: String, predicate: String, completionHandler : (relationalData : [PFObject])-> Void) throws {
let query = PFQuery(className: parentClass)
query.whereKey(keyForPredicate, containsString: predicate)
query.getObjectInBackgroundWithId(parentObejctId) { (object: PFObject?, error: NSError?) -> Void in
let relation = object?.relationForKey(relationalKey)
relation?.query().findObjectsInBackgroundWithBlock({ (relationalData: [PFObject]?, error: NSError?) -> Void in
completionHandler(relationalData: relationalData!)
})
}
}
func getValuesFromRelationalDataWithPredicate(parentClass: String, parentObejctId: String, relationalKey: String, keyDesired: String, keyForPredicate: String, predicate: String, completionHandler : (relationalData : [AnyObject])-> Void) throws {
let query = PFQuery(className: parentClass)
query.whereKey(keyForPredicate, containsString: predicate)
query.getObjectInBackgroundWithId(parentObejctId) { (object: PFObject?, error: NSError?) -> Void in
let relation = object?.relationForKey(relationalKey)
relation?.query().findObjectsInBackgroundWithBlock({ (relationalData: [PFObject]?, error: NSError?) -> Void in
var values: [AnyObject] = []
for object in relationalData! {
values.append(object[keyDesired])
}
print(values)
completionHandler(relationalData: values)
})
}
}
// same as the initial pair of functions, but using a query size and containing relational data
func getRelationalDataWithPredicateInBatches(parentClass: String, parentObejctId: String, relationalKey: String, keyForPredicate: String, predicate: String, batchesToSkip: Int, querySize: Int, completionHandler : (relationalData : [PFObject])-> Void) throws {
let query = PFQuery(className: parentClass)
query.whereKey(keyForPredicate, containsString: predicate)
query.getObjectInBackgroundWithId(parentObejctId) { (object: PFObject?, error: NSError?) -> Void in
let relation = object?.relationForKey(relationalKey).query()
relation!.limit = querySize
relation!.skip = batchesToSkip*querySize
relation?.findObjectsInBackgroundWithBlock({ (relationalData: [PFObject]?, error: NSError?) -> Void in
completionHandler(relationalData: relationalData!)
})
}
}
func getValuesFromRelationalDataWithPredicateInBatches(parentClass: String, parentObejctId: String, relationalKey: String, keyDesired: String, keyForPredicate: String, predicate: String, batchesToSkip: Int, querySize: Int, completionHandler : (relationalData : [AnyObject])-> Void) throws {
let query = PFQuery(className: parentClass)
query.whereKey(keyForPredicate, containsString: predicate)
query.getObjectInBackgroundWithId(parentObejctId) { (object: PFObject?, error: NSError?) -> Void in
let relation = object?.relationForKey(relationalKey)
relation!.query().limit = querySize
relation!.query().skip = batchesToSkip*querySize
relation?.query().findObjectsInBackgroundWithBlock({ (relationalData: [PFObject]?, error: NSError?) -> Void in
var values: [AnyObject] = []
for object in relationalData! {
values.append(object[keyDesired])
}
print(values)
completionHandler(relationalData: values)
})
}
}
/*
@brief get relational objectIds
@discussion ServerRequests().getObjectIdsFromRelationalData("parent","fff1222", "children")
@param parentClassName The parent class where the children belong to
@param parentObjectID The objectId of the parent
@param relationalKey The key the relation is under
@param keyDesired The key that houses the desired values from the related objects
@return The values from the related data that match the relationalKey
*/
func getObjectIdsFromRelationalData(parentClass: String, parentObejctId: String, relationalKey: String, completionHandler : (relationalData : [AnyObject])-> Void) throws {
let query = PFQuery(className: parentClass)
query.getObjectInBackgroundWithId(parentObejctId) { (object: PFObject?, error: NSError?) -> Void in
let relation = object?.relationForKey(relationalKey)
relation?.query().findObjectsInBackgroundWithBlock({ (relationalData: [PFObject]?, error: NSError?) -> Void in
var values: [AnyObject] = []
for object in relationalData! {
values.append(object.objectId!)
}
print(values)
completionHandler(relationalData: values)
})
}
}
/*
@brief Get the object ID of any object in any class given a value searched for
@discussion ServerRequests().getObjectID("class","name","desiredValue")
@param classNameGiven The class of which the object at hand belongs to
@param objectKey The key of which the objectValue being searched belongs to
@param objectValue The value which is to be searched for
*/
func getObjectID(classNameGiven: String, objectKey: String, objectValue: String, completionHandler : (objectID : String?)-> Void) throws {
var errorToThrow: ErrorType?
let query = PFQuery(className: classNameGiven)
query.whereKey(objectKey, equalTo: objectValue)
query.getFirstObjectInBackgroundWithBlock {
(object: PFObject?, error: NSError?) -> Void in
if object != nil {
completionHandler(objectID: object!.objectId)
} else if error != nil {
errorToThrow = error
completionHandler(objectID: nil)
} else {
errorToThrow = errors.failureToRetrieveObject
completionHandler(objectID: nil)
}
}
if let _ = errorToThrow {
throw errorToThrow!
}
}
/*
@brief Asyncronously retrieve a value
@discussion ServerRequests().getValue("class","fff11122","keyDesired")
@param classNameGiven The class of which the object at hand belongs to
@param objectKey The key of which the objectValue being searched belongs to
@param keyToRetreive The key of which the value is wanted
*/
func getValue(className: String, objectID: String, key: String, completionHandler : (value: AnyObject?)-> Void) throws {
var errorToThrow: ErrorType?
let query = PFQuery(className: className)
query.getObjectInBackgroundWithId(objectID) { (object: PFObject?, error: NSError?) -> Void in
if let _ = error {
errorToThrow = error
}
if let _ = object {
completionHandler(value: object![key])
}
}
if let _ = errorToThrow {
throw errorToThrow!
}
}
/*
@brief Asyncronously change a value
@discussion ServerRequests().getValue("class","fff11122","keyDesired")
@param classNameGiven The class of which the object at hand belongs to
@param objectKey The key of which the objectValue being searched belongs to
@param keyToRetreive The key of which the value is wanted
*/
func changeValue(className: String, objectID: String, key: String, newValue: String) throws {
var errorToThrow: ErrorType?
let query = PFQuery(className: className)
query.getObjectInBackgroundWithId(objectID) { (object: PFObject?, error: NSError?) -> Void in
if let _ = error {
errorToThrow = error
}
if let _ = object {
object![key] = newValue
object!.saveEventually()
}
}
if let _ = errorToThrow {
throw errorToThrow!
}
}
/*
@brief Asyncronously change a value
@discussion ServerRequests().updateArray("class","fff11122","keyDesired", "valueToAdd")
@param className The class of which the object at hand belongs to
@param objectID The objectId that the value is to be updated in
@param objectKey The key of which the objectValue being updated belongs to
@param valueToUpdate The value to add the the array
*/
func updateArray(className: String, objectID: String, key: String, valueToUpdate: AnyObject) throws {
var errorToThrow: ErrorType?
let query = PFQuery(className: className)
query.getObjectInBackgroundWithId(objectID) { (object: PFObject?, error: NSError?) -> Void in
if let _ = error {
errorToThrow = error
}
if let _ = object {
object!.addObject(valueToUpdate, forKey: key)
object!.saveEventually()
}
}
if let _ = errorToThrow {
throw errorToThrow!
}
}
// @brief Same as the above function, but takes an array of values to update
func updateArray(className: String, objectID: String, key: String, valuesToUpdate: [AnyObject]) throws {
var errorToThrow: ErrorType?
let query = PFQuery(className: className)
query.getObjectInBackgroundWithId(objectID) { (object: PFObject?, error: NSError?) -> Void in
if let _ = error {
errorToThrow = error
}
if let _ = object {
object!.addUniqueObjectsFromArray(valuesToUpdate, forKey: key)
object!.saveEventually()
}
}
if let _ = errorToThrow {
throw errorToThrow!
}
}
/*
@brief increment a key
@discussion ServerRequests().incrementKey("class","fff11122","incrementThis")
@param classNameGiven The class of which the object at hand belongs to
@param objectKey The key of which the objectValue being searched belongs to
@param keyToIncrement The value which you want to increment
*/
func changeKeyByOne(className: String, objectID: String, keyToIncrement: String, increment: Bool) throws {
var errorToThrow: ErrorType?
let query = PFQuery(className: className)
query.getObjectInBackgroundWithId(objectID) { (object: PFObject?, error: NSError?) -> Void in
if let _ = object {
if (increment) {
object?.incrementKey(keyToIncrement)
} else {
object?[keyToIncrement] = object?[keyToIncrement] as! Int - 1
}
object?.saveEventually()
} else {
errorToThrow = error;
}
}
if let _ = errorToThrow {
throw errorToThrow!
}
}
//MARK - DEPRICATED
/*
@brief Asyncronously retrieve an array of values from an array of subclassed PFObjects
@discussion ServerRequests().getValueFromArrayOfSubclassedObjects("parent","child", "fff1222", "keyThatHousesChild"), "keyWantedFromChildren"
@param parentClassName The parent class where the children belong to
@param subClassName The name of the class that is subclassed to the parent
@param parentObjectID The objectId of the parent
@param keyForObjectsINParentClass The key the array of subclassed objects is housed in
@param keyDesiredFromSubclassedObject The key that is desired from the children
*/
func getValueFromArrayOfSubclassedObjects(parentClassName: String, subClassName: String, parentObjectID: String, keyForObjectsInParentClass: String, keyDesiredFromSubclassedObject: String, completionHandler : (values: [AnyObject]?)-> Void) throws {
var errorToThrow: ErrorType?
var doBreak = false
let query = PFQuery(className: parentClassName)
query.getObjectInBackgroundWithId(parentObjectID) { (object: PFObject?, error: NSError?) -> Void in
if let _ = object {
let desiredValuesAsPointers = object?.valueForKey(keyForObjectsInParentClass)
desiredValuesAsPointers!.query().findObjectsInBackgroundWithBlock({ (objects: [PFObject]?, error: NSError?) -> Void in
print(objects)
var values: [AnyObject] = []
for object in objects! {
do {
try self.getValue(subClassName, objectID: object.objectId!, key: keyDesiredFromSubclassedObject, completionHandler: { (value) -> Void in
if let _ = value {
values.append(value!)
if objects!.last == object {
completionHandler(values: values)
}
} else {
values = []
doBreak = true
errorToThrow = errors.failureToRetrieveObject
}
})
} catch {
values = []
doBreak = true
errorToThrow = error
}
if doBreak {
break
}
}
})
}
}
if let _ = errorToThrow {
throw errorToThrow!
}
}
/*
@brief Asyncronously retrieve an array of objectIds from an array of subclassed PFObjects
@discussion ServerRequests().getObjectIdsFromArrayOfSubclassedObjects("parent","child", "fff1222", "keyThatHousesChild"), "keyWantedFromChildren"
@param parentClassName The parent class where the children belong to
@param subClassName The name of the class that is subclassed to the parent
@param parentObjectID The objectId of the parent
@param keyDesiredFromSubclassedObject The key that is desired from the children
*/
func getObjectIdsFromArrayOfSubclassedObjects(parentClassName: String, subClassName: String, parentObjectID: String, keyForObjectsInParentClass: String, completionHandler : (values: [String]?)-> Void) throws {
var errorToThrow: ErrorType?
var doBreak = false
let query = PFQuery(className: parentClassName)
query.getObjectInBackgroundWithId(parentObjectID) { (object: PFObject?, error: NSError?) -> Void in
if let _ = object {
let objects = object![keyForObjectsInParentClass] as! [PFObject]
var values: [String] = []
for object in objects {
if let value = object.objectId {
values.append(value)
if objects.last == object {
completionHandler(values: values)
}
} else {
values = []
doBreak = true
errorToThrow = errors.failureToRetrieveObject
}
if doBreak {
break
}
}
}
}
if let _ = errorToThrow {
throw errorToThrow!
}
}
} | apache-2.0 | 945e8d1cada004ac76ae352fef59eb92 | 42.483235 | 294 | 0.611386 | 5.734912 | false | false | false | false |
SwifterSwift/SwifterSwift | Sources/SwifterSwift/UIKit/UIViewControllerExtensions.swift | 1 | 6362 | // UIViewControllerExtensions.swift - Copyright 2020 SwifterSwift
#if canImport(UIKit) && !os(watchOS)
import UIKit
// MARK: - Properties
public extension UIViewController {
/// SwifterSwift: Check if ViewController is onscreen and not hidden.
var isVisible: Bool {
// http://stackoverflow.com/questions/2777438/how-to-tell-if-uiviewcontrollers-view-is-visible
return isViewLoaded && view.window != nil
}
}
// MARK: - Methods
public extension UIViewController {
/// SwifterSwift: Instantiate UIViewController from storyboard.
///
/// - Parameters:
/// - storyboard: Name of the storyboard where the UIViewController is located.
/// - bundle: Bundle in which storyboard is located.
/// - identifier: UIViewController's storyboard identifier.
/// - Returns: Custom UIViewController instantiated from storyboard.
class func instantiate(from storyboard: String = "Main", bundle: Bundle? = nil, identifier: String? = nil) -> Self {
let viewControllerIdentifier = identifier ?? String(describing: self)
let storyboard = UIStoryboard(name: storyboard, bundle: bundle)
guard let viewController = storyboard
.instantiateViewController(withIdentifier: viewControllerIdentifier) as? Self else {
preconditionFailure(
"Unable to instantiate view controller with identifier \(viewControllerIdentifier) as type \(type(of: self))")
}
return viewController
}
/// SwifterSwift: Assign as listener to notification.
///
/// - Parameters:
/// - name: notification name.
/// - selector: selector to run with notified.
func addNotificationObserver(name: Notification.Name, selector: Selector) {
NotificationCenter.default.addObserver(self, selector: selector, name: name, object: nil)
}
/// SwifterSwift: Unassign as listener to notification.
///
/// - Parameter name: notification name.
func removeNotificationObserver(name: Notification.Name) {
NotificationCenter.default.removeObserver(self, name: name, object: nil)
}
/// SwifterSwift: Unassign as listener from all notifications.
func removeNotificationsObserver() {
NotificationCenter.default.removeObserver(self)
}
/// SwifterSwift: Helper method to display an alert on any UIViewController subclass. Uses UIAlertController to show an alert.
///
/// - Parameters:
/// - title: title of the alert.
/// - message: message/body of the alert.
/// - buttonTitles: (Optional)list of button titles for the alert. Default button i.e "OK" will be shown if this parameter is nil.
/// - highlightedButtonIndex: (Optional) index of the button from buttonTitles that should be highlighted. If this parameter is nil no button will be highlighted.
/// - completion: (Optional) completion block to be invoked when any one of the buttons is tapped. It passes the index of the tapped button as an argument.
/// - Returns: UIAlertController object (discardable).
@discardableResult
func showAlert(
title: String?,
message: String?,
buttonTitles: [String]? = nil,
highlightedButtonIndex: Int? = nil,
completion: ((Int) -> Void)? = nil) -> UIAlertController {
let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert)
var allButtons = buttonTitles ?? [String]()
if allButtons.count == 0 {
allButtons.append("OK")
}
for index in 0..<allButtons.count {
let buttonTitle = allButtons[index]
let action = UIAlertAction(title: buttonTitle, style: .default, handler: { _ in
completion?(index)
})
alertController.addAction(action)
// Check which button to highlight
if let highlightedButtonIndex = highlightedButtonIndex, index == highlightedButtonIndex {
alertController.preferredAction = action
}
}
present(alertController, animated: true, completion: nil)
return alertController
}
/// SwifterSwift: Helper method to add a UIViewController as a childViewController.
///
/// - Parameters:
/// - child: the view controller to add as a child.
/// - containerView: the containerView for the child viewController's root view.
func addChildViewController(_ child: UIViewController, toContainerView containerView: UIView) {
addChild(child)
containerView.addSubview(child.view)
child.didMove(toParent: self)
}
/// SwifterSwift: Helper method to remove a UIViewController from its parent.
func removeViewAndControllerFromParentViewController() {
guard parent != nil else { return }
willMove(toParent: nil)
removeFromParent()
view.removeFromSuperview()
}
#if os(iOS)
/// SwifterSwift: Helper method to present a UIViewController as a popover.
///
/// - Parameters:
/// - popoverContent: the view controller to add as a popover.
/// - sourcePoint: the point in which to anchor the popover.
/// - size: the size of the popover. Default uses the popover preferredContentSize.
/// - delegate: the popover's presentationController delegate. Default is nil.
/// - animated: Pass true to animate the presentation; otherwise, pass false.
/// - completion: The block to execute after the presentation finishes. Default is nil.
func presentPopover(
_ popoverContent: UIViewController,
sourcePoint: CGPoint,
size: CGSize? = nil,
delegate: UIPopoverPresentationControllerDelegate? = nil,
animated: Bool = true,
completion: (() -> Void)? = nil) {
popoverContent.modalPresentationStyle = .popover
if let size = size {
popoverContent.preferredContentSize = size
}
if let popoverPresentationVC = popoverContent.popoverPresentationController {
popoverPresentationVC.sourceView = view
popoverPresentationVC.sourceRect = CGRect(origin: sourcePoint, size: .zero)
popoverPresentationVC.delegate = delegate
}
present(popoverContent, animated: animated, completion: completion)
}
#endif
}
#endif
| mit | 4129b7390551e876033a9f4f68442e46 | 41.697987 | 168 | 0.668815 | 5.201962 | false | false | false | false |
jsslai/Action | Carthage/Checkouts/RxSwift/RxExample/RxDataSources/DataSources/TableViewSectionedDataSource.swift | 3 | 10420 | //
// TableViewSectionedDataSource.swift
// RxDataSources
//
// Created by Krunoslav Zaher on 6/15/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
import UIKit
#if !RX_NO_MODULE
import RxCocoa
#endif
// objc monkey business
public class _TableViewSectionedDataSource
: NSObject
, UITableViewDataSource {
func _numberOfSectionsInTableView(_ tableView: UITableView) -> Int {
return 1
}
public func numberOfSections(in tableView: UITableView) -> Int {
return _numberOfSectionsInTableView(tableView)
}
func _rx_tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 0
}
public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return _rx_tableView(tableView, numberOfRowsInSection: section)
}
func _rx_tableView(_ tableView: UITableView, cellForRowAtIndexPath indexPath: IndexPath) -> UITableViewCell {
return (nil as UITableViewCell?)!
}
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
return _rx_tableView(tableView, cellForRowAtIndexPath: indexPath)
}
func _rx_tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return nil
}
public func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return _rx_tableView(tableView, titleForHeaderInSection: section)
}
func _rx_tableView(_ tableView: UITableView, titleForFooterInSection section: Int) -> String? {
return nil
}
public func tableView(_ tableView: UITableView, titleForFooterInSection section: Int) -> String? {
return _rx_tableView(tableView, titleForFooterInSection: section)
}
func _rx_tableView(_ tableView: UITableView, canEditRowAtIndexPath indexPath: IndexPath) -> Bool {
return false
}
public func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
return _rx_tableView(tableView, canEditRowAtIndexPath: indexPath)
}
func _rx_tableView(_ tableView: UITableView, canMoveRowAtIndexPath indexPath: IndexPath) -> Bool {
return false
}
public func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
return _rx_tableView(tableView, canMoveRowAtIndexPath: indexPath)
}
#if os(iOS)
func _sectionIndexTitlesForTableView(_ tableView: UITableView) -> [String]? {
return nil
}
public func sectionIndexTitles(for tableView: UITableView) -> [String]? {
return _sectionIndexTitlesForTableView(tableView)
}
func _rx_tableView(_ tableView: UITableView, sectionForSectionIndexTitle title: String, atIndex index: Int) -> Int {
return 0
}
public func tableView(_ tableView: UITableView, sectionForSectionIndexTitle title: String, at index: Int) -> Int {
return _rx_tableView(tableView, sectionForSectionIndexTitle: title, atIndex: index)
}
#endif
func _rx_tableView(_ tableView: UITableView, moveRowAtIndexPath sourceIndexPath: IndexPath, toIndexPath destinationIndexPath: IndexPath) {
}
public func tableView(_ tableView: UITableView, moveRowAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) {
_rx_tableView(tableView, moveRowAtIndexPath: sourceIndexPath, toIndexPath: destinationIndexPath)
}
}
public class RxTableViewSectionedDataSource<S: SectionModelType>
: _TableViewSectionedDataSource
, SectionedViewDataSourceType {
public typealias I = S.Item
public typealias Section = S
public typealias CellFactory = (RxTableViewSectionedDataSource<S>, UITableView, IndexPath, I) -> UITableViewCell
#if DEBUG
// If data source has already been bound, then mutating it
// afterwards isn't something desired.
// This simulates immutability after binding
var _dataSourceBound: Bool = false
private func ensureNotMutatedAfterBinding() {
assert(!_dataSourceBound, "Data source is already bound. Please write this line before binding call (`bindTo`, `drive`). Data source must first be completely configured, and then bound after that, otherwise there could be runtime bugs, glitches, or partial malfunctions.")
}
#endif
// This structure exists because model can be mutable
// In that case current state value should be preserved.
// The state that needs to be preserved is ordering of items in section
// and their relationship with section.
// If particular item is mutable, that is irrelevant for this logic to function
// properly.
public typealias SectionModelSnapshot = SectionModel<S, I>
private var _sectionModels: [SectionModelSnapshot] = []
public var sectionModels: [S] {
return _sectionModels.map { Section(original: $0.model, items: $0.items) }
}
public func sectionAtIndex(_ section: Int) -> S {
let sectionModel = _sectionModels[section]
return Section(original: sectionModel.model, items: sectionModel.items)
}
public subscript(indexPath: IndexPath) -> I {
get {
return self._sectionModels[indexPath.section].items[indexPath.item]
}
set(item) {
var section = self._sectionModels[indexPath.section]
section.items[indexPath.item] = item
self._sectionModels[indexPath.section] = section
}
}
public func model(_ indexPath: IndexPath) throws -> Any {
return self[indexPath]
}
public func setSections(_ sections: [S]) {
self._sectionModels = sections.map { SectionModelSnapshot(model: $0, items: $0.items) }
}
public var configureCell: CellFactory! = nil {
didSet {
#if DEBUG
ensureNotMutatedAfterBinding()
#endif
}
}
public var titleForHeaderInSection: ((RxTableViewSectionedDataSource<S>, Int) -> String?)? {
didSet {
#if DEBUG
ensureNotMutatedAfterBinding()
#endif
}
}
public var titleForFooterInSection: ((RxTableViewSectionedDataSource<S>, Int) -> String?)? {
didSet {
#if DEBUG
ensureNotMutatedAfterBinding()
#endif
}
}
public var canEditRowAtIndexPath: ((RxTableViewSectionedDataSource<S>, IndexPath) -> Bool)? {
didSet {
#if DEBUG
ensureNotMutatedAfterBinding()
#endif
}
}
public var canMoveRowAtIndexPath: ((RxTableViewSectionedDataSource<S>, IndexPath) -> Bool)? {
didSet {
#if DEBUG
ensureNotMutatedAfterBinding()
#endif
}
}
public var rowAnimation: UITableViewRowAnimation = .automatic
#if os(iOS)
public var sectionIndexTitles: ((RxTableViewSectionedDataSource<S>) -> [String]?)? {
didSet {
#if DEBUG
ensureNotMutatedAfterBinding()
#endif
}
}
public var sectionForSectionIndexTitle:((RxTableViewSectionedDataSource<S>, _ title: String, _ index: Int) -> Int)? {
didSet {
#if DEBUG
ensureNotMutatedAfterBinding()
#endif
}
}
#endif
public override init() {
super.init()
self.configureCell = { [weak self] _ in
if let strongSelf = self {
precondition(false, "There is a minor problem. `cellFactory` property on \(strongSelf) was not set. Please set it manually, or use one of the `rx_bindTo` methods.")
}
return (nil as UITableViewCell!)!
}
}
// UITableViewDataSource
override func _numberOfSectionsInTableView(_ tableView: UITableView) -> Int {
return _sectionModels.count
}
override func _rx_tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return _sectionModels[section].items.count
}
override func _rx_tableView(_ tableView: UITableView, cellForRowAtIndexPath indexPath: IndexPath) -> UITableViewCell {
precondition(indexPath.item < _sectionModels[indexPath.section].items.count)
return configureCell(self, tableView, indexPath, self[indexPath])
}
override func _rx_tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return titleForHeaderInSection?(self, section)
}
override func _rx_tableView(_ tableView: UITableView, titleForFooterInSection section: Int) -> String? {
return titleForFooterInSection?(self, section)
}
override func _rx_tableView(_ tableView: UITableView, canEditRowAtIndexPath indexPath: IndexPath) -> Bool {
guard let canEditRow = canEditRowAtIndexPath?(self, indexPath) else {
return super._rx_tableView(tableView, canEditRowAtIndexPath: indexPath)
}
return canEditRow
}
override func _rx_tableView(_ tableView: UITableView, canMoveRowAtIndexPath indexPath: IndexPath) -> Bool {
guard let canMoveRow = canMoveRowAtIndexPath?(self, indexPath) else {
return super._rx_tableView(tableView, canMoveRowAtIndexPath: indexPath)
}
return canMoveRow
}
override func _rx_tableView(_ tableView: UITableView, moveRowAtIndexPath sourceIndexPath: IndexPath, toIndexPath destinationIndexPath: IndexPath) {
self._sectionModels.moveFromSourceIndexPath(sourceIndexPath, destinationIndexPath: destinationIndexPath)
}
#if os(iOS)
override func _sectionIndexTitlesForTableView(_ tableView: UITableView) -> [String]? {
guard let titles = sectionIndexTitles?(self) else {
return super._sectionIndexTitlesForTableView(tableView)
}
return titles
}
override func _rx_tableView(_ tableView: UITableView, sectionForSectionIndexTitle title: String, atIndex index: Int) -> Int {
guard let section = sectionForSectionIndexTitle?(self, title, index) else {
return super._rx_tableView(tableView, sectionForSectionIndexTitle: title, atIndex: index)
}
return section
}
#endif
}
| mit | 07e446700702ba163690f7e1a9feabff | 34.927586 | 280 | 0.663691 | 5.506871 | false | false | false | false |
ben-ng/swift | stdlib/public/SDK/Intents/INSetProfileInCarIntent.swift | 1 | 1164 | //===----------------------------------------------------------------------===//
//
// 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 https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
@_exported import Intents
import Foundation
#if os(iOS)
@available(iOS 10.0, *)
extension INSetProfileInCarIntent {
@nonobjc
public convenience init(
profileNumber: Int? = nil,
profileLabel: String? = nil,
defaultProfile: Int? = nil
) {
self.init(
__profileNumber: profileNumber.map { NSNumber(value: $0) },
profileLabel: profileLabel,
defaultProfile: defaultProfile.map { NSNumber(value: $0) })
}
@nonobjc
public final var profileNumber: Int? {
return __profileNumber?.intValue
}
@nonobjc
public final var defaultProfile: Int? {
return __defaultProfile?.intValue
}
}
#endif
| apache-2.0 | 339740573c30192ac7f493ddfa58669b | 27.390244 | 80 | 0.601375 | 4.619048 | false | false | false | false |
cuzv/EasySwift | Sources/FlowLayout/StretchyHeaderFlowLayout.swift | 1 | 4034 | //
// StretchyHeaderFlowLayout.swift
// EasySwift
//
// Created by Shaw on 10/27/17.
// Copyright © 2017 Shaw. All rights reserved.
//
import UIKit
open class StretchyHeaderFlowLayout: UICollectionViewFlowLayout {
private(set) open var topDockHeight: CGFloat = 0
private(set) open var coefficient: CGFloat = 2.4
open var scrollUpAction: ((_ progress: CGFloat) -> Void)?
open var scrollDownAction: ((_ translation: CGFloat) -> Void)?
private var headerAttributes: UICollectionViewLayoutAttributes?
public convenience init(
topDockHeight: CGFloat,
coefficient: CGFloat = 2.4,
scrollUpAction: ((_ progress: CGFloat) -> Void)? = nil,
scrollDownAction: ((_ translation: CGFloat) -> Void)? = nil) {
self.init()
self.topDockHeight = topDockHeight
self.coefficient = coefficient
self.scrollUpAction = scrollUpAction
self.scrollDownAction = scrollDownAction
}
open override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
var layoutAttributes = super.layoutAttributesForElements(in: rect)! as [UICollectionViewLayoutAttributes]
let insets = collectionView!.contentInset
let offset = collectionView!.contentOffset
let minY = -insets.top
if offset.y < minY {
let deltaY: CGFloat = abs(offset.y - minY)
for attributes in layoutAttributes where 0 == attributes.indexPath.section && attributes.representedElementKind == UICollectionView.elementKindSectionHeader {
var frame: CGRect = attributes.frame
let referenceHeight: CGFloat = stretchyHeaderReferenceSize().height
var newHeight: CGFloat = max(minY, referenceHeight + deltaY)
if newHeight > referenceHeight * coefficient {
newHeight = referenceHeight * coefficient
}
frame.size.height = newHeight
frame.origin.y = frame.minY - deltaY
attributes.frame = frame
}
scrollDownAction?(deltaY)
} else if topDockHeight > 0 {
let referenceHeight = stretchyHeaderReferenceSize().height
let coverHeight = referenceHeight - topDockHeight - insets.top
if offset.y > coverHeight {
let deltaY = abs(offset.y)
for attributes in layoutAttributes where 0 == attributes.indexPath.section {
if attributes.representedElementKind == UICollectionView.elementKindSectionHeader {
var frame = attributes.frame
frame.origin.y = deltaY - coverHeight
attributes.frame = frame
attributes.zIndex = 1024
headerAttributes = attributes
} else {
if let headerAttributes = headerAttributes {
var frame = headerAttributes.frame
frame.origin.y = deltaY - coverHeight
headerAttributes.frame = frame
layoutAttributes.append(headerAttributes)
}
}
}
scrollUpAction?(1.0)
} else {
scrollUpAction?(1.0 - (coverHeight - offset.y) / coverHeight)
}
}
return layoutAttributes
}
private func stretchyHeaderReferenceSize() -> CGSize {
if let collectionView = collectionView {
if let delegate = collectionView.delegate as? UICollectionViewDelegateFlowLayout {
if let size = delegate.collectionView?(collectionView, layout: self, referenceSizeForHeaderInSection: 0) {
return size
}
}
}
return headerReferenceSize
}
open override func shouldInvalidateLayout(forBoundsChange newBounds: CGRect) -> Bool {
return true
}
}
| mit | 4ae21e721e2806c66a47ad8bd913a3c6 | 41.904255 | 170 | 0.597818 | 6.082956 | false | false | false | false |
guojiubo/PlainReader | PlainReader/View/ThemeSwitch.swift | 1 | 2928 | //
// ThemeSwitch.swift
// PlainReader
//
// Created by guo on 11/29/14.
// Copyright (c) 2014 guojiubo. All rights reserved.
//
import UIKit
import CWFoundation
class ThemeSwitch: UIControl {
var normalLabel = UILabel(frame: CGRect.zero)
var selectedLabel = UILabel(frame: CGRect.zero)
var imageView = UIImageView(image: UIImage(named: "ThemeNight"))
override init(frame: CGRect) {
super.init(frame: frame)
self.setup()
}
required init(coder: NSCoder) {
super.init(coder: coder)!
self.setup()
}
func setup() {
let border = UIImageView(image: UIImage(named: "ThemeSwitchBorder"))
border.center.y = self.bounds.height / 2
self.addSubview(border)
self.normalLabel.frame = CGRect(x: 10, y: (self.bounds.height - border.bounds.height) / 2, width: border.bounds.width - 20, height: border.bounds.height)
self.normalLabel.font = UIFont.systemFont(ofSize: 12)
self.normalLabel.textColor = UIColor.white
self.normalLabel.text = "夜间"
self.normalLabel.textAlignment = .right
self.addSubview(normalLabel)
self.selectedLabel.frame = CGRect(x: 10, y: (self.bounds.height - border.bounds.height) / 2, width: border.bounds.width - 20, height: border.bounds.height)
self.selectedLabel.font = UIFont.systemFont(ofSize: 12)
self.selectedLabel.textColor = CW_HEXColor(0x23beff)
self.selectedLabel.text = "白天"
self.selectedLabel.alpha = 0
self.addSubview(selectedLabel)
self.imageView.frame = CGRect(x: 5, y: (self.bounds.height - self.imageView.bounds.height) / 2, width: self.imageView.bounds.width, height: self.imageView.bounds.height)
self .addSubview(self.imageView)
self.addTarget(self, action: #selector(ThemeSwitch.handleTouchDown(_:)), for: .touchDown)
}
func handleTouchDown(_ sender: UIControl) {
self.isSelected = !self.isSelected
self.sendActions(for: .valueChanged)
}
override var isSelected: Bool {
didSet {
UIView.animate(withDuration: 0.3, animations: { () -> Void in
self.normalLabel.alpha = self.isSelected ? 0 : 1
self.selectedLabel.alpha = self.isSelected ? 1 : 0
var frame = self.imageView.frame
frame.origin.x = self.isSelected ? ( self.bounds.width - self.imageView.bounds.width - 5) : 5
self.imageView.frame = frame
})
UIView.transition(with: self.imageView, duration: 0.3, options: .transitionCrossDissolve, animations: { () -> Void in
self.imageView.image = self.isSelected ? UIImage(named: "ThemeDay") : UIImage(named: "ThemeNight")
}, completion: nil)
}
}
}
| mit | 321da671141a6602b059d38a5e1cda78 | 35.5 | 177 | 0.611301 | 4.183381 | false | false | false | false |
meetkei/KxUI | KxUI/Color/String+Color.swift | 1 | 5232 | //
// Copyright (c) 2016 Keun young Kim <[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 Foundation
public extension String {
private var len: Int {
#if swift(>=3.2)
return count
#else
return characters.count
#endif
}
/// A Boolean value that indicates whether the receiver is hexadecimal color string
var isHexColorString: Bool {
if !hasPrefix("#") || len < 4 || len > 9 {
return false
}
do {
let pattern = "^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3}|[A-Fa-f0-9]{4}|[A-Fa-f0-9]{8})$"
let regex = try NSRegularExpression(pattern: pattern, options: [])
let range = NSRange(location: 0, length: len)
return regex.numberOfMatches(in: self, options: [], range: range) == 1
} catch {
print(error)
}
return false
}
/// The red component of the hexadecimal color string
var redComponent: CGFloat? {
guard isHexColorString else { return nil }
switch len {
case 4, 5:
return parse(subRange: 1...2)
case 7, 9:
return parse(subRange: 1...3)
default:
return nil
}
}
/// The green component of the hexadecimal color string
var greenComponent: CGFloat? {
guard isHexColorString else { return nil }
switch len {
case 4, 5:
return parse(subRange: 2...3)
case 7, 9:
return parse(subRange: 3...5)
default:
return nil
}
}
/// The blue component of the hexadecimal color string
var blueComponent: CGFloat? {
guard isHexColorString else { return nil }
switch len {
case 4, 5:
return parse(subRange: 3...4)
case 7, 9:
return parse(subRange: 5...7)
default:
return nil
}
}
/// The alpha component of the hexadecimal color string
var alphaComponent: CGFloat? {
guard isHexColorString else { return nil }
switch len {
case 5:
return parse(subRange: 4...5)
case 9:
return parse(subRange: 7...9)
default:
return 255.0
}
}
/// The receiver's UIColor representation
var UIColorValue: UIColor? {
return parseHexColorString()
}
/// Parse the content of receiver.
///
/// The method can parse following format:
/// - RGB
/// - RGBA
/// - RRGGBB
/// - RRGGBBAA
///
/// - Returns: The UIColor object for the parsed string, or nil if there is an error of if receiver is not a valid hexadecimal color string
func parseHexColorString() -> UIColor? {
if let r = redComponent, let g = greenComponent, let b = blueComponent {
let a = alphaComponent ?? 255
return UIColor(red: r/255.0, green: g/255.0, blue: b/255.0, alpha: a/255.0)
}
return nil
}
/// Parse the content of specific range.
///
/// - Parameter subRange: range to parse
/// - Returns: The floating-point value, or nil if the content of specified range cannot be parsed
fileprivate func parse(subRange: CountableClosedRange<Int>) -> CGFloat? {
let substringRange = Range<String.Index>(uncheckedBounds: (index(startIndex, offsetBy: subRange.lowerBound), index(startIndex, offsetBy: subRange.upperBound)))
#if swift(>=4.0)
var value = String(self[substringRange])
#else
var value = substring(with: substringRange)
#endif
#if swift(>=3.2)
if value.count == 1 {
value = value + value
}
#else
if value.characters.count == 1 {
value = value + value
}
#endif
var result: UInt32 = 0
let scanner = Scanner(string: value)
if scanner.scanHexInt32(&result) {
return CGFloat(result)
}
return nil
}
}
| mit | 1a98c1a2c8a87b28c343daa223de40de | 29.068966 | 167 | 0.577982 | 4.613757 | false | false | false | false |
lwg123/swift_LWGWB | LWGWB/LWGWB/classes/Home/PhotoBrowser/ProgressView.swift | 1 | 1041 | //
// ProgressView.swift
// LWGWB
//
// Created by weiguang on 2017/5/10.
// Copyright © 2017年 weiguang. All rights reserved.
//
import UIKit
class ProgressView: UIView {
// 定义属性
var progress: CGFloat = 0 {
didSet {
setNeedsDisplay()
}
}
override func draw(_ rect: CGRect) {
super.draw(rect)
// 获取参数
let center = CGPoint(x: rect.width * 0.5, y: rect.height * 0.5)
let radius = rect.width * 0.5 - 3
let startAngle = CGFloat(-M_PI_2)
let endAngle = CGFloat(2 * M_PI) * progress + startAngle
// 创建贝塞尔曲线
let path = UIBezierPath(arcCenter: center, radius: radius, startAngle: startAngle, endAngle: endAngle, clockwise: true)
// 绘制一条中心点的线
path.addLine(to: center)
path.close()
// 设置绘制的颜色
UIColor(white: 1.0, alpha: 0.4).setFill()
// 开始绘制
path.fill()
}
}
| mit | 684c5dee98b26a33009760b28d7aaaa7 | 21.511628 | 127 | 0.53719 | 3.826087 | false | false | false | false |
AdaptiveMe/adaptive-arp-api-lib-darwin | Pod/Classes/Sources.Api/AnalyticsBridge.swift | 1 | 3476 | /**
--| ADAPTIVE RUNTIME PLATFORM |----------------------------------------------------------------------------------------
(C) Copyright 2013-2015 Carlos Lozano Diez t/a Adaptive.me <http://adaptive.me>.
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 appli-
-cable 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.
Original author:
* Carlos Lozano Diez
<http://github.com/carloslozano>
<http://twitter.com/adaptivecoder>
<mailto:[email protected]>
Contributors:
* Ferran Vila Conesa
<http://github.com/fnva>
<http://twitter.com/ferran_vila>
<mailto:[email protected]>
* See source code files for contributors.
Release:
* @version v2.2.15
-------------------------------------------| aut inveniam viam aut faciam |--------------------------------------------
*/
import Foundation
/**
Interface for Analytics purposes
Auto-generated implementation of IAnalytics specification.
*/
public class AnalyticsBridge : BaseApplicationBridge, IAnalytics, APIBridge {
/**
API Delegate.
*/
private var delegate : IAnalytics? = nil
/**
Constructor with delegate.
@param delegate The delegate implementing platform specific functions.
*/
public init(delegate : IAnalytics?) {
self.delegate = delegate
}
/**
Get the delegate implementation.
@return IAnalytics delegate that manages platform specific functions..
*/
public final func getDelegate() -> IAnalytics? {
return self.delegate
}
/**
Set the delegate implementation.
@param delegate The delegate implementing platform specific functions.
*/
public final func setDelegate(delegate : IAnalytics) {
self.delegate = delegate;
}
/**
Invokes the given method specified in the API request object.
@param request APIRequest object containing method name and parameters.
@return APIResponse with status code, message and JSON response or a JSON null string for void functions. Status code 200 is OK, all others are HTTP standard error conditions.
*/
public override func invoke(request : APIRequest) -> APIResponse? {
let response : APIResponse = APIResponse()
var responseCode : Int32 = 200
var responseMessage : String = "OK"
let responseJSON : String? = "null"
switch request.getMethodName()! {
default:
// 404 - response null.
responseCode = 404
responseMessage = "AnalyticsBridge does not provide the function '\(request.getMethodName()!)' Please check your client-side API version; should be API version >= v2.2.15."
}
response.setResponse(responseJSON!)
response.setStatusCode(responseCode)
response.setStatusMessage(responseMessage)
return response
}
}
/**
------------------------------------| Engineered with ♥ in Barcelona, Catalonia |--------------------------------------
*/
| apache-2.0 | de0f24fd3c96d531738a86d2c5b0b6ae | 34.814433 | 188 | 0.62464 | 5.22406 | false | false | false | false |
tbaranes/SwiftyUtils | Sources/Extensions/Foundation/Timer/TimerExtension.swift | 1 | 4372 | //
// Created by Tom Baranes on 24/04/16.
// Copyright © 2016 Tom Baranes. All rights reserved.
//
import Foundation
// MARK: - After
extension Timer {
/// Create and schedule a timer that will call `block` once after the specified time.
/// - Parameters:
/// - interval: The time interval to wait before schedule the `Timer`.
/// - block: The block invoked when the timer fires. The block takes no argument.
/// - Returns: The created Timer.
public class func new(after interval: TimeInterval, _ block: @escaping () -> Void) -> Timer {
CFRunLoopTimerCreateWithHandler(kCFAllocatorDefault,
CFAbsoluteTimeGetCurrent() + interval,
0,
0,
0) { _ in
block()
}
}
/// Create and schedule a timer that will call `block` once after the specified time.
/// - Parameters:
/// - interval: The time interval to wait before schedule the `Timer`.
/// - block: The block invoked when the timer fires. The block takes no argument.
/// - Returns: The created Timer.
public class func after(_ interval: TimeInterval, _ block: @escaping () -> Void) -> Timer {
let timer = Timer.new(after: interval, block)
timer.start()
return timer
}
}
// MARK: - Every
extension Timer {
/// Create and schedule a timer that will call `block` repeatedly in specified time intervals.
/// - Parameters:
/// - interval: The firing interval of the timer.
/// - firesImmediately: A boolean indicating if the Timer must be fired immediately or not.
/// Default value is false.
/// - block: The block invoked when the timer fires. The block takes one argument
/// corresponding to the `Timer` that has been fired.
/// - Returns: The created Timer.
public class func every(_ interval: TimeInterval,
firesImmediately: Bool = false,
_ block: @escaping (Timer) -> Void) -> Timer {
if firesImmediately {
let fireDate = CFAbsoluteTimeGetCurrent()
let timer = CFRunLoopTimerCreateWithHandler(kCFAllocatorDefault,
fireDate,
interval,
0,
0) { x in block(x!) }
CFRunLoopAddTimer(CFRunLoopGetCurrent(), timer, CFRunLoopMode.commonModes)
return timer!
} else {
let timer = Timer.new(every: interval, block)
timer.start()
return timer
}
}
/// Create and schedule a timer that will call `block` once after the specified time.
/// - Parameters:
/// - interval: The time interval to wait before schedule the `Timer`.
/// - block: The block invoked when the timer fires. The block takes one argument corresponding
/// to the `Timer` that has been fired.
/// - Returns: The created Timer.
public class func new(every interval: TimeInterval, _ block: @escaping (Timer) -> Void) -> Timer {
var timer: Timer!
timer = CFRunLoopTimerCreateWithHandler(kCFAllocatorDefault,
CFAbsoluteTimeGetCurrent() + interval,
interval,
0,
0) { _ in
block(timer)
}
return timer
}
}
// MARK: - Misc
extension Timer {
/// Schedule this timer on the run loop.
/// - Parameters:
/// - runLoop: The run loop where the Timer is scheduled. The default value is `RunLoop.current`
/// - modes: The run loop mode where the timer is scheduled. If none, it will scheduled on
/// `RunLoop.Mode.default`.
public func start(onRunLoop runLoop: RunLoop = RunLoop.current, modes: RunLoop.Mode...) {
let modes = modes.isEmpty ? [RunLoop.Mode.default] : modes
modes.forEach {
runLoop.add(self, forMode: $0)
}
}
}
| mit | 4fea36382c9091f362953db3d6a9a4b7 | 39.850467 | 104 | 0.532601 | 5.291768 | false | false | false | false |
NickKech/Breaker | Breaker-iOS/BlockNode.swift | 1 | 1768 | //
// BlockNode.swift
// Breaker
//
/* 1 */
import SpriteKit
/* 2 */
class BlockNode: SKNode {
/* 3 */
var image: SKSpriteNode!
/* 4 */
var toughness = 1 // Default value
/* 5 */
init(texture: SKTexture, toughness: Int) {
self.toughness = toughness
super.init()
/* Add Image */
addImage(texture)
/* Add Shadow */
addShadow()
}
/* 6 */
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func addImage(_ texture: SKTexture) {
/* 1 */
image = SKSpriteNode(texture: texture)
image.position = CGPoint(x: 0, y: 0)
image.zPosition = 1
addChild(image)
/* 2 */
physicsBody = SKPhysicsBody(rectangleOf: image.size)
/* 3 */
physicsBody?.isDynamic = false
/* 4 */
physicsBody?.friction = 0.0
/* 5 */
physicsBody?.restitution = 1.0
/* 6 */
physicsBody?.categoryBitMask = ColliderCategory.block.rawValue
/* 7 */
physicsBody?.collisionBitMask = ColliderCategory.ball.rawValue
}
func addShadow() {
/* 1 */
let shadow = SKSpriteNode(imageNamed: "ShadowBlock")
shadow.position = CGPoint(x: -1, y: -1)
shadow.zPosition = 0
addChild(shadow)
}
func gotHit() {
/* 1 */
toughness -= 1
if toughness > 0 {
/* 2 */
let crack = SKSpriteNode(texture: SKTexture(imageNamed: "Crack"))
crack.zPosition = 3
crack.name = "Crack"
image.addChild(crack)
} else {
/* 3 */
removeFromParent()
}
}
}
| mit | 0c125c41a54600d6522c3d7322e3715e | 20.82716 | 77 | 0.502828 | 4.475949 | false | false | false | false |
rogeriopr/app-anti-corrupcao | ios/Impactar/TabBarController.swift | 1 | 1127 | //
// TabBarController.swift
// Impactar
//
// Created by Davi Rodrigues on 13/04/16.
// Copyright © 2016 Davi Rodrigues. All rights reserved.
//
import UIKit
class TabBarController: UITabBarController {
override func viewDidLoad() {
super.viewDidLoad()
//Inicializa os títulos dos icones da tabBar
self.tabBar.items![0].title = "Fiscalizar"
self.tabBar.items![1].title = "Denunciar"
self.tabBar.items![2].title = "Social"
self.tabBar.items![3].title = "Mais"
//Inicializa os icones da tabBar
self.tabBar.items![0].image = UIImage(named:"Fiscalizar")
self.tabBar.items![1].image = UIImage(named:"Denunciar")
self.tabBar.items![2].image = UIImage(named:"Social")
self.tabBar.items![3].image = UIImage(named:"Mais")
self.tabBar.barTintColor = Styles.azulImpacta
self.tabBar.tintColor = Styles.cinzaTintColor
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| gpl-3.0 | 77e766e33d90f6f4e4b1376c25b765fc | 26.439024 | 65 | 0.628444 | 4.003559 | false | false | false | false |
Authman2/Pix | Pix/Post.swift | 1 | 2903 | //
// Post.swift
// Pix
//
// Created by Adeola Uthman on 12/23/16.
// Copyright © 2016 Adeola Uthman. All rights reserved.
//
import Foundation
import UIKit
import IGListKit
public class Post: NSObject, IGListDiffable {
/********************************
*
* VARIABLES
*
********************************/
/* The image view of the photo that is uploaded on this post. */
var photo: UIImage!;
/* The caption on the photo. */
var caption: String!;
/* The number of likes on this post. */
var likes: Int = Int();
/* The user who uploaded this post. */
var uploader: User!;
/* The id used to specify this particular Post object. */
var id: String!;
/* Whether or not this is the user's profile picture. */
var isProfilePicture = false;
/* The number of times this post has been flagged as inappropriate. */
var flags: Int = 0;
/* All of the comments on the picture. In the form "userid commentstring" */
var comments: [String]?;
/********************************
*
* METHODS
*
********************************/
init(photo: UIImage?, caption: String?, Uploader: User?, ID: String?) {
self.photo = photo;
self.caption = caption;
self.uploader = Uploader;
self.id = ID;
self.comments = [String]();
}
/* Turns the post object into a format that can be read by firebase. */
func toDictionary() -> NSDictionary {
let dict = NSDictionary(dictionary: ["image" : id+".jpg",
"id" : id,
"caption" : caption,
"likes" : likes,
"is_profile_picture" : isProfilePicture,
"flags" : flags,
"comments" : comments ?? []]);
return dict;
}
func copy(post: Post) {
self.photo = post.photo;
self.caption = post.caption;
self.uploader = post.uploader;
self.id = post.id;
self.flags = post.flags;
self.likes = post.likes;
self.isProfilePicture = post.isProfilePicture;
self.comments = post.comments;
}
func toString() -> String {
return "id=\(id!), caption=\(caption), likes=\(likes), profile picture?: \(isProfilePicture)";
}
public func diffIdentifier() -> NSObjectProtocol {
return self;
}
public func isEqual(toDiffableObject object: IGListDiffable?) -> Bool {
if let obj = object as! Post? {
return id == obj.id;
}
return false;
}
}
| gpl-3.0 | 37e88228181d14d6eb9e004ae3354c4b | 24.681416 | 102 | 0.474845 | 5.046957 | false | false | false | false |
bingFly/weibo | weibo/weibo/Classes/UI/Main/HBTabBar.swift | 1 | 2040 | //
// HBTabBar.swift
// weibo
//
// Created by hanbing on 15/3/5.
// Copyright (c) 2015年 fly. All rights reserved.
//
import UIKit
class HBTabBar: UITabBar {
var composeButtonClicked: (() -> ())?
override func awakeFromNib() {
//增加一个按钮
addCompose()
}
func addCompose(){
self.addSubview(composeButton!)
}
override func layoutSubviews() {
super.layoutSubviews()
setSubviewsFrame()
}
func setSubviewsFrame(){
let count = 5
let w = self.bounds.size.width / CGFloat(count)
let h = self.bounds.size.height
var index = 0
for view in self.subviews as! [UIView] {
if view is UIControl && !(view is UIButton) {
let frame = CGRectMake(CGFloat(index) * w, 0, w, h)
view.frame = frame
index++
if index == 2 {
index++
}
}
}
composeButton!.frame = CGRectMake(0, 0, w, h)
composeButton!.center = CGPointMake(self.center.x, h * 0.5)
}
/// 懒加载按钮
lazy var composeButton: UIButton? = {
let compose = UIButton()
compose.setImage(UIImage(named: "tabbar_compose_icon_add"), forState: .Normal)
compose.setImage(UIImage(named: "tabbar_compose_icon_add_highlighted"), forState: .Highlighted)
compose.setBackgroundImage(UIImage(named: "tabbar_compose_button"), forState: .Normal)
compose.setBackgroundImage(UIImage(named: "tabbar_compose_button_highlighted"), forState: .Highlighted)
compose.addTarget(self, action: "composeClick", forControlEvents: .TouchUpInside)
return compose
}()
func composeClick() {
if composeButtonClicked != nil {
composeButtonClicked!()
}
}
}
| mit | 03ca69de4fd886ddeb7e09d017fe00e3 | 24.2 | 111 | 0.524306 | 4.834532 | false | false | false | false |
netguru/inbbbox-ios | Inbbbox/Source Files/Networking/PageRequest.swift | 1 | 2294 | //
// PageRequest.swift
// Inbbbox
//
// Created by Patryk Kaczmarek on 28/01/16.
// Copyright © 2016 Netguru Sp. z o.o. All rights reserved.
//
import Foundation
import PromiseKit
import SwiftyJSON
typealias PageResponse = (json: JSON?, pages: (next: PageableComponent?, previous: PageableComponent?))
struct PageRequest: Requestable, Responsable {
/// Query used to create page request.
let query: Query
// Session for page request.
let session: URLSession
init(query: Query, urlSession: URLSession = URLSession.inbbboxDefaultSession()) {
self.query = query
session = urlSession
}
/// Invoke page request.
///
/// - returns: Promise which resolves with `PageResponse`
/// that contains response as JSON and components for
/// next and previous pages.
func resume() -> Promise<PageResponse> {
return Promise<PageResponse> { fulfill, reject in
do {
try APIRateLimitKeeper.sharedKeeper.verifyRateLimit()
} catch {
throw error
}
let dataTask = session.dataTask(with: foundationRequest as URLRequest) { data, response, error in
if let error = error {
reject(error); return
}
firstly {
self.responseWithData(data, response: response)
}.then { response -> Void in
var next: PageableComponent?
var previous: PageableComponent?
if let header = response.header {
next = PageableComponentSerializer.nextPageableComponentWithSentQuery(self.query,
receivedHeader: header)
previous = PageableComponentSerializer.previousPageableComponentWithSentQuery(self.query,
receivedHeader: header)
}
fulfill((
json: response.json,
pages: (
next: next,
previous: previous)
))
}.catch(execute: reject)
}
dataTask.resume()
}
}
}
| gpl-3.0 | c0036678252819eccbdea4a23ea24b98 | 29.171053 | 113 | 0.536415 | 5.512019 | false | false | false | false |
jamgzj/resourceObject | Swift/SwiftStudy/Pods/Kingfisher/Sources/Image.swift | 6 | 34094 | //
// Image.swift
// Kingfisher
//
// Created by Wei Wang on 16/1/6.
//
// Copyright (c) 2017 Wei Wang <[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.
#if os(macOS)
import AppKit
private var imagesKey: Void?
private var durationKey: Void?
#else
import UIKit
import MobileCoreServices
private var imageSourceKey: Void?
#endif
private var animatedImageDataKey: Void?
import ImageIO
import CoreGraphics
#if !os(watchOS)
import Accelerate
import CoreImage
#endif
// MARK: - Image Properties
extension Kingfisher where Base: Image {
fileprivate(set) var animatedImageData: Data? {
get {
return objc_getAssociatedObject(base, &animatedImageDataKey) as? Data
}
set {
objc_setAssociatedObject(base, &animatedImageDataKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
#if os(macOS)
var cgImage: CGImage? {
return base.cgImage(forProposedRect: nil, context: nil, hints: nil)
}
var scale: CGFloat {
return 1.0
}
fileprivate(set) var images: [Image]? {
get {
return objc_getAssociatedObject(base, &imagesKey) as? [Image]
}
set {
objc_setAssociatedObject(base, &imagesKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
fileprivate(set) var duration: TimeInterval {
get {
return objc_getAssociatedObject(base, &durationKey) as? TimeInterval ?? 0.0
}
set {
objc_setAssociatedObject(base, &durationKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
var size: CGSize {
return base.representations.reduce(CGSize.zero, { size, rep in
return CGSize(width: max(size.width, CGFloat(rep.pixelsWide)), height: max(size.height, CGFloat(rep.pixelsHigh)))
})
}
#else
var cgImage: CGImage? {
return base.cgImage
}
var scale: CGFloat {
return base.scale
}
var images: [Image]? {
return base.images
}
var duration: TimeInterval {
return base.duration
}
fileprivate(set) var imageSource: ImageSource? {
get {
return objc_getAssociatedObject(base, &imageSourceKey) as? ImageSource
}
set {
objc_setAssociatedObject(base, &imageSourceKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
var size: CGSize {
return base.size
}
#endif
}
// MARK: - Image Conversion
extension Kingfisher where Base: Image {
#if os(macOS)
static func image(cgImage: CGImage, scale: CGFloat, refImage: Image?) -> Image {
return Image(cgImage: cgImage, size: CGSize.zero)
}
/**
Normalize the image. This method does nothing in OS X.
- returns: The image itself.
*/
public var normalized: Image {
return base
}
static func animated(with images: [Image], forDuration forDurationduration: TimeInterval) -> Image? {
return nil
}
#else
static func image(cgImage: CGImage, scale: CGFloat, refImage: Image?) -> Image {
if let refImage = refImage {
return Image(cgImage: cgImage, scale: scale, orientation: refImage.imageOrientation)
} else {
return Image(cgImage: cgImage, scale: scale, orientation: .up)
}
}
/**
Normalize the image. This method will try to redraw an image with orientation and scale considered.
- returns: The normalized image with orientation set to up and correct scale.
*/
public var normalized: Image {
// prevent animated image (GIF) lose it's images
guard images == nil else { return base }
// No need to do anything if already up
guard base.imageOrientation != .up else { return base }
return draw(cgImage: nil, to: size) {
base.draw(in: CGRect(origin: CGPoint.zero, size: size))
}
}
static func animated(with images: [Image], forDuration duration: TimeInterval) -> Image? {
return .animatedImage(with: images, duration: duration)
}
#endif
}
// MARK: - Image Representation
extension Kingfisher where Base: Image {
// MARK: - PNG
public func pngRepresentation() -> Data? {
#if os(macOS)
guard let cgimage = cgImage else {
return nil
}
let rep = NSBitmapImageRep(cgImage: cgimage)
return rep.representation(using: .PNG, properties: [:])
#else
return UIImagePNGRepresentation(base)
#endif
}
// MARK: - JPEG
public func jpegRepresentation(compressionQuality: CGFloat) -> Data? {
#if os(macOS)
guard let cgImage = cgImage else {
return nil
}
let rep = NSBitmapImageRep(cgImage: cgImage)
return rep.representation(using:.JPEG, properties: [NSImageCompressionFactor: compressionQuality])
#else
return UIImageJPEGRepresentation(base, compressionQuality)
#endif
}
// MARK: - GIF
public func gifRepresentation() -> Data? {
return animatedImageData
}
}
// MARK: - Create images from data
extension Kingfisher where Base: Image {
static func animated(with data: Data, scale: CGFloat = 1.0, duration: TimeInterval = 0.0, preloadAll: Bool, onlyFirstFrame: Bool = false) -> Image? {
func decode(from imageSource: CGImageSource, for options: NSDictionary) -> ([Image], TimeInterval)? {
//Calculates frame duration for a gif frame out of the kCGImagePropertyGIFDictionary dictionary
func frameDuration(from gifInfo: NSDictionary?) -> Double {
let gifDefaultFrameDuration = 0.100
guard let gifInfo = gifInfo else {
return gifDefaultFrameDuration
}
let unclampedDelayTime = gifInfo[kCGImagePropertyGIFUnclampedDelayTime as String] as? NSNumber
let delayTime = gifInfo[kCGImagePropertyGIFDelayTime as String] as? NSNumber
let duration = unclampedDelayTime ?? delayTime
guard let frameDuration = duration else { return gifDefaultFrameDuration }
return frameDuration.doubleValue > 0.011 ? frameDuration.doubleValue : gifDefaultFrameDuration
}
let frameCount = CGImageSourceGetCount(imageSource)
var images = [Image]()
var gifDuration = 0.0
for i in 0 ..< frameCount {
guard let imageRef = CGImageSourceCreateImageAtIndex(imageSource, i, options) else {
return nil
}
if frameCount == 1 {
// Single frame
gifDuration = Double.infinity
} else {
// Animated GIF
guard let properties = CGImageSourceCopyPropertiesAtIndex(imageSource, i, nil) else {
return nil
}
let gifInfo = (properties as NSDictionary)[kCGImagePropertyGIFDictionary as String] as? NSDictionary
gifDuration += frameDuration(from: gifInfo)
}
images.append(Kingfisher<Image>.image(cgImage: imageRef, scale: scale, refImage: nil))
if onlyFirstFrame { break }
}
return (images, gifDuration)
}
// Start of kf.animatedImageWithGIFData
let options: NSDictionary = [kCGImageSourceShouldCache as String: true, kCGImageSourceTypeIdentifierHint as String: kUTTypeGIF]
guard let imageSource = CGImageSourceCreateWithData(data as CFData, options) else {
return nil
}
#if os(macOS)
guard let (images, gifDuration) = decode(from: imageSource, for: options) else {
return nil
}
let image: Image?
if onlyFirstFrame {
image = images.first
} else {
image = Image(data: data)
image?.kf.images = images
image?.kf.duration = gifDuration
}
image?.kf.animatedImageData = data
return image
#else
let image: Image?
if preloadAll || onlyFirstFrame {
guard let (images, gifDuration) = decode(from: imageSource, for: options) else { return nil }
image = onlyFirstFrame ? images.first : Kingfisher<Image>.animated(with: images, forDuration: duration <= 0.0 ? gifDuration : duration)
} else {
image = Image(data: data)
image?.kf.imageSource = ImageSource(ref: imageSource)
}
image?.kf.animatedImageData = data
return image
#endif
}
static func image(data: Data, scale: CGFloat, preloadAllGIFData: Bool, onlyFirstFrame: Bool) -> Image? {
var image: Image?
#if os(macOS)
switch data.kf.imageFormat {
case .JPEG:
image = Image(data: data)
case .PNG:
image = Image(data: data)
case .GIF:
image = Kingfisher<Image>.animated(
with: data,
scale: scale,
duration: 0.0,
preloadAll: preloadAllGIFData,
onlyFirstFrame: onlyFirstFrame)
case .unknown:
image = Image(data: data)
}
#else
switch data.kf.imageFormat {
case .JPEG:
image = Image(data: data, scale: scale)
case .PNG:
image = Image(data: data, scale: scale)
case .GIF:
image = Kingfisher<Image>.animated(
with: data,
scale: scale,
duration: 0.0,
preloadAll: preloadAllGIFData,
onlyFirstFrame: onlyFirstFrame)
case .unknown:
image = Image(data: data, scale: scale)
}
#endif
return image
}
}
// MARK: - Image Transforming
extension Kingfisher where Base: Image {
// MARK: - Round Corner
/// Create a round corner image based on `self`.
///
/// - parameter radius: The round corner radius of creating image.
/// - parameter size: The target size of creating image.
///
/// - returns: An image with round corner of `self`.
///
/// - Note: This method only works for CG-based image.
public func image(withRoundRadius radius: CGFloat, fit size: CGSize) -> Image {
guard let cgImage = cgImage else {
assertionFailure("[Kingfisher] Round corner image only works for CG-based image.")
return base
}
let rect = CGRect(origin: CGPoint(x: 0, y: 0), size: size)
return draw(cgImage: cgImage, to: size) {
#if os(macOS)
let path = NSBezierPath(roundedRect: rect, xRadius: radius, yRadius: radius)
path.windingRule = .evenOddWindingRule
path.addClip()
base.draw(in: rect)
#else
guard let context = UIGraphicsGetCurrentContext() else {
assertionFailure("[Kingfisher] Failed to create CG context for image.")
return
}
let path = UIBezierPath(roundedRect: rect, byRoundingCorners: .allCorners, cornerRadii: CGSize(width: radius, height: radius)).cgPath
context.addPath(path)
context.clip()
base.draw(in: rect)
#endif
}
}
#if os(iOS) || os(tvOS)
func resize(to size: CGSize, for contentMode: UIViewContentMode) -> Image {
switch contentMode {
case .scaleAspectFit:
return resize(to: size, for: .aspectFit)
case .scaleAspectFill:
return resize(to: size, for: .aspectFill)
default:
return resize(to: size)
}
}
#endif
// MARK: - Resize
/// Resize `self` to an image of new size.
///
/// - parameter size: The target size.
///
/// - returns: An image with new size.
///
/// - Note: This method only works for CG-based image.
public func resize(to size: CGSize) -> Image {
guard let cgImage = cgImage else {
assertionFailure("[Kingfisher] Resize only works for CG-based image.")
return base
}
let rect = CGRect(origin: CGPoint(x: 0, y: 0), size: size)
return draw(cgImage: cgImage, to: size) {
#if os(macOS)
base.draw(in: rect, from: NSRect.zero, operation: .copy, fraction: 1.0)
#else
base.draw(in: rect)
#endif
}
}
/// Resize `self` to an image of new size, respecting the content mode.
///
/// - Parameters:
/// - size: The target size.
/// - contentMode: Content mode of output image should be.
/// - Returns: An image with new size.
public func resize(to size: CGSize, for contentMode: ContentMode) -> Image {
switch contentMode {
case .aspectFit:
let newSize = self.size.kf.constrained(size)
return resize(to: newSize)
case .aspectFill:
let newSize = self.size.kf.filling(size)
return resize(to: newSize)
default:
return resize(to: size)
}
}
public func crop(to size: CGSize, anchorOn anchor: CGPoint) -> Image {
guard let cgImage = cgImage else {
assertionFailure("[Kingfisher] Crop only works for CG-based image.")
return base
}
let rect = self.size.kf.constrainedRect(for: size, anchor: anchor)
guard let image = cgImage.cropping(to: rect) else {
assertionFailure("[Kingfisher] Cropping image failed.")
return base
}
return Kingfisher.image(cgImage: image, scale: scale, refImage: base)
}
// MARK: - Blur
/// Create an image with blur effect based on `self`.
///
/// - parameter radius: The blur radius should be used when creating blue.
///
/// - returns: An image with blur effect applied.
///
/// - Note: This method only works for CG-based image.
public func blurred(withRadius radius: CGFloat) -> Image {
#if os(watchOS)
return base
#else
guard let cgImage = cgImage else {
assertionFailure("[Kingfisher] Blur only works for CG-based image.")
return base
}
// http://www.w3.org/TR/SVG/filters.html#feGaussianBlurElement
// let d = floor(s * 3*sqrt(2*pi)/4 + 0.5)
// if d is odd, use three box-blurs of size 'd', centered on the output pixel.
let s = Float(max(radius, 2.0))
// We will do blur on a resized image (*0.5), so the blur radius could be half as well.
// Fix the slow compiling time for Swift 3.
// See https://github.com/onevcat/Kingfisher/issues/611
let pi2 = 2 * Float.pi
let sqrtPi2 = sqrt(pi2)
var targetRadius = floor(s * 3.0 * sqrtPi2 / 4.0 + 0.5)
if targetRadius.isEven {
targetRadius += 1
}
let iterations: Int
if radius < 0.5 {
iterations = 1
} else if radius < 1.5 {
iterations = 2
} else {
iterations = 3
}
let w = Int(size.width)
let h = Int(size.height)
let rowBytes = Int(CGFloat(cgImage.bytesPerRow))
func createEffectBuffer(_ context: CGContext) -> vImage_Buffer {
let data = context.data
let width = vImagePixelCount(context.width)
let height = vImagePixelCount(context.height)
let rowBytes = context.bytesPerRow
return vImage_Buffer(data: data, height: height, width: width, rowBytes: rowBytes)
}
guard let context = beginContext() else {
assertionFailure("[Kingfisher] Failed to create CG context for blurring image.")
return base
}
defer { endContext() }
context.draw(cgImage, in: CGRect(x: 0, y: 0, width: w, height: h))
var inBuffer = createEffectBuffer(context)
guard let outContext = beginContext() else {
assertionFailure("[Kingfisher] Failed to create CG context for blurring image.")
return base
}
defer { endContext() }
var outBuffer = createEffectBuffer(outContext)
for _ in 0 ..< iterations {
vImageBoxConvolve_ARGB8888(&inBuffer, &outBuffer, nil, 0, 0, UInt32(targetRadius), UInt32(targetRadius), nil, vImage_Flags(kvImageEdgeExtend))
(inBuffer, outBuffer) = (outBuffer, inBuffer)
}
#if os(macOS)
let result = outContext.makeImage().flatMap { fixedForRetinaPixel(cgImage: $0, to: size) }
#else
let result = outContext.makeImage().flatMap { Image(cgImage: $0, scale: base.scale, orientation: base.imageOrientation) }
#endif
guard let blurredImage = result else {
assertionFailure("[Kingfisher] Can not make an blurred image within this context.")
return base
}
return blurredImage
#endif
}
// MARK: - Overlay
/// Create an image from `self` with a color overlay layer.
///
/// - parameter color: The color should be use to overlay.
/// - parameter fraction: Fraction of input color. From 0.0 to 1.0. 0.0 means solid color, 1.0 means transparent overlay.
///
/// - returns: An image with a color overlay applied.
///
/// - Note: This method only works for CG-based image.
public func overlaying(with color: Color, fraction: CGFloat) -> Image {
guard let cgImage = cgImage else {
assertionFailure("[Kingfisher] Overlaying only works for CG-based image.")
return base
}
let rect = CGRect(x: 0, y: 0, width: size.width, height: size.height)
return draw(cgImage: cgImage, to: rect.size) {
#if os(macOS)
base.draw(in: rect)
if fraction > 0 {
color.withAlphaComponent(1 - fraction).set()
NSRectFillUsingOperation(rect, .sourceAtop)
}
#else
color.set()
UIRectFill(rect)
base.draw(in: rect, blendMode: .destinationIn, alpha: 1.0)
if fraction > 0 {
base.draw(in: rect, blendMode: .sourceAtop, alpha: fraction)
}
#endif
}
}
// MARK: - Tint
/// Create an image from `self` with a color tint.
///
/// - parameter color: The color should be used to tint `self`
///
/// - returns: An image with a color tint applied.
public func tinted(with color: Color) -> Image {
#if os(watchOS)
return base
#else
return apply(.tint(color))
#endif
}
// MARK: - Color Control
/// Create an image from `self` with color control.
///
/// - parameter brightness: Brightness changing to image.
/// - parameter contrast: Contrast changing to image.
/// - parameter saturation: Saturation changing to image.
/// - parameter inputEV: InputEV changing to image.
///
/// - returns: An image with color control applied.
public func adjusted(brightness: CGFloat, contrast: CGFloat, saturation: CGFloat, inputEV: CGFloat) -> Image {
#if os(watchOS)
return base
#else
return apply(.colorControl(brightness, contrast, saturation, inputEV))
#endif
}
}
// MARK: - Decode
extension Kingfisher where Base: Image {
var decoded: Image? {
return decoded(scale: scale)
}
func decoded(scale: CGFloat) -> Image {
// prevent animated image (GIF) lose it's images
#if os(iOS)
if imageSource != nil { return base }
#else
if images != nil { return base }
#endif
guard let imageRef = self.cgImage else {
assertionFailure("[Kingfisher] Decoding only works for CG-based image.")
return base
}
let colorSpace = CGColorSpaceCreateDeviceRGB()
guard let context = beginContext() else {
assertionFailure("[Kingfisher] Decoding fails to create a valid context.")
return base
}
defer { endContext() }
let rect = CGRect(x: 0, y: 0, width: imageRef.width, height: imageRef.height)
context.draw(imageRef, in: rect)
let decompressedImageRef = context.makeImage()
return Kingfisher<Image>.image(cgImage: decompressedImageRef!, scale: scale, refImage: base)
}
}
/// Reference the source image reference
class ImageSource {
var imageRef: CGImageSource?
init(ref: CGImageSource) {
self.imageRef = ref
}
}
// MARK: - Image format
private struct ImageHeaderData {
static var PNG: [UInt8] = [0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A]
static var JPEG_SOI: [UInt8] = [0xFF, 0xD8]
static var JPEG_IF: [UInt8] = [0xFF]
static var GIF: [UInt8] = [0x47, 0x49, 0x46]
}
enum ImageFormat {
case unknown, PNG, JPEG, GIF
}
// MARK: - Misc Helpers
public struct DataProxy {
fileprivate let base: Data
init(proxy: Data) {
base = proxy
}
}
extension Data: KingfisherCompatible {
public typealias CompatibleType = DataProxy
public var kf: DataProxy {
return DataProxy(proxy: self)
}
}
extension DataProxy {
var imageFormat: ImageFormat {
var buffer = [UInt8](repeating: 0, count: 8)
(base as NSData).getBytes(&buffer, length: 8)
if buffer == ImageHeaderData.PNG {
return .PNG
} else if buffer[0] == ImageHeaderData.JPEG_SOI[0] &&
buffer[1] == ImageHeaderData.JPEG_SOI[1] &&
buffer[2] == ImageHeaderData.JPEG_IF[0]
{
return .JPEG
} else if buffer[0] == ImageHeaderData.GIF[0] &&
buffer[1] == ImageHeaderData.GIF[1] &&
buffer[2] == ImageHeaderData.GIF[2]
{
return .GIF
}
return .unknown
}
}
public struct CGSizeProxy {
fileprivate let base: CGSize
init(proxy: CGSize) {
base = proxy
}
}
extension CGSize: KingfisherCompatible {
public typealias CompatibleType = CGSizeProxy
public var kf: CGSizeProxy {
return CGSizeProxy(proxy: self)
}
}
extension CGSizeProxy {
func constrained(_ size: CGSize) -> CGSize {
let aspectWidth = round(aspectRatio * size.height)
let aspectHeight = round(size.width / aspectRatio)
return aspectWidth > size.width ? CGSize(width: size.width, height: aspectHeight) : CGSize(width: aspectWidth, height: size.height)
}
func filling(_ size: CGSize) -> CGSize {
let aspectWidth = round(aspectRatio * size.height)
let aspectHeight = round(size.width / aspectRatio)
return aspectWidth < size.width ? CGSize(width: size.width, height: aspectHeight) : CGSize(width: aspectWidth, height: size.height)
}
private var aspectRatio: CGFloat {
return base.height == 0.0 ? 1.0 : base.width / base.height
}
func constrainedRect(for size: CGSize, anchor: CGPoint) -> CGRect {
let unifiedAnchor = CGPoint(x: anchor.x.clamped(to: 0.0...1.0),
y: anchor.y.clamped(to: 0.0...1.0))
let x = unifiedAnchor.x * base.width - unifiedAnchor.x * size.width
let y = unifiedAnchor.y * base.height - unifiedAnchor.y * size.height
let r = CGRect(x: x, y: y, width: size.width, height: size.height)
let ori = CGRect(origin: CGPoint.zero, size: base)
return ori.intersection(r)
}
}
extension Comparable {
func clamped(to limits: ClosedRange<Self>) -> Self {
return min(max(self, limits.lowerBound), limits.upperBound)
}
}
extension Kingfisher where Base: Image {
func beginContext() -> CGContext? {
#if os(macOS)
guard let rep = NSBitmapImageRep(
bitmapDataPlanes: nil,
pixelsWide: Int(size.width),
pixelsHigh: Int(size.height),
bitsPerSample: cgImage?.bitsPerComponent ?? 8,
samplesPerPixel: 4,
hasAlpha: true,
isPlanar: false,
colorSpaceName: NSCalibratedRGBColorSpace,
bytesPerRow: 0,
bitsPerPixel: 0) else
{
assertionFailure("[Kingfisher] Image representation cannot be created.")
return nil
}
rep.size = size
NSGraphicsContext.saveGraphicsState()
guard let context = NSGraphicsContext(bitmapImageRep: rep) else {
assertionFailure("[Kingfisher] Image contenxt cannot be created.")
return nil
}
NSGraphicsContext.setCurrent(context)
return context.cgContext
#else
UIGraphicsBeginImageContextWithOptions(size, false, scale)
let context = UIGraphicsGetCurrentContext()
context?.scaleBy(x: 1.0, y: -1.0)
context?.translateBy(x: 0, y: -size.height)
return context
#endif
}
func endContext() {
#if os(macOS)
NSGraphicsContext.restoreGraphicsState()
#else
UIGraphicsEndImageContext()
#endif
}
func draw(cgImage: CGImage?, to size: CGSize, draw: ()->()) -> Image {
#if os(macOS)
guard let rep = NSBitmapImageRep(
bitmapDataPlanes: nil,
pixelsWide: Int(size.width),
pixelsHigh: Int(size.height),
bitsPerSample: cgImage?.bitsPerComponent ?? 8,
samplesPerPixel: 4,
hasAlpha: true,
isPlanar: false,
colorSpaceName: NSCalibratedRGBColorSpace,
bytesPerRow: 0,
bitsPerPixel: 0) else
{
assertionFailure("[Kingfisher] Image representation cannot be created.")
return base
}
rep.size = size
NSGraphicsContext.saveGraphicsState()
let context = NSGraphicsContext(bitmapImageRep: rep)
NSGraphicsContext.setCurrent(context)
draw()
NSGraphicsContext.restoreGraphicsState()
let outputImage = Image(size: size)
outputImage.addRepresentation(rep)
return outputImage
#else
UIGraphicsBeginImageContextWithOptions(size, false, scale)
defer { UIGraphicsEndImageContext() }
draw()
return UIGraphicsGetImageFromCurrentImageContext() ?? base
#endif
}
#if os(macOS)
func fixedForRetinaPixel(cgImage: CGImage, to size: CGSize) -> Image {
let image = Image(cgImage: cgImage, size: base.size)
let rect = CGRect(origin: CGPoint(x: 0, y: 0), size: size)
return draw(cgImage: cgImage, to: self.size) {
image.draw(in: rect, from: NSRect.zero, operation: .copy, fraction: 1.0)
}
}
#endif
}
extension Float {
var isEven: Bool {
return truncatingRemainder(dividingBy: 2.0) == 0
}
}
// MARK: - Deprecated. Only for back compatibility.
extension Image {
/**
Normalize the image. This method does nothing in OS X.
- returns: The image itself.
*/
@available(*, deprecated,
message: "Extensions directly on Image are deprecated. Use `kf.normalized` instead.",
renamed: "kf.normalized")
public func kf_normalized() -> Image {
return kf.normalized
}
// MARK: - Round Corner
/// Create a round corner image based on `self`.
///
/// - parameter radius: The round corner radius of creating image.
/// - parameter size: The target size of creating image.
/// - parameter scale: The image scale of creating image.
///
/// - returns: An image with round corner of `self`.
///
/// - Note: This method only works for CG-based image.
@available(*, deprecated,
message: "Extensions directly on Image are deprecated. Use `kf.image(withRoundRadius:fit:scale:)` instead.",
renamed: "kf.image")
public func kf_image(withRoundRadius radius: CGFloat, fit size: CGSize, scale: CGFloat) -> Image {
return kf.image(withRoundRadius: radius, fit: size)
}
// MARK: - Resize
/// Resize `self` to an image of new size.
///
/// - parameter size: The target size.
///
/// - returns: An image with new size.
///
/// - Note: This method only works for CG-based image.
@available(*, deprecated,
message: "Extensions directly on Image are deprecated. Use `kf.resize(to:)` instead.",
renamed: "kf.resize")
public func kf_resize(to size: CGSize) -> Image {
return kf.resize(to: size)
}
// MARK: - Blur
/// Create an image with blur effect based on `self`.
///
/// - parameter radius: The blur radius should be used when creating blue.
///
/// - returns: An image with blur effect applied.
///
/// - Note: This method only works for CG-based image.
@available(*, deprecated,
message: "Extensions directly on Image are deprecated. Use `kf.blurred(withRadius:)` instead.",
renamed: "kf.blurred")
public func kf_blurred(withRadius radius: CGFloat) -> Image {
return kf.blurred(withRadius: radius)
}
// MARK: - Overlay
/// Create an image from `self` with a color overlay layer.
///
/// - parameter color: The color should be use to overlay.
/// - parameter fraction: Fraction of input color. From 0.0 to 1.0. 0.0 means solid color, 1.0 means transparent overlay.
///
/// - returns: An image with a color overlay applied.
///
/// - Note: This method only works for CG-based image.
@available(*, deprecated,
message: "Extensions directly on Image are deprecated. Use `kf.overlaying(with:fraction:)` instead.",
renamed: "kf.overlaying")
public func kf_overlaying(with color: Color, fraction: CGFloat) -> Image {
return kf.overlaying(with: color, fraction: fraction)
}
// MARK: - Tint
/// Create an image from `self` with a color tint.
///
/// - parameter color: The color should be used to tint `self`
///
/// - returns: An image with a color tint applied.
@available(*, deprecated,
message: "Extensions directly on Image are deprecated. Use `kf.tinted(with:)` instead.",
renamed: "kf.tinted")
public func kf_tinted(with color: Color) -> Image {
return kf.tinted(with: color)
}
// MARK: - Color Control
/// Create an image from `self` with color control.
///
/// - parameter brightness: Brightness changing to image.
/// - parameter contrast: Contrast changing to image.
/// - parameter saturation: Saturation changing to image.
/// - parameter inputEV: InputEV changing to image.
///
/// - returns: An image with color control applied.
@available(*, deprecated,
message: "Extensions directly on Image are deprecated. Use `kf.adjusted` instead.",
renamed: "kf.adjusted")
public func kf_adjusted(brightness: CGFloat, contrast: CGFloat, saturation: CGFloat, inputEV: CGFloat) -> Image {
return kf.adjusted(brightness: brightness, contrast: contrast, saturation: saturation, inputEV: inputEV)
}
}
extension Kingfisher where Base: Image {
@available(*, deprecated,
message: "`scale` is not used. Use the version without scale instead. (Remove the `scale` argument)")
public func image(withRoundRadius radius: CGFloat, fit size: CGSize, scale: CGFloat) -> Image {
return image(withRoundRadius: radius, fit: size)
}
}
| apache-2.0 | 7f89ed17d1bea5aa71b72c684819414f | 33.968205 | 158 | 0.577492 | 4.824395 | false | false | false | false |
codeWorm2015/LRLPhotoBrowser | Sources/LRLPhotoBrowser.swift | 1 | 14034 | //
// LRLPhotoBrowser.swift
// FeelfelCode
//
// Created by liuRuiLong on 17/5/17.
// Copyright © 2017年 李策. All rights reserved.
//
import UIKit
import SnapKit
public enum LRLPhotoBrowserModel{
case imageName(String)
case image(UIImage)
case imageUrl(ur: String, placeHolder: UIImage?)
case videoUrl(url: URL, placeHolder: UIImage?)
}
public enum LRLPBCollectionViewPageType {
case common
case slide
}
public protocol LRLPhotoBrowserDelegate: class{
func imageDidScroll(index: Int) -> UIImageView?
func imageSwipViewDismiss(imageView: UIImageView?)
}
public class LRLPhotoBrowser: UIView, LRLPBCollectionDelegate{
/// 所点击的 imageView
public var selectedImageView: UIImageView?
/// 当前所选中ImageView 相对于 pbSuperView 的位置
public var selectedFrame: CGRect?
public weak var delegate: LRLPhotoBrowserDelegate?
/// 是否开启拖动
public var animition = false{
didSet{
self.collectionView?.panEnable = animition
}
}
/// 相册的实例化方法
///
/// - Parameters:
/// - frame: 相册视图尺寸, 默认为屏幕尺寸
/// - dataSource: 数据源
/// - initialIndex: 初始位置
/// - selectedImageView: 所点击的imageView 根据这个imageView 内部进行动画
/// - delegate: 代理
/// - animition: 是否开启拖拽和动画
public init(frame: CGRect = UIScreen.main.bounds, dataSource: [LRLPhotoBrowserModel], initialIndex: Int, selectedImageView: UIImageView?, delegate: LRLPhotoBrowserDelegate?, animition: Bool = true, pageType: LRLPBCollectionViewPageType = .slide) {
self.pageType = pageType
super.init(frame:frame)
self.dataSource = dataSource
self.delegateHolder = LRLPBCollectionDelegateHolder(delegate: self)
self.imgContentMode = contentMode
self.initialIndex = initialIndex
self.currentIndex = initialIndex
self.selectedImageView = selectedImageView
self.delegate = delegate
self.animition = animition
configUI()
}
/// 显示相册
public func show(){
guard let window = pbSuperView else{
fatalError("no superView")
}
if let inImageView = selectedImageView, let initialFrame = inImageView.superview?.convert(inImageView.frame, to: window){
selectedFrame = initialFrame
let imageView = LRLPBImageView(frame: initialFrame)
imageView.contentMode = .scaleAspectFill
imageView.image = inImageView.image
window.addSubview(imageView)
window.isUserInteractionEnabled = false
UIView.animate(withDuration: 0.2, animations: {
imageView.contentMode = .scaleAspectFit
imageView.frame = self.frame
imageView.backgroundColor = UIColor.black
}, completion: { (complete) in
window.isUserInteractionEnabled = true
imageView.removeFromSuperview()
window.addSubview(self)
})
}else{
window.addSubview(self)
}
}
public func dismiss(){
if let cell = collectionView?.cellForItem(at: IndexPath(item: currentIndex, section: 0)) as? LRLPBImageCell{
dismissCell(cell)
}else{
self.removeFromSuperview()
self.delegate?.imageSwipViewDismiss(imageView: nil)
}
}
private var dataSource:[LRLPhotoBrowserModel]?
private var imgContentMode: UIViewContentMode = .scaleAspectFill
private var initialIndex: Int?
private var collectionView: LRLPBCollectionView?
private var pageControl: UIPageControl?
private var collectionDelegate: LRLPBCollectionDelegate?
private var delegateHolder: LRLPBCollectionDelegateHolder?
private var currentIndex:Int = 0
private var pageType: LRLPBCollectionViewPageType = .slide
private var pbSuperView: UIWindow?{
get{
return UIApplication.shared.keyWindow
}
}
required public init?(coder aDecoder: NSCoder) {
fatalError()
}
private func configUI() {
let myLayout = UICollectionViewFlowLayout()
myLayout.scrollDirection = .horizontal
myLayout.minimumLineSpacing = 0
myLayout.minimumInteritemSpacing = 0
collectionView = LRLPBCollectionView(frame: CGRect(x: 0, y: 0, width: self.bounds.size.width, height: self.bounds.size.height), collectionViewLayout: myLayout)
collectionView?.dismissBlock = dismissCell
collectionView?.register(LRLPBImageCell.self, forCellWithReuseIdentifier: LRLPBImageCell.reuseIdentifier())
collectionView?.register(LRLPBVideoCell.self, forCellWithReuseIdentifier: LRLPBVideoCell.reuseIdentifier())
collectionView?.panEnable = self.animition
collectionView?.isPagingEnabled = true
collectionView?.delegate = delegateHolder
collectionView?.dataSource = delegateHolder
addSubview(collectionView!)
if let index = initialIndex{
let index = IndexPath(item: index, section: 0)
collectionView?.scrollToItem(at: index, at: .centeredHorizontally, animated: false)
collectionView?.reloadData()
}
pageControl = UIPageControl()
pageControl?.numberOfPages = self.dataSource?.count ?? 0
addSubview(pageControl!)
pageControl?.addTarget(self, action: #selector(LRLPhotoBrowser.pageControlAct), for: .touchUpInside)
pageControl?.snp.makeConstraints { (make) in
make.centerX.equalTo(self)
make.leading.equalTo(self)
make.trailing.equalTo(self)
make.bottom.equalTo(self).offset(-20.0)
}
if let index = self.initialIndex {
pageControl?.currentPage = index
}
}
lazy private var dismissCell: (LRLPBCell) -> Void = { [weak self] (dissMissCell) in
guard let s = self else{
return
}
let imageView = dissMissCell.showView
func dismiss(){
imageView.removeFromSuperview()
s.removeFromSuperview()
s.delegate?.imageSwipViewDismiss(imageView: imageView.imageView)
}
imageView.removeFromSuperview()
if let localView = UIApplication.shared.keyWindow, let loc = s.selectedFrame, s.animition{
localView.addSubview(imageView)
UIView.animate(withDuration: 0.3, animations: {
imageView.transform = CGAffineTransform.identity
imageView.setZoomScale(scale: 1.0)
imageView.contentMode = UIViewContentMode.scaleAspectFill
imageView.frame = loc
s.alpha = 0.0
}, completion: { (success) in
dismiss()
})
}else{
dismiss()
}
}
@objc private func pageControlAct(page: UIPageControl){
if !(collectionView?.panning ?? true){
let indexPath = IndexPath(item: page.currentPage, section: 0)
collectionView?.scrollToItem(at: indexPath, at: .centeredHorizontally, animated: true)
hasScrollTo(index: page.currentPage)
}else{
page.currentPage = currentIndex
}
}
private func hasScrollTo(index:Int){
if let inImageView = self.delegate?.imageDidScroll(index: index){
self.selectedFrame = inImageView.superview?.convert(inImageView.frame, to: pbSuperView)
}
currentIndex = index
}
//MARK: UICollectionViewDataSource
public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
guard let data = dataSource?[indexPath.row] else { return UICollectionViewCell() }
let cell:UICollectionViewCell
switch data {
case .videoUrl(url: _, placeHolder: _):
cell = collectionView.dequeueReusableCell(withReuseIdentifier: LRLPBVideoCell.reuseIdentifier(), for: indexPath) as! LRLPBVideoCell
default:
cell = collectionView.dequeueReusableCell(withReuseIdentifier: LRLPBImageCell.reuseIdentifier(), for: indexPath) as! LRLPBImageCell
}
switch data {
case .imageName(let name):
(cell as! LRLPBImageCell).setData(imageName: name)
case .imageUrl(let imageUrl, let placeHolder):
(cell as! LRLPBImageCell).setData(imageUrl: imageUrl, placeHolder: placeHolder)
case .image(let image):
(cell as! LRLPBImageCell).setData(image: image)
case .videoUrl(url: let videoUrl, placeHolder: let image):
(cell as! LRLPBVideoCell).setData(videoUrl: videoUrl, placeHolder: image)
}
return cell
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return self.dataSource?.count ?? 0
}
//MARK: UICollectionViewDelegate
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
if let cell = collectionView.cellForItem(at: indexPath) as? LRLPBCell{
dismissCell(cell)
}
}
func collectionView(_ collectionView: UICollectionView, didEndDisplaying cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
(cell as? LRLPBCell)?.endDisplay()
}
//MARK: UICollectionViewDelegateFlowLayout
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: self.bounds.size.width, height: self.bounds.size.height)
}
//MARK:
func scrollViewDidScroll(_ scrollView: UIScrollView) {
guard pageType == .slide else {
return
}
var offset = scrollView.contentOffset.x/scrollView.bounds.width
if offset >= 0 && offset < CGFloat(self.dataSource?.count ?? 0){
let i = floor(offset)
let j = ceil(offset)
if i != offset || j != offset{
offset = offset - floor(offset)
}else{
offset = 1.0
}
if self.collectionView?.visibleCells.count ?? 0 == 2 {
let cell1 = collectionView?.cellForItem(at: IndexPath(item: Int(i), section: 0)) as? LRLPBCell
cell1?.changeTheImageViewLocationWithOffset(offset: offset)
let cell2 = collectionView?.cellForItem(at: IndexPath(item: Int(j), section: 0)) as? LRLPBCell
cell2?.changeTheImageViewLocationWithOffset(offset: offset - 1.0)
}
}
}
func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
let index = Int(scrollView.contentOffset.x/self.bounds.size.width)
self.pageControl?.currentPage = index
hasScrollTo(index: index)
}
fileprivate class LRLPBCollectionDelegateHolder: NSObject, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout{
private override init() {
fatalError()
}
init(delegate: LRLPBCollectionDelegate) {
collectionDelegate = delegate
}
fileprivate weak var collectionDelegate: LRLPBCollectionDelegate?
//MARK: UICollectionViewDataSource
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
return collectionDelegate?.collectionView(collectionView, cellForItemAt: indexPath) ?? UICollectionViewCell()
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return collectionDelegate?.collectionView(collectionView, numberOfItemsInSection: section) ?? 0
}
//MARK: UICollectionViewDelegate
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
collectionDelegate?.collectionView(collectionView, didSelectItemAt: indexPath)
}
func collectionView(_ collectionView: UICollectionView, didEndDisplaying cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
collectionDelegate?.collectionView(collectionView, didEndDisplaying: cell, forItemAt: indexPath)
}
//MARK: UICollectionViewDelegateFlowLayout
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return collectionDelegate?.collectionView(collectionView, layout: collectionViewLayout, sizeForItemAt: indexPath) ?? CGSize.zero
}
//MARK: UIScrollViewDelegate
func scrollViewDidScroll(_ scrollView: UIScrollView) {
collectionDelegate?.scrollViewDidScroll(scrollView)
}
func scrollViewDidEndDecelerating(_ scrollView: UIScrollView){
collectionDelegate?.scrollViewDidEndDecelerating(scrollView)
}
}
}
fileprivate protocol LRLPBCollectionDelegate: NSObjectProtocol{
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath)
func collectionView(_ collectionView: UICollectionView, didEndDisplaying cell: UICollectionViewCell, forItemAt indexPath: IndexPath)
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize
func scrollViewDidScroll(_ scrollView: UIScrollView)
func scrollViewDidEndDecelerating(_ scrollView: UIScrollView)
}
| mit | 52f877f6a5d87043a79c6f150efeba5a | 41.54908 | 251 | 0.666787 | 5.673211 | false | false | false | false |
lightsprint09/socket.io-client-swift | Source/SocketIO/Util/SocketStringReader.swift | 8 | 2659 | //
// SocketStringReader.swift
// Socket.IO-Client-Swift
//
// Created by Lukas Schmidt on 07.09.15.
//
// 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.
struct SocketStringReader {
let message: String
var currentIndex: String.UTF16View.Index
var hasNext: Bool {
return currentIndex != message.utf16.endIndex
}
var currentCharacter: String {
return String(UnicodeScalar(message.utf16[currentIndex])!)
}
init(message: String) {
self.message = message
currentIndex = message.utf16.startIndex
}
@discardableResult
mutating func advance(by: Int) -> String.UTF16View.Index {
currentIndex = message.utf16.index(currentIndex, offsetBy: by)
return currentIndex
}
mutating func read(count: Int) -> String {
let readString = String(message.utf16[currentIndex..<message.utf16.index(currentIndex, offsetBy: count)])!
advance(by: count)
return readString
}
mutating func readUntilOccurence(of string: String) -> String {
let substring = message.utf16[currentIndex..<message.utf16.endIndex]
guard let foundIndex = substring.index(of: string.utf16.first!) else {
currentIndex = message.utf16.endIndex
return String(substring)!
}
advance(by: substring.distance(from: substring.startIndex, to: foundIndex) + 1)
return String(substring[substring.startIndex..<foundIndex])!
}
mutating func readUntilEnd() -> String {
return read(count: message.utf16.distance(from: currentIndex, to: message.utf16.endIndex))
}
}
| apache-2.0 | 52230b3e00b75b60c2b605d061070c3f | 35.424658 | 114 | 0.703272 | 4.409619 | false | false | false | false |
jopamer/swift | test/SILGen/addressors.swift | 1 | 33960 |
// RUN: %target-swift-emit-sil -enable-sil-ownership -parse-stdlib %s | %FileCheck %s
// RUN: %target-swift-emit-silgen -enable-sil-ownership -parse-stdlib %s | %FileCheck %s -check-prefix=SILGEN
// RUN: %target-swift-emit-ir -enable-sil-ownership -parse-stdlib %s
// This test includes some calls to transparent stdlib functions.
// We pattern match for the absence of access markers in the inlined code.
// REQUIRES: optimized_stdlib
import Swift
func someValidPointer<T>() -> UnsafePointer<T> { fatalError() }
func someValidPointer<T>() -> UnsafeMutablePointer<T> { fatalError() }
struct A {
var base: UnsafeMutablePointer<Int32> = someValidPointer()
subscript(index: Int32) -> Int32 {
unsafeAddress {
return UnsafePointer(base)
}
unsafeMutableAddress {
return base
}
}
static var staticProp: Int32 {
unsafeAddress {
// Just don't trip up the verifier.
fatalError()
}
}
}
// CHECK-LABEL: sil hidden @$S10addressors1AVys5Int32VAEcilu : $@convention(method) (Int32, A) -> UnsafePointer<Int32>
// CHECK: bb0([[INDEX:%.*]] : $Int32, [[SELF:%.*]] : $A):
// CHECK: [[BASE:%.*]] = struct_extract [[SELF]] : $A, #A.base
// CHECK: [[T0:%.*]] = struct_extract [[BASE]] : $UnsafeMutablePointer<Int32>, #UnsafeMutablePointer._rawValue
// CHECK: [[T1:%.*]] = struct $UnsafePointer<Int32> ([[T0]] : $Builtin.RawPointer)
// CHECK: return [[T1]] : $UnsafePointer<Int32>
// CHECK-LABEL: sil hidden @$S10addressors1AVys5Int32VAEciau : $@convention(method) (Int32, @inout A) -> UnsafeMutablePointer<Int32>
// CHECK: bb0([[INDEX:%.*]] : $Int32, [[SELF:%.*]] : $*A):
// CHECK: [[READ:%.*]] = begin_access [read] [static] [[SELF]] : $*A
// CHECK: [[T0:%.*]] = struct_element_addr [[READ]] : $*A, #A.base
// CHECK: [[BASE:%.*]] = load [[T0]] : $*UnsafeMutablePointer<Int32>
// CHECK: return [[BASE]] : $UnsafeMutablePointer<Int32>
// CHECK-LABEL: sil hidden @$S10addressors5test0yyF : $@convention(thin) () -> () {
func test0() {
// CHECK: [[A:%.*]] = alloc_stack $A
// CHECK: [[T1:%.*]] = metatype $@thin A.Type
// CHECK: [[T0:%.*]] = function_ref @$S10addressors1AV{{[_0-9a-zA-Z]*}}fC
// CHECK: [[AVAL:%.*]] = apply [[T0]]([[T1]])
// CHECK: store [[AVAL]] to [[A]]
var a = A()
// CHECK: [[T0:%.*]] = function_ref @$S10addressors1AVys5Int32VAEcilu :
// CHECK: [[T1:%.*]] = apply [[T0]]({{%.*}}, [[AVAL]])
// CHECK: [[T2:%.*]] = struct_extract [[T1]] : $UnsafePointer<Int32>, #UnsafePointer._rawValue
// CHECK: [[T3:%.*]] = pointer_to_address [[T2]] : $Builtin.RawPointer to [strict] $*Int32
// CHECK: [[ACCESS:%.*]] = begin_access [read] [unsafe] [[T3]] : $*Int32
// CHECK: [[Z:%.*]] = load [[ACCESS]] : $*Int32
let z = a[10]
// CHECK: [[WRITE:%.*]] = begin_access [modify] [static] [[A]] : $*A
// CHECK: [[T0:%.*]] = function_ref @$S10addressors1AVys5Int32VAEciau :
// CHECK: [[T1:%.*]] = apply [[T0]]({{%.*}}, [[WRITE]])
// CHECK: [[T2:%.*]] = struct_extract [[T1]] : $UnsafeMutablePointer<Int32>, #UnsafeMutablePointer._rawValue
// CHECK: [[T3:%.*]] = pointer_to_address [[T2]] : $Builtin.RawPointer to [strict] $*Int32
// CHECK: [[ACCESS:%.*]] = begin_access [modify] [unsafe] [[T3]] : $*Int32
// CHECK: load
// CHECK: sadd_with_overflow_Int{{32|64}}
// CHECK: store {{%.*}} to [[ACCESS]]
a[5] += z
// CHECK: [[WRITE:%.*]] = begin_access [modify] [static] [[A]] : $*A
// CHECK: [[T0:%.*]] = function_ref @$S10addressors1AVys5Int32VAEciau :
// CHECK: [[T1:%.*]] = apply [[T0]]({{%.*}}, [[WRITE]])
// CHECK: [[T2:%.*]] = struct_extract [[T1]] : $UnsafeMutablePointer<Int32>, #UnsafeMutablePointer._rawValue
// CHECK: [[T3:%.*]] = pointer_to_address [[T2]] : $Builtin.RawPointer to [strict] $*Int32
// CHECK: [[ACCESS:%.*]] = begin_access [modify] [unsafe] [[T3]] : $*Int32
// CHECK: store {{%.*}} to [[ACCESS]]
a[3] = 6
}
// CHECK-LABEL: sil hidden @$S10addressors5test1s5Int32VyF : $@convention(thin) () -> Int32
func test1() -> Int32 {
// CHECK: [[T0:%.*]] = metatype $@thin A.Type
// CHECK: [[CTOR:%.*]] = function_ref @$S10addressors1AV{{[_0-9a-zA-Z]*}}fC
// CHECK: [[A:%.*]] = apply [[CTOR]]([[T0]]) : $@convention(method) (@thin A.Type) -> A
// CHECK: [[ACCESSOR:%.*]] = function_ref @$S10addressors1AVys5Int32VAEcilu : $@convention(method) (Int32, A) -> UnsafePointer<Int32>
// CHECK: [[PTR:%.*]] = apply [[ACCESSOR]]({{%.*}}, [[A]]) : $@convention(method) (Int32, A) -> UnsafePointer<Int32>
// CHECK: [[T0:%.*]] = struct_extract [[PTR]] : $UnsafePointer<Int32>, #UnsafePointer._rawValue
// CHECK: [[T1:%.*]] = pointer_to_address [[T0]] : $Builtin.RawPointer to [strict] $*Int32
// CHECK: [[ACCESS:%.*]] = begin_access [read] [unsafe] [[T1]] : $*Int32
// CHECK: [[T2:%.*]] = load [[ACCESS]] : $*Int32
// CHECK: return [[T2]] : $Int32
return A()[0]
}
let uninitAddr = UnsafeMutablePointer<Int32>.allocate(capacity: 1)
var global: Int32 {
unsafeAddress {
return UnsafePointer(uninitAddr)
}
// CHECK: sil hidden @$S10addressors6globals5Int32Vvlu : $@convention(thin) () -> UnsafePointer<Int32> {
// CHECK: [[T0:%.*]] = global_addr @$S10addressors10uninitAddrSpys5Int32VGvp : $*UnsafeMutablePointer<Int32>
// CHECK: [[T1:%.*]] = load [[T0]] : $*UnsafeMutablePointer<Int32>
// CHECK: [[T2:%.*]] = struct_extract [[T1]] : $UnsafeMutablePointer<Int32>, #UnsafeMutablePointer._rawValue
// CHECK: [[T3:%.*]] = struct $UnsafePointer<Int32> ([[T2]] : $Builtin.RawPointer)
// CHECK: return [[T3]] : $UnsafePointer<Int32>
}
func test_global() -> Int32 {
return global
}
// CHECK-LABEL: sil hidden @$S10addressors11test_globals5Int32VyF : $@convention(thin) () -> Int32 {
// CHECK: [[T0:%.*]] = function_ref @$S10addressors6globals5Int32Vvlu : $@convention(thin) () -> UnsafePointer<Int32>
// CHECK: [[T1:%.*]] = apply [[T0]]() : $@convention(thin) () -> UnsafePointer<Int32>
// CHECK: [[T2:%.*]] = struct_extract [[T1]] : $UnsafePointer<Int32>, #UnsafePointer._rawValue
// CHECK: [[T3:%.*]] = pointer_to_address [[T2]] : $Builtin.RawPointer to [strict] $*Int32
// CHECK: [[ACCESS:%.*]] = begin_access [read] [unsafe] [[T3]] : $*Int32
// CHECK: [[T4:%.*]] = load [[ACCESS]] : $*Int32
// CHECK: return [[T4]] : $Int32
// Test that having generated trivial accessors for something because
// of protocol conformance doesn't force us down inefficient access paths.
protocol Subscriptable {
subscript(i: Int32) -> Int32 { get set }
}
struct B : Subscriptable {
subscript(i: Int32) -> Int32 {
unsafeAddress { return someValidPointer() }
unsafeMutableAddress { return someValidPointer() }
}
}
// CHECK-LABEL: sil hidden @$S10addressors6test_ByyAA1BVzF : $@convention(thin) (@inout B) -> () {
// CHECK: bb0([[B:%.*]] : $*B):
// CHECK: [[T0:%.*]] = integer_literal $Builtin.Int32, 0
// CHECK: [[INDEX:%.*]] = struct $Int32 ([[T0]] : $Builtin.Int32)
// CHECK: [[RHS:%.*]] = integer_literal $Builtin.Int32, 7
// CHECK: [[WRITE:%.*]] = begin_access [modify] [static] [[B]] : $*B
// CHECK: [[T0:%.*]] = function_ref @$S10addressors1BVys5Int32VAEciau
// CHECK: [[PTR:%.*]] = apply [[T0]]([[INDEX]], [[WRITE]])
// CHECK: [[T0:%.*]] = struct_extract [[PTR]] : $UnsafeMutablePointer<Int32>,
// CHECK: [[ADDR:%.*]] = pointer_to_address [[T0]] : $Builtin.RawPointer to [strict] $*Int32
// CHECK: [[ACCESS:%.*]] = begin_access [modify] [unsafe] [[ADDR]] : $*Int32
// Accept either of struct_extract+load or load+struct_element_addr.
// CHECK: load
// CHECK: [[T1:%.*]] = builtin "or_Int32"
// CHECK: [[T2:%.*]] = struct $Int32 ([[T1]] : $Builtin.Int32)
// CHECK: store [[T2]] to [[ACCESS]] : $*Int32
func test_B(_ b: inout B) {
b[0] |= 7
}
// Test that we handle abstraction difference.
struct CArray<T> {
var storage: UnsafeMutablePointer<T>
subscript(index: Int) -> T {
unsafeAddress { return UnsafePointer(storage) + index }
unsafeMutableAddress { return storage + index }
}
}
func id_int(_ i: Int32) -> Int32 { return i }
// CHECK-LABEL: sil hidden @$S10addressors11test_carrayys5Int32VAA6CArrayVyA2DcGzF : $@convention(thin) (@inout CArray<(Int32) -> Int32>) -> Int32 {
// CHECK: bb0([[ARRAY:%.*]] : $*CArray<(Int32) -> Int32>):
func test_carray(_ array: inout CArray<(Int32) -> Int32>) -> Int32 {
// CHECK: [[WRITE:%.*]] = begin_access [modify] [static] [[ARRAY]] : $*CArray<(Int32) -> Int32>
// CHECK: [[T0:%.*]] = function_ref @$S10addressors6CArrayVyxSiciau :
// CHECK: [[T1:%.*]] = apply [[T0]]<(Int32) -> Int32>({{%.*}}, [[WRITE]])
// CHECK: [[T2:%.*]] = struct_extract [[T1]] : $UnsafeMutablePointer<(Int32) -> Int32>, #UnsafeMutablePointer._rawValue
// CHECK: [[T3:%.*]] = pointer_to_address [[T2]] : $Builtin.RawPointer to [strict] $*@callee_guaranteed (@in_guaranteed Int32) -> @out Int32
// CHECK: [[ACCESS:%.*]] = begin_access [modify] [unsafe] [[T3]] : $*@callee_guaranteed (@in_guaranteed Int32) -> @out Int32
// CHECK: store {{%.*}} to [[ACCESS]] :
array[0] = id_int
// CHECK: [[READ:%.*]] = begin_access [read] [static] [[ARRAY]] : $*CArray<(Int32) -> Int32>
// CHECK: [[T0:%.*]] = load [[READ]]
// CHECK: [[T1:%.*]] = function_ref @$S10addressors6CArrayVyxSicilu :
// CHECK: [[T2:%.*]] = apply [[T1]]<(Int32) -> Int32>({{%.*}}, [[T0]])
// CHECK: [[T3:%.*]] = struct_extract [[T2]] : $UnsafePointer<(Int32) -> Int32>, #UnsafePointer._rawValue
// CHECK: [[T4:%.*]] = pointer_to_address [[T3]] : $Builtin.RawPointer to [strict] $*@callee_guaranteed (@in_guaranteed Int32) -> @out Int32
// CHECK: [[ACCESS:%.*]] = begin_access [read] [unsafe] [[T4]] : $*@callee_guaranteed (@in_guaranteed Int32) -> @out Int32
// CHECK: [[T5:%.*]] = load [[ACCESS]]
return array[1](5)
}
// rdar://17270560, redux
struct D : Subscriptable {
subscript(i: Int32) -> Int32 {
get { return i }
unsafeMutableAddress { return someValidPointer() }
}
}
// Setter.
// SILGEN-LABEL: sil hidden [transparent] @$S10addressors1DVys5Int32VAEcis
// SILGEN: bb0([[VALUE:%.*]] : @trivial $Int32, [[I:%.*]] : @trivial $Int32, [[SELF:%.*]] : @trivial $*D):
// SILGEN: debug_value [[VALUE]] : $Int32
// SILGEN: debug_value [[I]] : $Int32
// SILGEN: debug_value_addr [[SELF]]
// SILGEN: [[ACCESS:%.*]] = begin_access [modify] [unknown] [[SELF]] : $*D
// SILGEN: [[T0:%.*]] = function_ref @$S10addressors1DVys5Int32VAEciau{{.*}}
// SILGEN: [[PTR:%.*]] = apply [[T0]]([[I]], [[ACCESS]])
// SILGEN: [[T0:%.*]] = struct_extract [[PTR]] : $UnsafeMutablePointer<Int32>,
// SILGEN: [[ADDR:%.*]] = pointer_to_address [[T0]] : $Builtin.RawPointer to [strict] $*Int32
// SILGEN: [[ACCESS:%.*]] = begin_access [modify] [unsafe] [[ADDR]] : $*Int32
// SILGEN: assign [[VALUE]] to [[ACCESS]] : $*Int32
// materializeForSet.
// SILGEN-LABEL: sil hidden [transparent] @$S10addressors1DVys5Int32VAEcim
// SILGEN: bb0([[BUFFER:%.*]] : @trivial $Builtin.RawPointer, [[STORAGE:%.*]] : @trivial $*Builtin.UnsafeValueBuffer, [[I:%.*]] : @trivial $Int32, [[SELF:%.*]] : @trivial $*D):
// SILGEN: [[T0:%.*]] = function_ref @$S10addressors1DVys5Int32VAEciau
// SILGEN: [[PTR:%.*]] = apply [[T0]]([[I]], [[SELF]])
// SILGEN: [[ADDR_TMP:%.*]] = struct_extract [[PTR]] : $UnsafeMutablePointer<Int32>,
// SILGEN: [[ADDR:%.*]] = pointer_to_address [[ADDR_TMP]]
// SILGEN: [[PTR:%.*]] = address_to_pointer [[ADDR]]
// SILGEN: [[OPT:%.*]] = enum $Optional<Builtin.RawPointer>, #Optional.none!enumelt
// SILGEN: [[T2:%.*]] = tuple ([[PTR]] : $Builtin.RawPointer, [[OPT]] : $Optional<Builtin.RawPointer>)
// SILGEN: return [[T2]] :
func make_int() -> Int32 { return 0 }
func take_int_inout(_ value: inout Int32) {}
// CHECK-LABEL: sil hidden @$S10addressors6test_dys5Int32VAA1DVzF : $@convention(thin) (@inout D) -> Int32
// CHECK: bb0([[ARRAY:%.*]] : $*D):
func test_d(_ array: inout D) -> Int32 {
// CHECK: [[T0:%.*]] = function_ref @$S10addressors8make_ints5Int32VyF
// CHECK: [[V:%.*]] = apply [[T0]]()
// CHECK: [[WRITE:%.*]] = begin_access [modify] [static] [[ARRAY]] : $*D
// CHECK: [[T0:%.*]] = function_ref @$S10addressors1DVys5Int32VAEciau
// CHECK: [[T1:%.*]] = apply [[T0]]({{%.*}}, [[WRITE]])
// CHECK: [[T2:%.*]] = struct_extract [[T1]] : $UnsafeMutablePointer<Int32>,
// CHECK: [[ADDR:%.*]] = pointer_to_address [[T2]] : $Builtin.RawPointer to [strict] $*Int32
// CHECK: [[ACCESS:%.*]] = begin_access [modify] [unsafe] [[ADDR]] : $*Int32
// CHECK: store [[V]] to [[ACCESS]] : $*Int32
array[0] = make_int()
// CHECK: [[WRITE:%.*]] = begin_access [modify] [static] [[ARRAY]] : $*D
// CHECK: [[T0:%.*]] = function_ref @$S10addressors1DVys5Int32VAEciau
// CHECK: [[T1:%.*]] = apply [[T0]]({{%.*}}, [[WRITE]])
// CHECK: [[T2:%.*]] = struct_extract [[T1]] : $UnsafeMutablePointer<Int32>,
// CHECK: [[ADDR:%.*]] = pointer_to_address [[T2]] : $Builtin.RawPointer to [strict] $*Int32
// CHECK: [[ACCESS:%.*]] = begin_access [modify] [unsafe] [[ADDR]] : $*Int32
// CHECK: [[FN:%.*]] = function_ref @$S10addressors14take_int_inoutyys5Int32VzF
// CHECK: apply [[FN]]([[ACCESS]])
take_int_inout(&array[1])
// CHECK: [[READ:%.*]] = begin_access [read] [static] [[ARRAY]] : $*D
// CHECK: [[T0:%.*]] = load [[READ]]
// CHECK: [[T1:%.*]] = function_ref @$S10addressors1DVys5Int32VAEcig
// CHECK: [[T2:%.*]] = apply [[T1]]({{%.*}}, [[T0]])
// CHECK: return [[T2]]
return array[2]
}
struct E {
var value: Int32 {
unsafeAddress { return someValidPointer() }
nonmutating unsafeMutableAddress { return someValidPointer() }
}
}
// CHECK-LABEL: sil hidden @$S10addressors6test_eyyAA1EVF
// CHECK: bb0([[E:%.*]] : $E):
// CHECK: [[T0:%.*]] = function_ref @$S10addressors1EV5values5Int32Vvau
// CHECK: [[T1:%.*]] = apply [[T0]]([[E]])
// CHECK: [[T2:%.*]] = struct_extract [[T1]]
// CHECK: [[T3:%.*]] = pointer_to_address [[T2]]
// CHECK: [[ACCESS:%.*]] = begin_access [modify] [unsafe] [[T3]] : $*Int32
// CHECK: store {{%.*}} to [[ACCESS]] : $*Int32
func test_e(_ e: E) {
e.value = 0
}
class F {
var data: UnsafeMutablePointer<Int32> = UnsafeMutablePointer.allocate(capacity: 100)
final var value: Int32 {
addressWithNativeOwner {
return (UnsafePointer(data), Builtin.castToNativeObject(self))
}
mutableAddressWithNativeOwner {
return (data, Builtin.castToNativeObject(self))
}
}
}
// CHECK-LABEL: sil hidden @$S10addressors1FC5values5Int32Vvlo : $@convention(method) (@guaranteed F) -> (UnsafePointer<Int32>, @owned Builtin.NativeObject) {
// CHECK-LABEL: sil hidden @$S10addressors1FC5values5Int32Vvao : $@convention(method) (@guaranteed F) -> (UnsafeMutablePointer<Int32>, @owned Builtin.NativeObject) {
func test_f0(_ f: F) -> Int32 {
return f.value
}
// CHECK-LABEL: sil hidden @$S10addressors7test_f0ys5Int32VAA1FCF : $@convention(thin) (@guaranteed F) -> Int32 {
// CHECK: bb0([[SELF:%0]] : $F):
// CHECK: [[ADDRESSOR:%.*]] = function_ref @$S10addressors1FC5values5Int32Vvlo : $@convention(method) (@guaranteed F) -> (UnsafePointer<Int32>, @owned Builtin.NativeObject)
// CHECK: [[T0:%.*]] = apply [[ADDRESSOR]]([[SELF]])
// CHECK: [[PTR:%.*]] = tuple_extract [[T0]] : $(UnsafePointer<Int32>, Builtin.NativeObject), 0
// CHECK: [[OWNER:%.*]] = tuple_extract [[T0]] : $(UnsafePointer<Int32>, Builtin.NativeObject), 1
// CHECK: [[T0:%.*]] = struct_extract [[PTR]]
// CHECK: [[T1:%.*]] = pointer_to_address [[T0]] : $Builtin.RawPointer to [strict] $*Int32
// CHECK: [[T2:%.*]] = mark_dependence [[T1]] : $*Int32 on [[OWNER]] : $Builtin.NativeObject
// CHECK: [[ACCESS:%.*]] = begin_access [read] [unsafe] [[T2]] : $*Int32
// CHECK: [[VALUE:%.*]] = load [[ACCESS]] : $*Int32
// CHECK: strong_release [[OWNER]] : $Builtin.NativeObject
// CHECK-NOT: strong_release [[SELF]] : $F
// CHECK: return [[VALUE]] : $Int32
func test_f1(_ f: F) {
f.value = 14
}
// CHECK-LABEL: sil hidden @$S10addressors7test_f1yyAA1FCF : $@convention(thin) (@guaranteed F) -> () {
// CHECK: bb0([[SELF:%0]] : $F):
// CHECK: [[T0:%.*]] = integer_literal $Builtin.Int32, 14
// CHECK: [[VALUE:%.*]] = struct $Int32 ([[T0]] : $Builtin.Int32)
// CHECK: [[ADDRESSOR:%.*]] = function_ref @$S10addressors1FC5values5Int32Vvao : $@convention(method) (@guaranteed F) -> (UnsafeMutablePointer<Int32>, @owned Builtin.NativeObject)
// CHECK: [[T0:%.*]] = apply [[ADDRESSOR]]([[SELF]])
// CHECK: [[PTR:%.*]] = tuple_extract [[T0]] : $(UnsafeMutablePointer<Int32>, Builtin.NativeObject), 0
// CHECK: [[OWNER:%.*]] = tuple_extract [[T0]] : $(UnsafeMutablePointer<Int32>, Builtin.NativeObject), 1
// CHECK: [[T0:%.*]] = struct_extract [[PTR]]
// CHECK: [[T1:%.*]] = pointer_to_address [[T0]] : $Builtin.RawPointer to [strict] $*Int32
// CHECK: [[T2:%.*]] = mark_dependence [[T1]] : $*Int32 on [[OWNER]] : $Builtin.NativeObject
// CHECK: [[ACCESS:%.*]] = begin_access [modify] [unsafe] [[T2]] : $*Int32
// CHECK: store [[VALUE]] to [[ACCESS]] : $*Int32
// CHECK: strong_release [[OWNER]] : $Builtin.NativeObject
// CHECK-NOT: strong_release [[SELF]] : $F
class G {
var data: UnsafeMutablePointer<Int32> = UnsafeMutablePointer.allocate(capacity: 100)
var value: Int32 {
addressWithNativeOwner {
return (UnsafePointer(data), Builtin.castToNativeObject(self))
}
mutableAddressWithNativeOwner {
return (data, Builtin.castToNativeObject(self))
}
}
}
// CHECK-LABEL: sil hidden [transparent] @$S10addressors1GC5values5Int32Vvg : $@convention(method) (@guaranteed G) -> Int32 {
// CHECK: bb0([[SELF:%0]] : $G):
// CHECK: [[ADDRESSOR:%.*]] = function_ref @$S10addressors1GC5values5Int32Vvlo : $@convention(method) (@guaranteed G) -> (UnsafePointer<Int32>, @owned Builtin.NativeObject)
// CHECK: [[T0:%.*]] = apply [[ADDRESSOR]]([[SELF]])
// CHECK: [[PTR:%.*]] = tuple_extract [[T0]] : $(UnsafePointer<Int32>, Builtin.NativeObject), 0
// CHECK: [[OWNER:%.*]] = tuple_extract [[T0]] : $(UnsafePointer<Int32>, Builtin.NativeObject), 1
// CHECK: [[T0:%.*]] = struct_extract [[PTR]]
// CHECK: [[T1:%.*]] = pointer_to_address [[T0]] : $Builtin.RawPointer to [strict] $*Int32
// CHECK: [[T2:%.*]] = mark_dependence [[T1]] : $*Int32 on [[OWNER]] : $Builtin.NativeObject
// CHECK: [[ACCESS:%.*]] = begin_access [read] [unsafe] [[T2]] : $*Int32
// CHECK: [[VALUE:%.*]] = load [[ACCESS]] : $*Int32
// CHECK: strong_release [[OWNER]] : $Builtin.NativeObject
// CHECK: return [[VALUE]] : $Int32
// CHECK-LABEL: sil hidden [transparent] @$S10addressors1GC5values5Int32Vvs : $@convention(method) (Int32, @guaranteed G) -> () {
// CHECK: bb0([[VALUE:%0]] : $Int32, [[SELF:%1]] : $G):
// CHECK: [[ADDRESSOR:%.*]] = function_ref @$S10addressors1GC5values5Int32Vvao : $@convention(method) (@guaranteed G) -> (UnsafeMutablePointer<Int32>, @owned Builtin.NativeObject)
// CHECK: [[T0:%.*]] = apply [[ADDRESSOR]]([[SELF]])
// CHECK: [[PTR:%.*]] = tuple_extract [[T0]] : $(UnsafeMutablePointer<Int32>, Builtin.NativeObject), 0
// CHECK: [[OWNER:%.*]] = tuple_extract [[T0]] : $(UnsafeMutablePointer<Int32>, Builtin.NativeObject), 1
// CHECK: [[T0:%.*]] = struct_extract [[PTR]]
// CHECK: [[T1:%.*]] = pointer_to_address [[T0]] : $Builtin.RawPointer to [strict] $*Int32
// CHECK: [[T2:%.*]] = mark_dependence [[T1]] : $*Int32 on [[OWNER]] : $Builtin.NativeObject
// CHECK: [[ACCESS:%.*]] = begin_access [modify] [unsafe] [[T2]] : $*Int32
// CHECK: store [[VALUE]] to [[ACCESS]] : $*Int32
// CHECK: strong_release [[OWNER]] : $Builtin.NativeObject
// materializeForSet callback for G.value
// CHECK-LABEL: sil private [transparent] @$S10addressors1GC5values5Int32VvmytfU_ : $@convention(method) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @in_guaranteed G, @thick G.Type) -> () {
// CHECK: bb0([[BUFFER:%0]] : $Builtin.RawPointer, [[STORAGE:%1]] : $*Builtin.UnsafeValueBuffer, [[SELF:%2]] : $*G, [[SELFTYPE:%3]] : $@thick G.Type):
// CHECK: [[T0:%.*]] = project_value_buffer $Builtin.NativeObject in [[STORAGE]] : $*Builtin.UnsafeValueBuffer
// CHECK: [[OWNER:%.*]] = load [[T0]]
// CHECK: strong_release [[OWNER]] : $Builtin.NativeObject
// CHECK: dealloc_value_buffer $Builtin.NativeObject in [[STORAGE]] : $*Builtin.UnsafeValueBuffer
// materializeForSet for G.value
// CHECK-LABEL: sil hidden [transparent] @$S10addressors1GC5values5Int32Vvm : $@convention(method) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @guaranteed G) -> (Builtin.RawPointer, Optional<Builtin.RawPointer>) {
// CHECK: bb0([[BUFFER:%0]] : $Builtin.RawPointer, [[STORAGE:%1]] : $*Builtin.UnsafeValueBuffer, [[SELF:%2]] : $G):
// Call the addressor.
// CHECK: [[ADDRESSOR:%.*]] = function_ref @$S10addressors1GC5values5Int32Vvao : $@convention(method) (@guaranteed G) -> (UnsafeMutablePointer<Int32>, @owned Builtin.NativeObject)
// CHECK: [[T0:%.*]] = apply [[ADDRESSOR]]([[SELF]])
// CHECK: [[T1:%.*]] = tuple_extract [[T0]] : $(UnsafeMutablePointer<Int32>, Builtin.NativeObject), 0
// CHECK: [[T2:%.*]] = tuple_extract [[T0]] : $(UnsafeMutablePointer<Int32>, Builtin.NativeObject), 1
// Get the address.
// CHECK: [[PTR:%.*]] = struct_extract [[T1]] : $UnsafeMutablePointer<Int32>, #UnsafeMutablePointer._rawValue
// CHECK: [[ADDR_TMP:%.*]] = pointer_to_address [[PTR]]
// CHECK: [[ADDR:%.*]] = mark_dependence [[ADDR_TMP]] : $*Int32 on [[T2]]
// Initialize the callback storage with the owner.
// CHECK: [[T0:%.*]] = alloc_value_buffer $Builtin.NativeObject in [[STORAGE]] : $*Builtin.UnsafeValueBuffer
// CHECK: store [[T2]] to [[T0]] : $*Builtin.NativeObject
// CHECK: [[PTR:%.*]] = address_to_pointer [[ADDR]]
// Set up the callback.
// CHECK: [[CALLBACK_FN:%.*]] = function_ref @$S10addressors1GC5values5Int32VvmytfU_ :
// CHECK: [[CALLBACK_ADDR:%.*]] = thin_function_to_pointer [[CALLBACK_FN]]
// CHECK: [[CALLBACK:%.*]] = enum $Optional<Builtin.RawPointer>, #Optional.some!enumelt.1, [[CALLBACK_ADDR]]
// Epilogue.
// CHECK: [[RESULT:%.*]] = tuple ([[PTR]] : $Builtin.RawPointer, [[CALLBACK]] : $Optional<Builtin.RawPointer>)
// CHECK: return [[RESULT]]
class H {
var data: UnsafeMutablePointer<Int32> = UnsafeMutablePointer.allocate(capacity: 100)
final var value: Int32 {
addressWithPinnedNativeOwner {
return (UnsafePointer(data), Builtin.tryPin(Builtin.castToNativeObject(self)))
}
mutableAddressWithPinnedNativeOwner {
return (data, Builtin.tryPin(Builtin.castToNativeObject(self)))
}
}
}
// CHECK-LABEL: sil hidden @$S10addressors1HC5values5Int32Vvlp : $@convention(method) (@guaranteed H) -> (UnsafePointer<Int32>, @owned Optional<Builtin.NativeObject>) {
// CHECK-LABEL: sil hidden @$S10addressors1HC5values5Int32VvaP : $@convention(method) (@guaranteed H) -> (UnsafeMutablePointer<Int32>, @owned Optional<Builtin.NativeObject>) {
func test_h0(_ f: H) -> Int32 {
return f.value
}
// CHECK-LABEL: sil hidden @$S10addressors7test_h0ys5Int32VAA1HCF : $@convention(thin) (@guaranteed H) -> Int32 {
// CHECK: bb0([[SELF:%0]] : $H):
// CHECK: [[ADDRESSOR:%.*]] = function_ref @$S10addressors1HC5values5Int32Vvlp : $@convention(method) (@guaranteed H) -> (UnsafePointer<Int32>, @owned Optional<Builtin.NativeObject>)
// CHECK: [[T0:%.*]] = apply [[ADDRESSOR]]([[SELF]])
// CHECK: [[PTR:%.*]] = tuple_extract [[T0]] : $(UnsafePointer<Int32>, Optional<Builtin.NativeObject>), 0
// CHECK: [[OWNER:%.*]] = tuple_extract [[T0]] : $(UnsafePointer<Int32>, Optional<Builtin.NativeObject>), 1
// CHECK: [[T0:%.*]] = struct_extract [[PTR]]
// CHECK: [[T1:%.*]] = pointer_to_address [[T0]] : $Builtin.RawPointer to [strict] $*Int32
// CHECK: [[T2:%.*]] = mark_dependence [[T1]] : $*Int32 on [[OWNER]] : $Optional<Builtin.NativeObject>
// CHECK: [[ACCESS:%.*]] = begin_access [read] [unsafe] [[T2]] : $*Int32
// CHECK: [[VALUE:%.*]] = load [[ACCESS]] : $*Int32
// CHECK: strong_unpin [[OWNER]] : $Optional<Builtin.NativeObject>
// CHECK-NOT: strong_release [[SELF]] : $H
// CHECK: return [[VALUE]] : $Int32
func test_h1(_ f: H) {
f.value = 14
}
// CHECK-LABEL: sil hidden @$S10addressors7test_h1yyAA1HCF : $@convention(thin) (@guaranteed H) -> () {
// CHECK: bb0([[SELF:%0]] : $H):
// CHECK: [[T0:%.*]] = integer_literal $Builtin.Int32, 14
// CHECK: [[VALUE:%.*]] = struct $Int32 ([[T0]] : $Builtin.Int32)
// CHECK: [[ADDRESSOR:%.*]] = function_ref @$S10addressors1HC5values5Int32VvaP : $@convention(method) (@guaranteed H) -> (UnsafeMutablePointer<Int32>, @owned Optional<Builtin.NativeObject>)
// CHECK: [[T0:%.*]] = apply [[ADDRESSOR]]([[SELF]])
// CHECK: [[PTR:%.*]] = tuple_extract [[T0]] : $(UnsafeMutablePointer<Int32>, Optional<Builtin.NativeObject>), 0
// CHECK: [[OWNER:%.*]] = tuple_extract [[T0]] : $(UnsafeMutablePointer<Int32>, Optional<Builtin.NativeObject>), 1
// CHECK: [[T0:%.*]] = struct_extract [[PTR]]
// CHECK: [[T1:%.*]] = pointer_to_address [[T0]] : $Builtin.RawPointer to [strict] $*Int32
// CHECK: [[T2:%.*]] = mark_dependence [[T1]] : $*Int32 on [[OWNER]] : $Optional<Builtin.NativeObject>
// CHECK: [[ACCESS:%.*]] = begin_access [modify] [unsafe] [[T2]] : $*Int32
// CHECK: store [[VALUE]] to [[ACCESS]] : $*Int32
// CHECK: strong_unpin [[OWNER]] : $Optional<Builtin.NativeObject>
// CHECK-NOT: strong_release [[SELF]] : $H
class I {
var data: UnsafeMutablePointer<Int32> = UnsafeMutablePointer.allocate(capacity: 100)
var value: Int32 {
addressWithPinnedNativeOwner {
return (UnsafePointer(data), Builtin.tryPin(Builtin.castToNativeObject(self)))
}
mutableAddressWithPinnedNativeOwner {
return (data, Builtin.tryPin(Builtin.castToNativeObject(self)))
}
}
}
// CHECK-LABEL: sil hidden [transparent] @$S10addressors1IC5values5Int32Vvg : $@convention(method) (@guaranteed I) -> Int32 {
// CHECK: bb0([[SELF:%0]] : $I):
// CHECK: [[ADDRESSOR:%.*]] = function_ref @$S10addressors1IC5values5Int32Vvlp : $@convention(method) (@guaranteed I) -> (UnsafePointer<Int32>, @owned Optional<Builtin.NativeObject>)
// CHECK: [[T0:%.*]] = apply [[ADDRESSOR]]([[SELF]])
// CHECK: [[PTR:%.*]] = tuple_extract [[T0]] : $(UnsafePointer<Int32>, Optional<Builtin.NativeObject>), 0
// CHECK: [[OWNER:%.*]] = tuple_extract [[T0]] : $(UnsafePointer<Int32>, Optional<Builtin.NativeObject>), 1
// CHECK: [[T0:%.*]] = struct_extract [[PTR]]
// CHECK: [[T1:%.*]] = pointer_to_address [[T0]] : $Builtin.RawPointer to [strict] $*Int32
// CHECK: [[T2:%.*]] = mark_dependence [[T1]] : $*Int32 on [[OWNER]] : $Optional<Builtin.NativeObject>
// CHECK: [[ACCESS:%.*]] = begin_access [read] [unsafe] [[T2]] : $*Int32
// CHECK: [[VALUE:%.*]] = load [[ACCESS]] : $*Int32
// CHECK: strong_unpin [[OWNER]] : $Optional<Builtin.NativeObject>
// CHECK: return [[VALUE]] : $Int32
// CHECK-LABEL: sil hidden [transparent] @$S10addressors1IC5values5Int32Vvs : $@convention(method) (Int32, @guaranteed I) -> () {
// CHECK: bb0([[VALUE:%0]] : $Int32, [[SELF:%1]] : $I):
// CHECK: [[ADDRESSOR:%.*]] = function_ref @$S10addressors1IC5values5Int32VvaP : $@convention(method) (@guaranteed I) -> (UnsafeMutablePointer<Int32>, @owned Optional<Builtin.NativeObject>)
// CHECK: [[T0:%.*]] = apply [[ADDRESSOR]]([[SELF]])
// CHECK: [[PTR:%.*]] = tuple_extract [[T0]] : $(UnsafeMutablePointer<Int32>, Optional<Builtin.NativeObject>), 0
// CHECK: [[OWNER:%.*]] = tuple_extract [[T0]] : $(UnsafeMutablePointer<Int32>, Optional<Builtin.NativeObject>), 1
// CHECK: [[T0:%.*]] = struct_extract [[PTR]]
// CHECK: [[T1:%.*]] = pointer_to_address [[T0]] : $Builtin.RawPointer to [strict] $*Int32
// CHECK: [[T2:%.*]] = mark_dependence [[T1]] : $*Int32 on [[OWNER]] : $Optional<Builtin.NativeObject>
// CHECK: [[ACCESS:%.*]] = begin_access [modify] [unsafe] [[T2]] : $*Int32
// CHECK: store [[VALUE]] to [[ACCESS]] : $*Int32
// CHECK: strong_unpin [[OWNER]] : $Optional<Builtin.NativeObject>
// materializeForSet callback for I.value
// CHECK-LABEL: sil private [transparent] @$S10addressors1IC5values5Int32VvmytfU_ : $@convention(method) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @in_guaranteed I, @thick I.Type) -> () {
// CHECK: bb0([[BUFFER:%0]] : $Builtin.RawPointer, [[STORAGE:%1]] : $*Builtin.UnsafeValueBuffer, [[SELF:%2]] : $*I, [[SELFTYPE:%3]] : $@thick I.Type):
// CHECK: [[T0:%.*]] = project_value_buffer $Optional<Builtin.NativeObject> in [[STORAGE]] : $*Builtin.UnsafeValueBuffer
// CHECK: [[OWNER:%.*]] = load [[T0]]
// CHECK: strong_unpin [[OWNER]] : $Optional<Builtin.NativeObject>
// CHECK: dealloc_value_buffer $Optional<Builtin.NativeObject> in [[STORAGE]] : $*Builtin.UnsafeValueBuffer
// CHECK-LABEL: sil hidden [transparent] @$S10addressors1IC5values5Int32Vvm : $@convention(method) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @guaranteed I) -> (Builtin.RawPointer, Optional<Builtin.RawPointer>) {
// CHECK: bb0([[BUFFER:%0]] : $Builtin.RawPointer, [[STORAGE:%1]] : $*Builtin.UnsafeValueBuffer, [[SELF:%2]] : $I):
// Call the addressor.
// CHECK: [[ADDRESSOR:%.*]] = function_ref @$S10addressors1IC5values5Int32VvaP : $@convention(method) (@guaranteed I) -> (UnsafeMutablePointer<Int32>, @owned Optional<Builtin.NativeObject>)
// CHECK: [[T0:%.*]] = apply [[ADDRESSOR]]([[SELF]])
// CHECK: [[T1:%.*]] = tuple_extract [[T0]] : $(UnsafeMutablePointer<Int32>, Optional<Builtin.NativeObject>), 0
// CHECK: [[T2:%.*]] = tuple_extract [[T0]] : $(UnsafeMutablePointer<Int32>, Optional<Builtin.NativeObject>), 1
// Pull out the address.
// CHECK: [[PTR:%.*]] = struct_extract [[T1]] : $UnsafeMutablePointer<Int32>, #UnsafeMutablePointer._rawValue
// CHECK: [[ADDR_TMP:%.*]] = pointer_to_address [[PTR]]
// CHECK: [[ADDR:%.*]] = mark_dependence [[ADDR_TMP]] : $*Int32 on [[T2]]
// Initialize the callback storage with the owner.
// CHECK: [[T0:%.*]] = alloc_value_buffer $Optional<Builtin.NativeObject> in [[STORAGE]] : $*Builtin.UnsafeValueBuffer
// CHECK: store [[T2]] to [[T0]] : $*Optional<Builtin.NativeObject>
// CHECK: [[PTR:%.*]] = address_to_pointer [[ADDR]]
// Set up the callback.
// CHECK: [[CALLBACK_FN:%.*]] = function_ref @$S10addressors1IC5values5Int32VvmytfU_ :
// CHECK: [[CALLBACK_ADDR:%.*]] = thin_function_to_pointer [[CALLBACK_FN]]
// CHECK: [[CALLBACK:%.*]] = enum $Optional<Builtin.RawPointer>, #Optional.some!enumelt.1, [[CALLBACK_ADDR]]
// Epilogue.
// CHECK: [[RESULT:%.*]] = tuple ([[PTR]] : $Builtin.RawPointer, [[CALLBACK]] : $Optional<Builtin.RawPointer>)
// CHECK: return [[RESULT]]
struct RecInner {
subscript(i: Int32) -> Int32 {
mutating get { return i }
}
}
struct RecMiddle {
var inner: RecInner
}
class RecOuter {
var data: UnsafeMutablePointer<RecMiddle> = UnsafeMutablePointer.allocate(capacity: 100)
final var middle: RecMiddle {
addressWithPinnedNativeOwner {
return (UnsafePointer(data), Builtin.tryPin(Builtin.castToNativeObject(self)))
}
mutableAddressWithPinnedNativeOwner {
return (data, Builtin.tryPin(Builtin.castToNativeObject(self)))
}
}
}
func test_rec(_ outer: RecOuter) -> Int32 {
return outer.middle.inner[0]
}
// This uses the mutable addressor.
// CHECK-LABEL: sil hidden @$S10addressors8test_recys5Int32VAA8RecOuterCF : $@convention(thin) (@guaranteed RecOuter) -> Int32 {
// CHECK: function_ref @$S10addressors8RecOuterC6middleAA0B6MiddleVvaP
// CHECK: struct_element_addr {{.*}} : $*RecMiddle, #RecMiddle.inner
// CHECK: function_ref @$S10addressors8RecInnerVys5Int32VAEcig
class Base {
var data: UnsafeMutablePointer<Int32> = UnsafeMutablePointer.allocate(capacity: 100)
var value: Int32 {
addressWithNativeOwner {
return (UnsafePointer(data), Builtin.castToNativeObject(self))
}
mutableAddressWithNativeOwner {
return (data, Builtin.castToNativeObject(self))
}
}
}
class Sub : Base {
override var value: Int32 {
addressWithNativeOwner {
return (UnsafePointer(data), Builtin.castToNativeObject(self))
}
mutableAddressWithNativeOwner {
return (data, Builtin.castToNativeObject(self))
}
}
}
// Make sure addressors don't get vtable entries.
// CHECK-LABEL: sil_vtable Base {
// CHECK-NEXT: #Base.data!getter.1: (Base) -> () -> UnsafeMutablePointer<Int32> : @$S10addressors4BaseC4dataSpys5Int32VGvg
// CHECK-NEXT: #Base.data!setter.1: (Base) -> (UnsafeMutablePointer<Int32>) -> () : @$S10addressors4BaseC4dataSpys5Int32VGvs
// CHECK-NEXT: #Base.data!materializeForSet.1: (Base) -> (Builtin.RawPointer, inout Builtin.UnsafeValueBuffer) -> (Builtin.RawPointer, Builtin.RawPointer?) : @$S10addressors4BaseC4dataSpys5Int32VGvm
// CHECK-NEXT: #Base.value!getter.1: (Base) -> () -> Int32 : @$S10addressors4BaseC5values5Int32Vvg
// CHECK-NEXT: #Base.value!setter.1: (Base) -> (Int32) -> () : @$S10addressors4BaseC5values5Int32Vvs
// CHECK-NEXT: #Base.value!materializeForSet.1: (Base) -> (Builtin.RawPointer, inout Builtin.UnsafeValueBuffer) -> (Builtin.RawPointer, Builtin.RawPointer?) : @$S10addressors4BaseC5values5Int32Vvm
// CHECK-NEXT: #Base.init!initializer.1: (Base.Type) -> () -> Base : @$S10addressors4BaseCACycfc
// CHECK-NEXT: #Base.deinit!deallocator.1: @$S10addressors4BaseCfD
// CHECK-NEXT: }
// CHECK-LABEL: sil_vtable Sub {
// CHECK-NEXT: #Base.data!getter.1: (Base) -> () -> UnsafeMutablePointer<Int32> : @$S10addressors4BaseC4dataSpys5Int32VGvg
// CHECK-NEXT: #Base.data!setter.1: (Base) -> (UnsafeMutablePointer<Int32>) -> () : @$S10addressors4BaseC4dataSpys5Int32VGvs
// CHECK-NEXT: #Base.data!materializeForSet.1: (Base) -> (Builtin.RawPointer, inout Builtin.UnsafeValueBuffer) -> (Builtin.RawPointer, Builtin.RawPointer?) : @$S10addressors4BaseC4dataSpys5Int32VGvm
// CHECK-NEXT: #Base.value!getter.1: (Base) -> () -> Int32 : @$S10addressors3SubC5values5Int32Vvg
// CHECK-NEXT: #Base.value!setter.1: (Base) -> (Int32) -> () : @$S10addressors3SubC5values5Int32Vvs
// CHECK-NEXT: #Base.value!materializeForSet.1: (Base) -> (Builtin.RawPointer, inout Builtin.UnsafeValueBuffer) -> (Builtin.RawPointer, Builtin.RawPointer?) : @$S10addressors3SubC5values5Int32Vvm
// CHECK-NEXT: #Base.init!initializer.1: (Base.Type) -> () -> Base : @$S10addressors3SubCACycfc
// CHECK-NEXT: #Sub.deinit!deallocator.1: @$S10addressors3SubCfD
// CHECK-NEXT: }
| apache-2.0 | e176999cd62b10a5ccf2d38ec65cce97 | 55.41196 | 224 | 0.634717 | 3.340876 | false | false | false | false |
caicai0/ios_demo | load/thirdpart/SwiftSoup/DocumentType.swift | 4 | 4306 | //
// DocumentType.swift
// SwifSoup
//
// Created by Nabil Chatbi on 29/09/16.
// Copyright © 2016 Nabil Chatbi.. All rights reserved.
//
import Foundation
/**
* A {@code <!DOCTYPE>} node.
*/
public class DocumentType: Node {
static let PUBLIC_KEY: String = "PUBLIC"
static let SYSTEM_KEY: String = "SYSTEM";
private static let NAME: String = "name"
private static let PUB_SYS_KEY: String = "pubSysKey"; // PUBLIC or SYSTEM
private static let PUBLIC_ID: String = "publicId"
private static let SYSTEM_ID: String = "systemId"
// todo: quirk mode from publicId and systemId
/**
* Create a new doctype element.
* @param name the doctype's name
* @param publicId the doctype's public ID
* @param systemId the doctype's system ID
* @param baseUri the doctype's base URI
*/
public init(_ name: String, _ publicId: String, _ systemId: String, _ baseUri: String) {
super.init(baseUri)
do {
try attr(DocumentType.NAME, name);
try attr(DocumentType.PUBLIC_ID, publicId);
if (has(DocumentType.PUBLIC_ID)) {
try attr(DocumentType.PUB_SYS_KEY, DocumentType.PUBLIC_KEY);
}
try attr(DocumentType.SYSTEM_ID, systemId);
} catch {}
}
/**
* Create a new doctype element.
* @param name the doctype's name
* @param publicId the doctype's public ID
* @param systemId the doctype's system ID
* @param baseUri the doctype's base URI
*/
public init(_ name: String, _ pubSysKey: String?, _ publicId: String, _ systemId: String, _ baseUri: String) {
super.init(baseUri)
do {
try attr(DocumentType.NAME, name)
if(pubSysKey != nil){
try attr(DocumentType.PUB_SYS_KEY, pubSysKey!)
}
try attr(DocumentType.PUBLIC_ID, publicId);
try attr(DocumentType.SYSTEM_ID, systemId);
} catch {}
}
public override func nodeName() -> String {
return "#doctype"
}
override func outerHtmlHead(_ accum: StringBuilder, _ depth: Int, _ out: OutputSettings) {
if (out.syntax() == OutputSettings.Syntax.html && !has(DocumentType.PUBLIC_ID) && !has(DocumentType.SYSTEM_ID)) {
// looks like a html5 doctype, go lowercase for aesthetics
accum.append("<!doctype")
} else {
accum.append("<!DOCTYPE")
}
if (has(DocumentType.NAME)) {
do {
accum.append(" ").append(try attr(DocumentType.NAME))
} catch {}
}
if (has(DocumentType.PUB_SYS_KEY)){
do {
try accum.append(" ").append(attr(DocumentType.PUB_SYS_KEY))
} catch {}
}
if (has(DocumentType.PUBLIC_ID)) {
do {
try accum.append(" \"").append(attr(DocumentType.PUBLIC_ID)).append("\"");
} catch {}
}
if (has(DocumentType.SYSTEM_ID)) {
do {
accum.append(" \"").append(try attr(DocumentType.SYSTEM_ID)).append("\"")
} catch {}
}
accum.append(">")
}
override func outerHtmlTail(_ accum: StringBuilder, _ depth: Int, _ out: OutputSettings) {
}
private func has(_ attribute: String) -> Bool {
do {
return !StringUtil.isBlank(try attr(attribute))
} catch {return false}
}
public override func copy(with zone: NSZone? = nil) -> Any {
let clone = DocumentType(attributes!.get(key: DocumentType.NAME),
attributes!.get(key: DocumentType.PUBLIC_ID),
attributes!.get(key: DocumentType.SYSTEM_ID),
baseUri!)
return copy(clone: clone)
}
public override func copy(parent: Node?) -> Node {
let clone = DocumentType(attributes!.get(key: DocumentType.NAME),
attributes!.get(key: DocumentType.PUBLIC_ID),
attributes!.get(key: DocumentType.SYSTEM_ID),
baseUri!)
return copy(clone: clone, parent: parent)
}
public override func copy(clone: Node, parent: Node?) -> Node {
return super.copy(clone: clone, parent: parent)
}
}
| mit | 83e5e11e954f94deb55e0af66c809bd3 | 31.368421 | 121 | 0.563995 | 4.283582 | false | false | false | false |
itsaboutcode/WordPress-iOS | WordPress/Classes/ViewRelated/Media/MediaPreviewHelper.swift | 2 | 3175 |
import Foundation
import WPMediaPicker
/// This class is intended to be used with WPMediaPicker delegate `mediaPickerController(_:previewViewControllerFor:selectedIndex:)`
/// making this implementation reusable with all the instances of the media picker.
///
class MediaPreviewHelper: NSObject {
let assets: [WPMediaAsset]
init(assets: [WPMediaAsset]) {
self.assets = assets
super.init()
}
/// Return a controller to show the given assets.
///
/// - Parameters:
/// - selected: The selected index to be displayed by default.
/// - Returns: The controller to be displayed or nil if the asset is not an image.
func previewViewController(selectedIndex selected: Int) -> UIViewController? {
guard assets.count > 0, selected < assets.endIndex else {
return nil
}
if assets.count > 1 {
return carouselController(with: assets, selectedIndex: selected)
}
let selectedAsset = assets[selected]
return self.viewController(for: selectedAsset)
}
private func carouselController(with assets: [WPMediaAsset], selectedIndex selected: Int) -> UIViewController {
let carouselViewController = WPCarouselAssetsViewController(assets: assets)
carouselViewController.setPreviewingAssetAt(selected, animated: false)
carouselViewController.carouselDelegate = self
return carouselViewController
}
fileprivate func imageViewController(with mediaAsset: Media) -> UIViewController {
let imageController = WPImageViewController(media: mediaAsset)
imageController.shouldDismissWithGestures = false
return imageController
}
private func viewController(for asset: WPMediaAsset) -> UIViewController? {
guard asset.assetType() == .image else {
return nil
}
if let mediaAsset = asset as? Media {
return imageViewController(with: mediaAsset)
} else if let phasset = asset as? PHAsset {
let imageController = WPImageViewController(asset: phasset)
imageController.shouldDismissWithGestures = false
return imageController
} else if let mediaAsset = asset as? MediaExternalAsset {
let imageController = WPImageViewController(externalMediaURL: mediaAsset.URL,
andAsset: asset)
imageController.shouldDismissWithGestures = false
return imageController
}
return nil
}
}
extension MediaPreviewHelper: WPCarouselAssetsViewControllerDelegate {
func carouselController(_ controller: WPCarouselAssetsViewController, viewControllerFor asset: WPMediaAsset) -> UIViewController? {
return viewController(for: asset)
}
func carouselController(_ controller: WPCarouselAssetsViewController, assetFor viewController: UIViewController) -> WPMediaAsset {
guard
let imageViewController = viewController as? WPImageViewController,
let asset = imageViewController.mediaAsset else {
fatalError()
}
return asset
}
}
| gpl-2.0 | d521ef923b24a2a8662f883853d05dab | 37.253012 | 135 | 0.678425 | 5.815018 | false | false | false | false |
src256/libswift | libswift/Classes/DateUtils.swift | 1 | 599 | //
// DateUtils.swift
// Pods
//
// Created by sora on 2016/11/04.
//
//
import Foundation
public class DateUtils {
public static func create(year:Int, month:Int, day:Int, hour:Int = 0, minute:Int = 0, second:Int = 0, nanosecond:Int = 0)-> Date? {
var components = DateComponents()
components.year = year
components.month = month
components.day = day
components.hour = hour
components.minute = minute
components.second = second
components.nanosecond = nanosecond
return Calendar.current.date(from: components)
}
}
| mit | 79ef3bf5497d068b71d6ae1109c458b3 | 25.043478 | 135 | 0.631052 | 3.993333 | false | false | false | false |
abertelrud/swift-package-manager | Fixtures/Miscellaneous/Plugins/MyBuildToolPluginDependencies/Plugins/MySourceGenBuildToolPlugin/plugin.swift | 2 | 1568 | import PackagePlugin
@main
struct MyPlugin: BuildToolPlugin {
// Create build commands that don't invoke the MySourceGenBuildTool source generator
// tool directly, but instead invoke a system tool that invokes it indirectly. We
// want to test that we still end up with a dependency on not only that tool but also
// on the library it depends on, even without including an explicit dependency on it.
func createBuildCommands(context: PluginContext, target: Target) throws -> [Command] {
print("Hello from the Build Tool Plugin!")
guard let target = target as? SourceModuleTarget else { return [] }
let inputFiles = target.sourceFiles.filter({ $0.path.extension == "dat" })
return try inputFiles.map {
let inputFile = $0
let inputPath = inputFile.path
let outputName = inputPath.stem + ".swift"
let outputPath = context.pluginWorkDirectory.appending(outputName)
return .buildCommand(
displayName:
"Generating \(outputName) from \(inputPath.lastComponent)",
executable:
Path("/usr/bin/env"),
arguments: [
try context.tool(named: "MySourceGenBuildTool").path,
"\(inputPath)",
"\(outputPath)"
],
inputFiles: [
inputPath,
],
outputFiles: [
outputPath
]
)
}
}
}
| apache-2.0 | bccc14df4501538b62e5127ebe3f15fb | 40.263158 | 90 | 0.561224 | 5.6 | false | false | false | false |
Incipia/Goalie | PaintCode/ComputerAccessoryKit.swift | 1 | 9777 | //
// ComputerAccessoryKit.swift
// Goalie
//
// Created by Gregory Klein on 3/28/16.
// Copyright © 2016 Incipia. All rights reserved.
//
import Foundation
class ComputerAccessoryKit: AccessoryItemDrawing
{
static func drawWithFrame(_ frame: CGRect, priority: TaskPriority)
{
//// General Declarations
let context = UIGraphicsGetCurrentContext()
//// Color Declarations
let primaryColor = UIColor(priority: priority, headComponent: .background)
//// Subframes
let group: CGRect = CGRect(x: frame.minX, y: frame.minY, width: frame.width, height: frame.height)
//// Group
//// Bezier 2 Drawing
let bezier2Path = UIBezierPath()
bezier2Path.move(to: CGPoint(x: group.minX + 0.80714 * group.width, y: group.minY + 0.84615 * group.height))
bezier2Path.addLine(to: CGPoint(x: group.minX + 0.19286 * group.width, y: group.minY + 0.84615 * group.height))
bezier2Path.addLine(to: CGPoint(x: group.minX + 0.19240 * group.width, y: group.minY + 0.17513 * group.height))
bezier2Path.addLine(to: CGPoint(x: group.minX + 0.80760 * group.width, y: group.minY + 0.17513 * group.height))
bezier2Path.addLine(to: CGPoint(x: group.minX + 0.80714 * group.width, y: group.minY + 0.84615 * group.height))
bezier2Path.close()
bezier2Path.move(to: CGPoint(x: group.minX + 0.08571 * group.width, y: group.minY + 0.10257 * group.height))
bezier2Path.addLine(to: CGPoint(x: group.minX + 0.08571 * group.width, y: group.minY + 0.84621 * group.height))
bezier2Path.addLine(to: CGPoint(x: group.minX + 0.91429 * group.width, y: group.minY + 0.84621 * group.height))
bezier2Path.addLine(to: CGPoint(x: group.minX + 0.91429 * group.width, y: group.minY + 0.10257 * group.height))
bezier2Path.addCurve(to: CGPoint(x: group.minX + 0.85714 * group.width, y: group.minY + 0.00000 * group.height), controlPoint1: CGPoint(x: group.minX + 0.91429 * group.width, y: group.minY + 0.04590 * group.height), controlPoint2: CGPoint(x: group.minX + 0.88870 * group.width, y: group.minY + 0.00000 * group.height))
bezier2Path.addLine(to: CGPoint(x: group.minX + 0.14286 * group.width, y: group.minY + 0.00000 * group.height))
bezier2Path.addCurve(to: CGPoint(x: group.minX + 0.08571 * group.width, y: group.minY + 0.10257 * group.height), controlPoint1: CGPoint(x: group.minX + 0.11130 * group.width, y: group.minY + 0.00000 * group.height), controlPoint2: CGPoint(x: group.minX + 0.08571 * group.width, y: group.minY + 0.04590 * group.height))
bezier2Path.close()
primaryColor.setFill()
bezier2Path.fill()
//// Rectangle Drawing
let rectanglePath = UIBezierPath(rect: CGRect(x: group.minX + floor(group.width * 0.31429 + 0.5), y: group.minY + floor(group.height * 0.43595 - 0.5) + 1, width: floor(group.width * 0.68571 + 0.5) - floor(group.width * 0.31429 + 0.5), height: floor(group.height * 0.74365 - 0.5) - floor(group.height * 0.43595 - 0.5)))
primaryColor.setFill()
rectanglePath.fill()
//// Group 2
context!.saveGState()
context!.setAlpha(0.4)
context!.beginTransparencyLayer(auxiliaryInfo: nil)
//// Bezier Drawing
let bezierPath = UIBezierPath()
bezierPath.move(to: CGPoint(x: group.minX + 0.91429 * group.width, y: group.minY + 1.00000 * group.height))
bezierPath.addLine(to: CGPoint(x: group.minX + 0.08571 * group.width, y: group.minY + 1.00000 * group.height))
bezierPath.addCurve(to: CGPoint(x: group.minX + 0.00000 * group.width, y: group.minY + 0.84615 * group.height), controlPoint1: CGPoint(x: group.minX + 0.03837 * group.width, y: group.minY + 1.00000 * group.height), controlPoint2: CGPoint(x: group.minX + 0.00000 * group.width, y: group.minY + 0.93113 * group.height))
bezierPath.addLine(to: CGPoint(x: group.minX + 0.00000 * group.width, y: group.minY + 0.84615 * group.height))
bezierPath.addLine(to: CGPoint(x: group.minX + 1.00000 * group.width, y: group.minY + 0.84615 * group.height))
bezierPath.addLine(to: CGPoint(x: group.minX + 1.00000 * group.width, y: group.minY + 0.84615 * group.height))
bezierPath.addCurve(to: CGPoint(x: group.minX + 0.91429 * group.width, y: group.minY + 1.00000 * group.height), controlPoint1: CGPoint(x: group.minX + 1.00000 * group.width, y: group.minY + 0.93113 * group.height), controlPoint2: CGPoint(x: group.minX + 0.96163 * group.width, y: group.minY + 1.00000 * group.height))
bezierPath.close()
primaryColor.setFill()
bezierPath.fill()
//// Bezier 3 Drawing
let bezier3Path = UIBezierPath()
bezier3Path.move(to: CGPoint(x: group.minX + 0.44286 * group.width, y: group.minY + 0.41029 * group.height))
bezier3Path.addCurve(to: CGPoint(x: group.minX + 0.42857 * group.width, y: group.minY + 0.38465 * group.height), controlPoint1: CGPoint(x: group.minX + 0.43497 * group.width, y: group.minY + 0.41029 * group.height), controlPoint2: CGPoint(x: group.minX + 0.42857 * group.width, y: group.minY + 0.39880 * group.height))
bezier3Path.addCurve(to: CGPoint(x: group.minX + 0.44286 * group.width, y: group.minY + 0.35901 * group.height), controlPoint1: CGPoint(x: group.minX + 0.42857 * group.width, y: group.minY + 0.37050 * group.height), controlPoint2: CGPoint(x: group.minX + 0.43497 * group.width, y: group.minY + 0.35901 * group.height))
bezier3Path.addCurve(to: CGPoint(x: group.minX + 0.45714 * group.width, y: group.minY + 0.38465 * group.height), controlPoint1: CGPoint(x: group.minX + 0.45074 * group.width, y: group.minY + 0.35901 * group.height), controlPoint2: CGPoint(x: group.minX + 0.45714 * group.width, y: group.minY + 0.37050 * group.height))
bezier3Path.addCurve(to: CGPoint(x: group.minX + 0.44286 * group.width, y: group.minY + 0.41029 * group.height), controlPoint1: CGPoint(x: group.minX + 0.45714 * group.width, y: group.minY + 0.39880 * group.height), controlPoint2: CGPoint(x: group.minX + 0.45074 * group.width, y: group.minY + 0.41029 * group.height))
bezier3Path.close()
bezier3Path.move(to: CGPoint(x: group.minX + 0.40000 * group.width, y: group.minY + 0.41029 * group.height))
bezier3Path.addCurve(to: CGPoint(x: group.minX + 0.38571 * group.width, y: group.minY + 0.38465 * group.height), controlPoint1: CGPoint(x: group.minX + 0.39211 * group.width, y: group.minY + 0.41029 * group.height), controlPoint2: CGPoint(x: group.minX + 0.38571 * group.width, y: group.minY + 0.39880 * group.height))
bezier3Path.addCurve(to: CGPoint(x: group.minX + 0.40000 * group.width, y: group.minY + 0.35901 * group.height), controlPoint1: CGPoint(x: group.minX + 0.38571 * group.width, y: group.minY + 0.37050 * group.height), controlPoint2: CGPoint(x: group.minX + 0.39211 * group.width, y: group.minY + 0.35901 * group.height))
bezier3Path.addCurve(to: CGPoint(x: group.minX + 0.41428 * group.width, y: group.minY + 0.38465 * group.height), controlPoint1: CGPoint(x: group.minX + 0.40788 * group.width, y: group.minY + 0.35901 * group.height), controlPoint2: CGPoint(x: group.minX + 0.41428 * group.width, y: group.minY + 0.37050 * group.height))
bezier3Path.addCurve(to: CGPoint(x: group.minX + 0.40000 * group.width, y: group.minY + 0.41029 * group.height), controlPoint1: CGPoint(x: group.minX + 0.41428 * group.width, y: group.minY + 0.39880 * group.height), controlPoint2: CGPoint(x: group.minX + 0.40788 * group.width, y: group.minY + 0.41029 * group.height))
bezier3Path.close()
bezier3Path.move(to: CGPoint(x: group.minX + 0.35714 * group.width, y: group.minY + 0.41029 * group.height))
bezier3Path.addCurve(to: CGPoint(x: group.minX + 0.34286 * group.width, y: group.minY + 0.38465 * group.height), controlPoint1: CGPoint(x: group.minX + 0.34926 * group.width, y: group.minY + 0.41029 * group.height), controlPoint2: CGPoint(x: group.minX + 0.34286 * group.width, y: group.minY + 0.39880 * group.height))
bezier3Path.addCurve(to: CGPoint(x: group.minX + 0.35714 * group.width, y: group.minY + 0.35901 * group.height), controlPoint1: CGPoint(x: group.minX + 0.34286 * group.width, y: group.minY + 0.37050 * group.height), controlPoint2: CGPoint(x: group.minX + 0.34926 * group.width, y: group.minY + 0.35901 * group.height))
bezier3Path.addCurve(to: CGPoint(x: group.minX + 0.37143 * group.width, y: group.minY + 0.38465 * group.height), controlPoint1: CGPoint(x: group.minX + 0.36503 * group.width, y: group.minY + 0.35901 * group.height), controlPoint2: CGPoint(x: group.minX + 0.37143 * group.width, y: group.minY + 0.37050 * group.height))
bezier3Path.addCurve(to: CGPoint(x: group.minX + 0.35714 * group.width, y: group.minY + 0.41029 * group.height), controlPoint1: CGPoint(x: group.minX + 0.37143 * group.width, y: group.minY + 0.39880 * group.height), controlPoint2: CGPoint(x: group.minX + 0.36503 * group.width, y: group.minY + 0.41029 * group.height))
bezier3Path.close()
bezier3Path.move(to: CGPoint(x: group.minX + 0.31428 * group.width, y: group.minY + 0.43593 * group.height))
bezier3Path.addLine(to: CGPoint(x: group.minX + 0.68571 * group.width, y: group.minY + 0.43593 * group.height))
bezier3Path.addLine(to: CGPoint(x: group.minX + 0.68571 * group.width, y: group.minY + 0.33337 * group.height))
bezier3Path.addLine(to: CGPoint(x: group.minX + 0.31428 * group.width, y: group.minY + 0.33337 * group.height))
bezier3Path.addLine(to: CGPoint(x: group.minX + 0.31428 * group.width, y: group.minY + 0.43593 * group.height))
bezier3Path.close()
primaryColor.setFill()
bezier3Path.fill()
context!.endTransparencyLayer()
context!.restoreGState()
}
}
| apache-2.0 | e27a34ff2d5e0ab0c687ec6c62f9c7e4 | 91.226415 | 324 | 0.675123 | 3.182292 | false | false | false | false |
mlibai/XZKit | Projects/Example/XZKitExample/XZKitExample/XZKitExample/Code/UIImage+XZKit/ImageTestViewController.swift | 1 | 2177 | //
// ImageTestViewController.swift
// XZKit_Example
//
// Created by mlibai on 2017/10/31.
// Copyright © 2017年 mlibai. All rights reserved.
//
import UIKit
import XZKit
class ImageTestCell: UICollectionViewCell {
@IBOutlet var imageView: UIImageView!
}
class ImageTestViewController: UICollectionViewController {
var colors: [UIColor] = [
.black, .darkGray, .lightGray, .white,
.gray, .red, .green, .blue,
.cyan, .yellow, .magenta, .orange,
.purple, .brown
]
override func viewDidLoad() {
super.viewDidLoad()
// self.navigationBar.title = "UIImage"
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func numberOfSections(in collectionView: UICollectionView) -> Int {
return 3;
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return colors.count;
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: Foundation.IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! ImageTestCell
switch indexPath.section {
case 0:
cell.imageView.image = UIImage.init(filled: colors[indexPath.row]);
case 1:
cell.imageView.image = UIImage.init(filled: colors[indexPath.row], borderColor: UIColor.init(0x59c8d5ff))
default:
cell.imageView.image = UIImage.init(filled: colors[indexPath.row], borderColor: UIColor.red, cornerRadius: 20)
}
return cell
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| mit | 987627c4b9c2d22ecd5f8f24f0f5cf13 | 28.780822 | 141 | 0.653634 | 4.799117 | false | true | false | false |
CD1212/Doughnut | DoughnutTests/LibraryTests/LibraryTestsWithSubscription.swift | 1 | 6241 | //
// LibraryTestsWithSubscription.swift
// DoughnutTests
//
// Created by Chris Dyer on 13/10/2017.
// Copyright © 2017 Chris Dyer. All rights reserved.
//
import XCTest
import Doughnut
import GRDB
class LibraryTestsWithSubscription: LibraryTestCase {
var library: Library?
var sub: Podcast?
override func setUp() {
super.setUp()
// Setup an initial podcast subscription
let expectation = self.expectation(description: "Library has subscribed")
let spy = LibrarySpyDelegate()
Library.global.delegate = spy
spy.subscribedToPodcastExpectation = expectation
Library.global.subscribe(url: fixtureURL("ValidFeed", type: "xml").absoluteString)
self.waitForExpectations(timeout: 10) { error in
self.sub = spy.subscribedToPodcastResult
}
}
func testReloadWhenNoNewEpisodesExist() {
XCTAssertEqual(sub!.episodes.count, 2)
let spy = LibrarySpyDelegate()
Library.global.delegate = spy
spy.updatedPodcastExpectation = self.expectation(description: "Library updated podcast")
Library.global.reload(podcast: sub!)
self.waitForExpectations(timeout: 10) { error in
guard let podcast = spy.updatedPodcastResult else {
XCTFail("Expected delegate to be called")
return
}
XCTAssertEqual(podcast.episodes.count, 2)
}
}
func testReloadWhenNewEpisodesExist() {
XCTAssertEqual(sub!.episodes.count, 2)
let spy = LibrarySpyDelegate()
Library.global.delegate = spy
spy.updatedPodcastExpectation = self.expectation(description: "Library updated podcast")
// Silently change podcast feed
sub!.feed = fixtureURL("ValidFeedx3", type: "xml").absoluteString
do {
try Library.global.dbQueue?.inDatabase { db in
try sub!.save(db)
}
} catch {}
Library.global.reload(podcast: sub!)
self.waitForExpectations(timeout: 10) { error in
guard let podcast = spy.updatedPodcastResult else {
XCTFail("Expected delegate to be called")
return
}
XCTAssertEqual(podcast.episodes.count, 3)
// Ensure new episodes are linked back to podcast
do {
try Library.global.dbQueue?.inDatabase({ db in
try XCTAssertEqual(Episode.filter(Column("podcast_id") == podcast.id).fetchCount(db), 3)
})
} catch {
XCTFail()
}
}
}
func testUnsubscribeLeaveDownloads() {
guard let podcast = sub else { XCTFail(); return }
guard let storagePath = podcast.storagePath() else { XCTFail(); return }
let spy = LibrarySpyDelegate()
Library.global.delegate = spy
spy.unsubscribedPodcastExpectation = self.expectation(description: "Library unsubscribed podcast")
XCTAssertEqual(Library.global.podcasts.contains(where: { p -> Bool in
p.id == podcast.id
}), true)
var isDir = ObjCBool(true)
XCTAssertEqual(FileManager.default.fileExists(atPath: storagePath.path, isDirectory: &isDir), true)
Library.global.unsubscribe(podcast: podcast)
self.waitForExpectations(timeout: 10) { error in
XCTAssertEqual(Library.global.podcasts.count, 0)
do {
try Library.global.dbQueue?.inDatabase { db in
let podcastCount = try Podcast.fetchCount(db)
XCTAssertEqual(podcastCount, 0)
}
} catch {
XCTFail()
}
XCTAssertEqual(FileManager.default.fileExists(atPath: storagePath.path, isDirectory: &isDir), true)
}
}
func testUnsubscribeRemoveDownloads() {
guard let podcast = sub else { XCTFail(); return }
guard let storagePath = podcast.storagePath() else { XCTFail(); return }
let spy = LibrarySpyDelegate()
Library.global.delegate = spy
spy.unsubscribedPodcastExpectation = self.expectation(description: "Library unsubscribed podcast")
XCTAssertEqual(Library.global.podcasts.contains(where: { p -> Bool in
p.id == podcast.id
}), true)
var isDir = ObjCBool(true)
XCTAssertEqual(FileManager.default.fileExists(atPath: storagePath.path, isDirectory: &isDir), true)
Library.global.unsubscribe(podcast: podcast, removeFiles: true)
self.waitForExpectations(timeout: 10) { error in
XCTAssertEqual(Library.global.podcasts.count, 0)
do {
try Library.global.dbQueue?.inDatabase { db in
let podcastCount = try Podcast.fetchCount(db)
XCTAssertEqual(podcastCount, 0)
}
} catch {
XCTFail()
}
sleep(1)
XCTAssertEqual(FileManager.default.fileExists(atPath: storagePath.path, isDirectory: &isDir), false)
}
}
func testSavePodcast() {
guard let podcast = sub else { XCTFail(); return }
let spy = LibrarySpyDelegate()
Library.global.delegate = spy
spy.updatedPodcastExpectation = self.expectation(description: "Library updated podcast")
podcast.title = "This is the new title"
Library.global.save(podcast: podcast)
self.waitForExpectations(timeout: 10) { error in
XCTAssertEqual(Library.global.podcasts.first?.title, "This is the new title")
do {
try Library.global.dbQueue?.inDatabase { db in
let updated = try Podcast.fetchOne(db)
XCTAssertEqual(updated?.title, "This is the new title")
}
} catch {
XCTFail()
}
}
}
func testSaveEpisode() {
guard let episode = sub?.episodes.first else { XCTFail(); return }
let spy = LibrarySpyDelegate()
Library.global.delegate = spy
spy.updatedPodcastExpectation = self.expectation(description: "Library updated episode")
episode.title = "This is the new episode"
Library.global.save(episode: episode)
self.waitForExpectations(timeout: 10) { error in
XCTAssertEqual(Library.global.podcasts.first?.episodes.first?.title, "This is the new episode")
do {
try Library.global.dbQueue?.inDatabase { db in
let updated = try Episode.filter(Column("id") == episode.id).fetchOne(db)
XCTAssertEqual(updated?.title, "This is the new episode")
}
} catch {
XCTFail()
}
}
}
}
| gpl-3.0 | d2ff87021af63ffdd149489475d0d7da | 30.044776 | 106 | 0.657532 | 4.62908 | false | true | false | false |
MattesGroeger/BrightFutures | BrightFutures/ExecutionContext.swift | 4 | 2680 | // The MIT License (MIT)
//
// Copyright (c) 2014 Thomas Visser
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
import Foundation
/// The context in which something can be executed
/// By default, an execution context can be assumed to be asynchronous unless stated otherwise
public typealias ExecutionContext = (() -> Void) -> Void
/// Immediately executes the given task. No threading, no semaphores.
public let ImmediateExecutionContext: ExecutionContext = { task in
task()
}
/// Runs immediately if on the main thread, otherwise asynchronously on the main thread
public let ImmediateOnMainExecutionContext: ExecutionContext = { task in
if NSThread.isMainThread() {
task()
} else {
Queue.main.async(task)
}
}
/// Creates an asynchronous ExecutionContext bound to the given queue
public func toContext(queue: Queue) -> ExecutionContext {
return queue.context
}
/// Creates an asynchronous ExecutionContext bound to the given queue
public func toContext(queue: dispatch_queue_t) -> ExecutionContext {
return Queue(queue: queue).context
}
/// Creates a synchronous context that is guarded by the given semaphore
func toContext(sema: Semaphore) -> ExecutionContext {
return sema.execute
}
typealias ThreadingModel = () -> ExecutionContext
var DefaultThreadingModel: ThreadingModel = defaultContext
/// Defines BrightFutures' default threading behavior:
/// - if on the main thread, `Queue.main.context` is returned
/// - if off the main thread, `Queue.global.context` is returned
func defaultContext() -> ExecutionContext {
return toContext(NSThread.isMainThread() ? Queue.main : Queue.global)
} | mit | 64be66f4cf5d53f77548f47a42cfa489 | 38.426471 | 94 | 0.754104 | 4.685315 | false | false | false | false |
itsaboutcode/WordPress-iOS | WordPress/Classes/ViewRelated/Tools/SettingsListEditorViewController.swift | 1 | 6186 | import Foundation
import WordPressShared
/// The purpose of this class is to render an interface that allows the user to Insert / Edit / Delete
/// a set of strings.
///
open class SettingsListEditorViewController: UITableViewController {
// MARK: - Public Properties
@objc open var footerText: String?
@objc open var emptyText: String?
@objc open var insertTitle: String?
@objc open var editTitle: String?
@objc open var onChange: ((Set<String>) -> Void)?
// MARK: - Initialiers
@objc public convenience init(collection: Set<String>?) {
self.init(style: .grouped)
emptyText = NSLocalizedString("No Items", comment: "List Editor Empty State Message")
if let unwrappedCollection = collection?.sorted() as [String]? {
rows.addObjects(from: unwrappedCollection)
}
}
// MARK: - View Lifecycle
open override func viewDidLoad() {
super.viewDidLoad()
setupNavBar()
setupTableView()
}
// MARK: - Helpers
fileprivate func notifyDidChange() {
let orderedRows = Set<String>(rows.array as! [String])
onChange?(orderedRows)
}
// MARK: - Setup Helpers
fileprivate func setupNavBar() {
navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .add,
target: self,
action: #selector(SettingsListEditorViewController.addItemPressed(_:)))
}
fileprivate func setupTableView() {
tableView.register(WPTableViewCell.self, forCellReuseIdentifier: reuseIdentifier)
WPStyleGuide.configureColors(view: view, tableView: tableView)
}
// MARK: - Button Handlers
@IBAction func addItemPressed(_ sender: AnyObject?) {
let settingsViewController = SettingsTextViewController(text: nil, placeholder: nil, hint: nil)
settingsViewController.title = insertTitle
settingsViewController.onValueChanged = { (updatedValue: String!) in
self.insertString(updatedValue)
self.notifyDidChange()
self.tableView.reloadData()
}
navigationController?.pushViewController(settingsViewController, animated: true)
}
// MARK: - UITableViewDataSoutce Methods
open override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
open override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// Note:
// We'll always render, at least, one row, with the Empty State text
return max(rows.count, 1)
}
open override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: reuseIdentifier)!
WPStyleGuide.configureTableViewCell(cell)
cell.accessoryType = isEmpty() ? .none : .disclosureIndicator
cell.textLabel?.text = isEmpty() ? emptyText : stringAtIndexPath(indexPath)
cell.textLabel?.textColor = isEmpty() ? .neutral(.shade10) : .neutral(.shade70)
return cell
}
open override func tableView(_ tableView: UITableView, titleForFooterInSection section: Int) -> String? {
return footerText
}
open override func tableView(_ tableView: UITableView, willDisplayFooterView view: UIView, forSection section: Int) {
WPStyleGuide.configureTableViewSectionFooter(view)
}
open override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectSelectedRowWithAnimation(true)
// Empty State
if isEmpty() {
addItemPressed(nil)
return
}
// Edit!
let oldText = stringAtIndexPath(indexPath)
let settingsViewController = SettingsTextViewController(text: oldText, placeholder: nil, hint: nil)
settingsViewController.title = editTitle
settingsViewController.onValueChanged = { (newText: String!) in
self.replaceString(oldText, newText: newText)
self.notifyDidChange()
self.tableView.reloadData()
}
navigationController?.pushViewController(settingsViewController, animated: true)
}
open override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
return isEmpty() == false
}
open override func tableView(_ tableView: UITableView,
editingStyleForRowAt indexPath: IndexPath) -> UITableViewCell.EditingStyle {
return .delete
}
open override func tableView(_ tableView: UITableView,
commit editingStyle: UITableViewCell.EditingStyle,
forRowAt indexPath: IndexPath) {
// Nuke it from the collection
removeAtIndexPath(indexPath)
notifyDidChange()
// Empty State: We'll always render a single row, indicating that there are no items
if isEmpty() {
tableView.reloadRows(at: [indexPath], with: .fade)
} else {
tableView.deleteRows(at: [indexPath], with: .fade)
}
}
// MARK: - Helpers
fileprivate func stringAtIndexPath(_ indexPath: IndexPath) -> String {
return rows.object(at: indexPath.row) as! String
}
fileprivate func removeAtIndexPath(_ indexPath: IndexPath) {
rows.removeObject(at: indexPath.row)
}
fileprivate func insertString(_ newText: String) {
if newText.isEmpty {
return
}
rows.add(newText)
sortStrings()
}
fileprivate func replaceString(_ oldText: String, newText: String) {
if oldText == newText {
return
}
insertString(newText)
rows.remove(oldText)
}
fileprivate func sortStrings() {
self.rows.sort (comparator: { ($0 as! String).compare($1 as! String) })
}
fileprivate func isEmpty() -> Bool {
return rows.count == 0
}
// MARK: - Constants
fileprivate let reuseIdentifier = "WPTableViewCell"
// MARK: - Properties
fileprivate var rows = NSMutableOrderedSet()
}
| gpl-2.0 | ffac5e5b29366841fa304dfb760c9202 | 30.085427 | 121 | 0.649208 | 5.346586 | false | false | false | false |
TellMeAMovieTeam/TellMeAMovie_iOSApp | TellMeAMovie/Pods/TMDBSwift/Sources/Models/CompaniesMDB.swift | 1 | 2120 | //
// CompaniesMDB.swift
// MDBSwiftWrapper
//
// Created by George Kye on 2016-02-11.
// Copyright © 2016 George KyeKye. All rights reserved.
//
import Foundation
public struct parent_companymdb: ArrayObject{
public var name: String!
public var id: Int!
public var logo_path: String!
public init(results: JSON){
name = results["name"].string
id = results["id"].int
logo_path = results["logo_path"].string
}
}
open class CompanyMDB {
open var description: String?
open var headquarters: String?
open var homepage: String!
open var id: Int!
open var logo_path: String!
open var name: String!
open var parent_company: parent_companymdb?
public init(results: JSON){
description = results["description"].string
headquarters = results["headquarters"].string
homepage = results["homepage"].string
id = results["id"].int
logo_path = results["logo_path"].string
name = results["name"].string
if(results["parent_company"].count > 0){
parent_company = parent_companymdb.init(results: results["parent_company"])
}
}
///This method is used to retrieve all of the basic information about a company.
open class func companyInfo(_ api_key: String!, companyId: Int!, completion: @escaping (_ clientReturn: ClientReturn, _ data:CompanyMDB?) -> ()) -> (){
Client.Company(api_key, companyId: companyId){
apiReturn in
if(apiReturn.error == nil){
completion(apiReturn, CompanyMDB(results: apiReturn.json!))
}else{
completion(apiReturn, nil)
}
}
}
///Get the list of movies associated with a particular company.
open class func companyMovies(_ api_key: String!, companyId: Int!, language: String?, page: Int?, completion: @escaping (_ clientReturn: ClientReturn, _ data: [MovieMDB]?) -> ()) -> (){
Client.Company(api_key, companyId: companyId, language: language, page: page){
apiReturn in
if(apiReturn.error == nil){
completion(apiReturn, MovieMDB.initialize(json: apiReturn.json!["results"]))
}else{
completion(apiReturn, nil)
}
}
}
}
| apache-2.0 | 255179b6f548b0777733a546bb738693 | 31.6 | 187 | 0.664936 | 4.028517 | false | false | false | false |
vector-im/vector-ios | Riot/Managers/Serialization/SerializationService.swift | 2 | 1385 | /*
Copyright 2019 New Vector Ltd
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import Foundation
final class SerializationService: SerializationServiceType {
// MARK: - Properties
private let decoder = JSONDecoder()
private let encoder = JSONEncoder()
// MARK: - Public
func deserialize<T: Decodable>(_ data: Data) throws -> T {
return try decoder.decode(T.self, from: data)
}
func deserialize<T: Decodable>(_ object: Any) throws -> T {
let jsonData: Data
if let data = object as? Data {
jsonData = data
} else {
jsonData = try JSONSerialization.data(withJSONObject: object, options: [])
}
return try decoder.decode(T.self, from: jsonData)
}
func serialize<T: Encodable>(_ object: T) throws -> Data {
return try encoder.encode(object)
}
}
| apache-2.0 | be0a34284a74b64f50fc47b97cb09597 | 28.468085 | 86 | 0.66787 | 4.616667 | false | false | false | false |
powerytg/Accented | Accented/UI/Home/Themes/ThemeSelector/ThemeSelectorViewController.swift | 1 | 4552 | //
// ThemeSelectorViewController.swift
// Accented
//
// Created by Tiangong You on 6/7/16.
// Copyright © 2016 Tiangong You. All rights reserved.
//
import UIKit
class ThemeSelectorViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
@IBOutlet weak var themeCollectionView: UICollectionView!
static let drawerWidthInPercentage : CGFloat = 0.8
private var themeCellIdentifier = "themeCell"
private var footerIdentifier = "themeFooter"
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = ThemeManager.sharedInstance.currentTheme.streamBackgroundColor;
// Register cell types
let cellNib = UINib(nibName: "ThemeSelectorRenderer", bundle: nil)
themeCollectionView.register(cellNib, forCellWithReuseIdentifier: themeCellIdentifier)
let footerNib = UINib(nibName: "ThemeSelectorFooterRenderer", bundle: nil)
themeCollectionView.register(footerNib, forSupplementaryViewOfKind: UICollectionElementKindSectionFooter, withReuseIdentifier: footerIdentifier)
themeCollectionView.dataSource = self
themeCollectionView.delegate = self
// Layout
let porpotion : CGFloat = 0.45
let w : CGFloat = UIScreen.main.bounds.width * ThemeSelectorViewController.drawerWidthInPercentage
let layout = UICollectionViewFlowLayout()
layout.itemSize = CGSize(width: w, height: w * porpotion)
themeCollectionView.collectionViewLayout = layout
themeCollectionView.contentInset = UIEdgeInsetsMake(155, 0, 10, 0)
// Select the current theme
let currentThemeIndex = ThemeManager.sharedInstance.themes.index(of: ThemeManager.sharedInstance.currentTheme)!
let currentThemePath = IndexPath(item: currentThemeIndex, section: 0)
themeCollectionView.selectItem(at: currentThemePath, animated: false, scrollPosition: .top)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
self.view.layer.shadowPath = UIBezierPath(rect: self.view.bounds).cgPath
self.view.layer.shadowColor = UIColor.black.cgColor
self.view.layer.shadowOpacity = 0.65;
self.view.layer.shadowRadius = 5
self.view.layer.shadowOffset = CGSize(width: -3, height: 0)
}
override var supportedInterfaceOrientations : UIInterfaceOrientationMask {
return .portrait
}
// MARK: UICollectionViewDataSource
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return ThemeManager.sharedInstance.themes.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: themeCellIdentifier, for: indexPath) as! ThemeSelectorRenderer
cell.theme = ThemeManager.sharedInstance.themes[(indexPath as NSIndexPath).item]
return cell;
}
func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
return collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionElementKindSectionFooter, withReuseIdentifier: footerIdentifier, for: indexPath)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForFooterInSection section: Int) -> CGSize {
return CGSize(width: self.view.bounds.width, height: 100)
}
// MARK: UICollectionViewDelegateFlowLayout
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let selectedTheme = ThemeManager.sharedInstance.themes[(indexPath as NSIndexPath).item]
ThemeManager.sharedInstance.currentTheme = selectedTheme
self.dismiss(animated: true, completion: nil)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
return 0
}
}
| mit | 2303833fce42f7d732242b9d140ed1a4 | 42.759615 | 175 | 0.727093 | 5.956806 | false | false | false | false |
sawijaya/UIFloatPHTextField | UIFloatPHTextField/DataConvertible.swift | 1 | 2033 | //
// DataConvertible.swift
//
// Created by Salim Wijaya
// Copyright © 2017. All rights reserved.
//
import UIKit
protocol DataConvertible {
associatedtype Result
static func convertFromData(_ data:Data) -> Result?
}
private let imageSync = NSLock()
extension UIImage : DataConvertible {
public typealias Result = UIImage
// HACK: UIImage data initializer is no longer thread safe. See: https://github.com/AFNetworking/AFNetworking/issues/2572#issuecomment-115854482
static func safeImageWithData(_ data:Data) -> Result? {
imageSync.lock()
let image = UIImage(data:data, scale: scale)
imageSync.unlock()
return image
}
public class func convertFromData(_ data: Data) -> Result? {
let image = UIImage.safeImageWithData(data)
return image
}
fileprivate static let scale = UIScreen.main.scale
}
public enum JSON : DataConvertible {
public typealias Result = JSON
case Dictionary([String:AnyObject])
case Array([AnyObject])
public static func convertFromData(_ data: Data) -> Result? {
do {
let object : Any = try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions())
switch (object) {
case let dictionary as [String:AnyObject]:
return JSON.Dictionary(dictionary)
case let array as [AnyObject]:
return JSON.Array(array)
default:
return nil
}
} catch {
print(error)
return nil
}
}
public var array : [AnyObject]! {
switch (self) {
case .Dictionary(_):
return nil
case .Array(let array):
return array
}
}
public var dictionary : [String:AnyObject]! {
switch (self) {
case .Dictionary(let dictionary):
return dictionary
case .Array(_):
return nil
}
}
}
| mit | 2d9fdaa75636d33eee216ad4d6bed35e | 25.38961 | 148 | 0.588091 | 4.872902 | false | false | false | false |
JBenny25/MemeMe | MemeMe/MemeMe/SentMemesVC/SentMemesCollectionViewController.swift | 1 | 2937 | //
// SentMemesCollectionViewController.swift
// MemeMe
//
// Created by Jubin Benny on 5/21/17.
// Copyright © 2017 Jubin Benny. All rights reserved.
//
import UIKit
//MARK: CollectionView Cell
class SentMemeCollectionViewCell: UICollectionViewCell {
@IBOutlet weak var imageView: UIImageView!
}
//MARK: CollectionView Controller
class SentMemesCollectionViewController: UICollectionViewController, UICollectionViewDelegateFlowLayout {
@IBOutlet weak var flowLayout: UICollectionViewFlowLayout!
let appDelegate = UIApplication.shared.delegate as! AppDelegate
var cellSize = CGSize(width: 100, height: 100)
override func viewDidLoad() {
super.viewDidLoad()
calculateCellSize()
}
func calculateCellSize() {
let maxVerticalCells = self.view.bounds.height/100
let maxHorizontalCells = self.view.bounds.width/100
let maxCellWidthVertical = self.view.bounds.height/maxVerticalCells
let maxCellWidthHorizontal = self.view.bounds.width/maxHorizontalCells
let size = min(maxCellWidthVertical, maxCellWidthHorizontal)
cellSize = CGSize(width: size, height: size)
}
override func viewWillAppear(_ animated: Bool) {
collectionView?.reloadData()
}
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
flowLayout?.invalidateLayout()
}
//MARK: CollectionView Delegate FlowLayout
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return cellSize
}
//MARK: CollectionView Datasource
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return appDelegate.memes.count
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "memeCollectionViewCell", for: indexPath) as! SentMemeCollectionViewCell
let meme = appDelegate.memes[indexPath.row]
cell.imageView.image = meme.memedImage
return cell
}
//MARK: CollectionView Delegate
override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let image = appDelegate.memes[indexPath.row].memedImage
performSegue(withIdentifier: "showCollectionDetail", sender: image)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "showCollectionDetail" {
let memeImage = sender as! UIImage
let detailVC = segue.destination as! MemeDetailViewController
detailVC.memeImage = memeImage
}
}
}
| mit | 4323c4454d2b3ec141417748c7a300d9 | 36.164557 | 160 | 0.712534 | 5.571157 | false | false | false | false |
xedin/swift | stdlib/public/Darwin/Foundation/URLComponents.swift | 17 | 28444 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
@_exported import Foundation // Clang module
/// A structure designed to parse URLs based on RFC 3986 and to construct URLs from their constituent parts.
///
/// Its behavior differs subtly from the `URL` struct, which conforms to older RFCs. However, you can easily obtain a `URL` based on the contents of a `URLComponents` or vice versa.
public struct URLComponents : ReferenceConvertible, Hashable, Equatable, _MutableBoxing {
public typealias ReferenceType = NSURLComponents
internal var _handle: _MutableHandle<NSURLComponents>
/// Initialize with all components undefined.
public init() {
_handle = _MutableHandle(adoptingReference: NSURLComponents())
}
/// Initialize with the components of a URL.
///
/// If resolvingAgainstBaseURL is `true` and url is a relative URL, the components of url.absoluteURL are used. If the url string from the URL is malformed, nil is returned.
public init?(url: __shared URL, resolvingAgainstBaseURL resolve: Bool) {
guard let result = NSURLComponents(url: url, resolvingAgainstBaseURL: resolve) else { return nil }
_handle = _MutableHandle(adoptingReference: result)
}
/// Initialize with a URL string.
///
/// If the URLString is malformed, nil is returned.
public init?(string: __shared String) {
guard let result = NSURLComponents(string: string) else { return nil }
_handle = _MutableHandle(adoptingReference: result)
}
/// Returns a URL created from the NSURLComponents.
///
/// If the NSURLComponents has an authority component (user, password, host or port) and a path component, then the path must either begin with "/" or be an empty string. If the NSURLComponents does not have an authority component (user, password, host or port) and has a path component, the path component must not start with "//". If those requirements are not met, nil is returned.
public var url: URL? {
return _handle.map { $0.url }
}
// Returns a URL created from the NSURLComponents relative to a base URL.
///
/// If the NSURLComponents has an authority component (user, password, host or port) and a path component, then the path must either begin with "/" or be an empty string. If the NSURLComponents does not have an authority component (user, password, host or port) and has a path component, the path component must not start with "//". If those requirements are not met, nil is returned.
public func url(relativeTo base: URL?) -> URL? {
return _handle.map { $0.url(relativeTo: base) }
}
// Returns a URL string created from the NSURLComponents. If the NSURLComponents has an authority component (user, password, host or port) and a path component, then the path must either begin with "/" or be an empty string. If the NSURLComponents does not have an authority component (user, password, host or port) and has a path component, the path component must not start with "//". If those requirements are not met, nil is returned.
@available(macOS 10.10, iOS 8.0, *)
public var string: String? {
return _handle.map { $0.string }
}
/// The scheme subcomponent of the URL.
///
/// The getter for this property removes any percent encoding this component may have (if the component allows percent encoding). Setting this property assumes the subcomponent or component string is not percent encoded and will add percent encoding (if the component allows percent encoding).
/// Attempting to set the scheme with an invalid scheme string will cause an exception.
public var scheme: String? {
get { return _handle.map { $0.scheme } }
set { _applyMutation { $0.scheme = newValue } }
}
/// The user subcomponent of the URL.
///
/// The getter for this property removes any percent encoding this component may have (if the component allows percent encoding). Setting this property assumes the subcomponent or component string is not percent encoded and will add percent encoding (if the component allows percent encoding).
///
/// Warning: IETF STD 66 (rfc3986) says the use of the format "user:password" in the userinfo subcomponent of a URI is deprecated because passing authentication information in clear text has proven to be a security risk. However, there are cases where this practice is still needed, and so the user and password components and methods are provided.
public var user: String? {
get { return _handle.map { $0.user } }
set { _applyMutation { $0.user = newValue } }
}
/// The password subcomponent of the URL.
///
/// The getter for this property removes any percent encoding this component may have (if the component allows percent encoding). Setting this property assumes the subcomponent or component string is not percent encoded and will add percent encoding (if the component allows percent encoding).
///
/// Warning: IETF STD 66 (rfc3986) says the use of the format "user:password" in the userinfo subcomponent of a URI is deprecated because passing authentication information in clear text has proven to be a security risk. However, there are cases where this practice is still needed, and so the user and password components and methods are provided.
public var password: String? {
get { return _handle.map { $0.password } }
set { _applyMutation { $0.password = newValue } }
}
/// The host subcomponent.
///
/// The getter for this property removes any percent encoding this component may have (if the component allows percent encoding). Setting this property assumes the subcomponent or component string is not percent encoded and will add percent encoding (if the component allows percent encoding).
public var host: String? {
get { return _handle.map { $0.host } }
set { _applyMutation { $0.host = newValue } }
}
/// The port subcomponent.
///
/// The getter for this property removes any percent encoding this component may have (if the component allows percent encoding). Setting this property assumes the subcomponent or component string is not percent encoded and will add percent encoding (if the component allows percent encoding).
/// Attempting to set a negative port number will cause a fatal error.
public var port: Int? {
get { return _handle.map { $0.port?.intValue } }
set { _applyMutation { $0.port = newValue != nil ? newValue as NSNumber? : nil as NSNumber?} }
}
/// The path subcomponent.
///
/// The getter for this property removes any percent encoding this component may have (if the component allows percent encoding). Setting this property assumes the subcomponent or component string is not percent encoded and will add percent encoding (if the component allows percent encoding).
public var path: String {
get {
guard let result = _handle.map({ $0.path }) else { return "" }
return result
}
set {
_applyMutation { $0.path = newValue }
}
}
/// The query subcomponent.
///
/// The getter for this property removes any percent encoding this component may have (if the component allows percent encoding). Setting this property assumes the subcomponent or component string is not percent encoded and will add percent encoding (if the component allows percent encoding).
public var query: String? {
get { return _handle.map { $0.query } }
set { _applyMutation { $0.query = newValue } }
}
/// The fragment subcomponent.
///
/// The getter for this property removes any percent encoding this component may have (if the component allows percent encoding). Setting this property assumes the subcomponent or component string is not percent encoded and will add percent encoding (if the component allows percent encoding).
public var fragment: String? {
get { return _handle.map { $0.fragment } }
set { _applyMutation { $0.fragment = newValue } }
}
/// The user subcomponent, percent-encoded.
///
/// The getter for this property retains any percent encoding this component may have. Setting this properties assumes the component string is already correctly percent encoded. Attempting to set an incorrectly percent encoded string will cause a `fatalError`. Although ';' is a legal path character, it is recommended that it be percent-encoded for best compatibility with `URL` (`String.addingPercentEncoding(withAllowedCharacters:)` will percent-encode any ';' characters if you pass `CharacterSet.urlUserAllowed`).
public var percentEncodedUser: String? {
get { return _handle.map { $0.percentEncodedUser } }
set { _applyMutation { $0.percentEncodedUser = newValue } }
}
/// The password subcomponent, percent-encoded.
///
/// The getter for this property retains any percent encoding this component may have. Setting this properties assumes the component string is already correctly percent encoded. Attempting to set an incorrectly percent encoded string will cause a `fatalError`. Although ';' is a legal path character, it is recommended that it be percent-encoded for best compatibility with `URL` (`String.addingPercentEncoding(withAllowedCharacters:)` will percent-encode any ';' characters if you pass `CharacterSet.urlPasswordAllowed`).
public var percentEncodedPassword: String? {
get { return _handle.map { $0.percentEncodedPassword } }
set { _applyMutation { $0.percentEncodedPassword = newValue } }
}
/// The host subcomponent, percent-encoded.
///
/// The getter for this property retains any percent encoding this component may have. Setting this properties assumes the component string is already correctly percent encoded. Attempting to set an incorrectly percent encoded string will cause a `fatalError`. Although ';' is a legal path character, it is recommended that it be percent-encoded for best compatibility with `URL` (`String.addingPercentEncoding(withAllowedCharacters:)` will percent-encode any ';' characters if you pass `CharacterSet.urlHostAllowed`).
public var percentEncodedHost: String? {
get { return _handle.map { $0.percentEncodedHost } }
set { _applyMutation { $0.percentEncodedHost = newValue } }
}
/// The path subcomponent, percent-encoded.
///
/// The getter for this property retains any percent encoding this component may have. Setting this properties assumes the component string is already correctly percent encoded. Attempting to set an incorrectly percent encoded string will cause a `fatalError`. Although ';' is a legal path character, it is recommended that it be percent-encoded for best compatibility with `URL` (`String.addingPercentEncoding(withAllowedCharacters:)` will percent-encode any ';' characters if you pass `CharacterSet.urlPathAllowed`).
public var percentEncodedPath: String {
get {
guard let result = _handle.map({ $0.percentEncodedPath }) else { return "" }
return result
}
set {
_applyMutation { $0.percentEncodedPath = newValue }
}
}
/// The query subcomponent, percent-encoded.
///
/// The getter for this property retains any percent encoding this component may have. Setting this properties assumes the component string is already correctly percent encoded. Attempting to set an incorrectly percent encoded string will cause a `fatalError`. Although ';' is a legal path character, it is recommended that it be percent-encoded for best compatibility with `URL` (`String.addingPercentEncoding(withAllowedCharacters:)` will percent-encode any ';' characters if you pass `CharacterSet.urlQueryAllowed`).
public var percentEncodedQuery: String? {
get { return _handle.map { $0.percentEncodedQuery } }
set { _applyMutation { $0.percentEncodedQuery = newValue } }
}
/// The fragment subcomponent, percent-encoded.
///
/// The getter for this property retains any percent encoding this component may have. Setting this properties assumes the component string is already correctly percent encoded. Attempting to set an incorrectly percent encoded string will cause a `fatalError`. Although ';' is a legal path character, it is recommended that it be percent-encoded for best compatibility with `URL` (`String.addingPercentEncoding(withAllowedCharacters:)` will percent-encode any ';' characters if you pass `CharacterSet.urlFragmentAllowed`).
public var percentEncodedFragment: String? {
get { return _handle.map { $0.percentEncodedFragment } }
set { _applyMutation { $0.percentEncodedFragment = newValue } }
}
@available(macOS 10.11, iOS 9.0, *)
private func _toStringRange(_ r : NSRange) -> Range<String.Index>? {
guard let s = self.string else { return nil }
return Range(r, in: s)
}
/// Returns the character range of the scheme in the string returned by `var string`.
///
/// If the component does not exist, nil is returned.
/// - note: Zero length components are legal. For example, the URL string "scheme://:@/?#" has a zero length user, password, host, query and fragment; the URL strings "scheme:" and "" both have a zero length path.
@available(macOS 10.11, iOS 9.0, *)
public var rangeOfScheme: Range<String.Index>? {
return _toStringRange(_handle.map { $0.rangeOfScheme })
}
/// Returns the character range of the user in the string returned by `var string`.
///
/// If the component does not exist, nil is returned.
/// - note: Zero length components are legal. For example, the URL string "scheme://:@/?#" has a zero length user, password, host, query and fragment; the URL strings "scheme:" and "" both have a zero length path.
@available(macOS 10.11, iOS 9.0, *)
public var rangeOfUser: Range<String.Index>? {
return _toStringRange(_handle.map { $0.rangeOfUser })
}
/// Returns the character range of the password in the string returned by `var string`.
///
/// If the component does not exist, nil is returned.
/// - note: Zero length components are legal. For example, the URL string "scheme://:@/?#" has a zero length user, password, host, query and fragment; the URL strings "scheme:" and "" both have a zero length path.
@available(macOS 10.11, iOS 9.0, *)
public var rangeOfPassword: Range<String.Index>? {
return _toStringRange(_handle.map { $0.rangeOfPassword })
}
/// Returns the character range of the host in the string returned by `var string`.
///
/// If the component does not exist, nil is returned.
/// - note: Zero length components are legal. For example, the URL string "scheme://:@/?#" has a zero length user, password, host, query and fragment; the URL strings "scheme:" and "" both have a zero length path.
@available(macOS 10.11, iOS 9.0, *)
public var rangeOfHost: Range<String.Index>? {
return _toStringRange(_handle.map { $0.rangeOfHost })
}
/// Returns the character range of the port in the string returned by `var string`.
///
/// If the component does not exist, nil is returned.
/// - note: Zero length components are legal. For example, the URL string "scheme://:@/?#" has a zero length user, password, host, query and fragment; the URL strings "scheme:" and "" both have a zero length path.
@available(macOS 10.11, iOS 9.0, *)
public var rangeOfPort: Range<String.Index>? {
return _toStringRange(_handle.map { $0.rangeOfPort })
}
/// Returns the character range of the path in the string returned by `var string`.
///
/// If the component does not exist, nil is returned.
/// - note: Zero length components are legal. For example, the URL string "scheme://:@/?#" has a zero length user, password, host, query and fragment; the URL strings "scheme:" and "" both have a zero length path.
@available(macOS 10.11, iOS 9.0, *)
public var rangeOfPath: Range<String.Index>? {
return _toStringRange(_handle.map { $0.rangeOfPath })
}
/// Returns the character range of the query in the string returned by `var string`.
///
/// If the component does not exist, nil is returned.
/// - note: Zero length components are legal. For example, the URL string "scheme://:@/?#" has a zero length user, password, host, query and fragment; the URL strings "scheme:" and "" both have a zero length path.
@available(macOS 10.11, iOS 9.0, *)
public var rangeOfQuery: Range<String.Index>? {
return _toStringRange(_handle.map { $0.rangeOfQuery })
}
/// Returns the character range of the fragment in the string returned by `var string`.
///
/// If the component does not exist, nil is returned.
/// - note: Zero length components are legal. For example, the URL string "scheme://:@/?#" has a zero length user, password, host, query and fragment; the URL strings "scheme:" and "" both have a zero length path.
@available(macOS 10.11, iOS 9.0, *)
public var rangeOfFragment: Range<String.Index>? {
return _toStringRange(_handle.map { $0.rangeOfFragment })
}
/// Returns an array of query items for this `URLComponents`, in the order in which they appear in the original query string.
///
/// Each `URLQueryItem` represents a single key-value pair,
///
/// Note that a name may appear more than once in a single query string, so the name values are not guaranteed to be unique. If the `URLComponents` has an empty query component, returns an empty array. If the `URLComponents` has no query component, returns nil.
///
/// The setter combines an array containing any number of `URLQueryItem`s, each of which represents a single key-value pair, into a query string and sets the `URLComponents` query property. Passing an empty array sets the query component of the `URLComponents` to an empty string. Passing nil removes the query component of the `URLComponents`.
///
/// - note: If a name-value pair in a query is empty (i.e. the query string starts with '&', ends with '&', or has "&&" within it), you get a `URLQueryItem` with a zero-length name and a nil value. If a query's name-value pair has nothing before the equals sign, you get a zero-length name. If a query's name-value pair has nothing after the equals sign, you get a zero-length value. If a query's name-value pair has no equals sign, the query name-value pair string is the name and you get a nil value.
@available(macOS 10.10, iOS 8.0, *)
public var queryItems: [URLQueryItem]? {
get { return _handle.map { $0.queryItems } }
set { _applyMutation { $0.queryItems = newValue } }
}
/// Returns an array of query items for this `URLComponents`, in the order in which they appear in the original query string. Any percent-encoding in a query item name or value is retained
///
/// The setter combines an array containing any number of `URLQueryItem`s, each of which represents a single key-value pair, into a query string and sets the `URLComponents` query property. This property assumes the query item names and values are already correctly percent-encoded, and that the query item names do not contain the query item delimiter characters '&' and '='. Attempting to set an incorrectly percent-encoded query item or a query item name with the query item delimiter characters '&' and '=' will cause a `fatalError`.
@available(macOS 10.13, iOS 11.0, tvOS 11.0, watchOS 4.0, *)
public var percentEncodedQueryItems: [URLQueryItem]? {
get { return _handle.map { $0.percentEncodedQueryItems } }
set { _applyMutation { $0.percentEncodedQueryItems = newValue } }
}
public func hash(into hasher: inout Hasher) {
hasher.combine(_handle._uncopiedReference())
}
// MARK: - Bridging
fileprivate init(reference: __shared NSURLComponents) {
_handle = _MutableHandle(reference: reference)
}
public static func ==(lhs: URLComponents, rhs: URLComponents) -> Bool {
// Don't copy references here; no one should be storing anything
return lhs._handle._uncopiedReference().isEqual(rhs._handle._uncopiedReference())
}
}
extension URLComponents : CustomStringConvertible, CustomDebugStringConvertible, CustomReflectable {
public var description: String {
if let u = url {
return u.description
} else {
return self.customMirror.children.reduce("") {
$0.appending("\($1.label ?? ""): \($1.value) ")
}
}
}
public var debugDescription: String {
return self.description
}
public var customMirror: Mirror {
var c: [(label: String?, value: Any)] = []
if let s = self.scheme { c.append((label: "scheme", value: s)) }
if let u = self.user { c.append((label: "user", value: u)) }
if let pw = self.password { c.append((label: "password", value: pw)) }
if let h = self.host { c.append((label: "host", value: h)) }
if let p = self.port { c.append((label: "port", value: p)) }
c.append((label: "path", value: self.path))
if #available(macOS 10.10, iOS 8.0, *) {
if let qi = self.queryItems { c.append((label: "queryItems", value: qi)) }
}
if let f = self.fragment { c.append((label: "fragment", value: f)) }
let m = Mirror(self, children: c, displayStyle: Mirror.DisplayStyle.struct)
return m
}
}
extension URLComponents : _ObjectiveCBridgeable {
public static func _getObjectiveCType() -> Any.Type {
return NSURLComponents.self
}
@_semantics("convertToObjectiveC")
public func _bridgeToObjectiveC() -> NSURLComponents {
return _handle._copiedReference()
}
public static func _forceBridgeFromObjectiveC(_ x: NSURLComponents, result: inout URLComponents?) {
if !_conditionallyBridgeFromObjectiveC(x, result: &result) {
fatalError("Unable to bridge \(_ObjectiveCType.self) to \(self)")
}
}
public static func _conditionallyBridgeFromObjectiveC(_ x: NSURLComponents, result: inout URLComponents?) -> Bool {
result = URLComponents(reference: x)
return true
}
@_effects(readonly)
public static func _unconditionallyBridgeFromObjectiveC(_ source: NSURLComponents?) -> URLComponents {
guard let src = source else { return URLComponents() }
return URLComponents(reference: src)
}
}
extension NSURLComponents : _HasCustomAnyHashableRepresentation {
// Must be @nonobjc to avoid infinite recursion during bridging.
@nonobjc
public func _toCustomAnyHashable() -> AnyHashable? {
return AnyHashable(self as URLComponents)
}
}
/// A single name-value pair, for use with `URLComponents`.
@available(macOS 10.10, iOS 8.0, *)
public struct URLQueryItem : ReferenceConvertible, Hashable, Equatable {
public typealias ReferenceType = NSURLQueryItem
fileprivate var _queryItem : NSURLQueryItem
public init(name: __shared String, value: __shared String?) {
_queryItem = NSURLQueryItem(name: name, value: value)
}
fileprivate init(reference: __shared NSURLQueryItem) { _queryItem = reference.copy() as! NSURLQueryItem }
fileprivate var reference : NSURLQueryItem { return _queryItem }
public var name : String {
get { return _queryItem.name }
set { _queryItem = NSURLQueryItem(name: newValue, value: value) }
}
public var value : String? {
get { return _queryItem.value }
set { _queryItem = NSURLQueryItem(name: name, value: newValue) }
}
public func hash(into hasher: inout Hasher) {
hasher.combine(_queryItem)
}
@available(macOS 10.10, iOS 8.0, *)
public static func ==(lhs: URLQueryItem, rhs: URLQueryItem) -> Bool {
return lhs._queryItem.isEqual(rhs as NSURLQueryItem)
}
}
@available(macOS 10.10, iOS 8.0, *)
extension URLQueryItem : CustomStringConvertible, CustomDebugStringConvertible, CustomReflectable {
public var description: String {
if let v = value {
return "\(name)=\(v)"
} else {
return name
}
}
public var debugDescription: String {
return self.description
}
public var customMirror: Mirror {
let c: [(label: String?, value: Any)] = [
("name", name),
("value", value as Any),
]
return Mirror(self, children: c, displayStyle: Mirror.DisplayStyle.struct)
}
}
@available(macOS 10.10, iOS 8.0, *)
extension URLQueryItem : _ObjectiveCBridgeable {
public static func _getObjectiveCType() -> Any.Type {
return NSURLQueryItem.self
}
@_semantics("convertToObjectiveC")
public func _bridgeToObjectiveC() -> NSURLQueryItem {
return _queryItem
}
public static func _forceBridgeFromObjectiveC(_ x: NSURLQueryItem, result: inout URLQueryItem?) {
if !_conditionallyBridgeFromObjectiveC(x, result: &result) {
fatalError("Unable to bridge \(_ObjectiveCType.self) to \(self)")
}
}
public static func _conditionallyBridgeFromObjectiveC(_ x: NSURLQueryItem, result: inout URLQueryItem?) -> Bool {
result = URLQueryItem(reference: x)
return true
}
@_effects(readonly)
public static func _unconditionallyBridgeFromObjectiveC(_ source: NSURLQueryItem?) -> URLQueryItem {
var result: URLQueryItem?
_forceBridgeFromObjectiveC(source!, result: &result)
return result!
}
}
@available(macOS 10.10, iOS 8.0, *)
extension NSURLQueryItem : _HasCustomAnyHashableRepresentation {
// Must be @nonobjc to avoid infinite recursion during bridging.
@nonobjc
public func _toCustomAnyHashable() -> AnyHashable? {
return AnyHashable(self as URLQueryItem)
}
}
extension URLComponents : Codable {
private enum CodingKeys : Int, CodingKey {
case scheme
case user
case password
case host
case port
case path
case query
case fragment
}
public init(from decoder: Decoder) throws {
self.init()
let container = try decoder.container(keyedBy: CodingKeys.self)
self.scheme = try container.decodeIfPresent(String.self, forKey: .scheme)
self.user = try container.decodeIfPresent(String.self, forKey: .user)
self.password = try container.decodeIfPresent(String.self, forKey: .password)
self.host = try container.decodeIfPresent(String.self, forKey: .host)
self.port = try container.decodeIfPresent(Int.self, forKey: .port)
self.path = try container.decode(String.self, forKey: .path)
self.query = try container.decodeIfPresent(String.self, forKey: .query)
self.fragment = try container.decodeIfPresent(String.self, forKey: .fragment)
}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encodeIfPresent(self.scheme, forKey: .scheme)
try container.encodeIfPresent(self.user, forKey: .user)
try container.encodeIfPresent(self.password, forKey: .password)
try container.encodeIfPresent(self.host, forKey: .host)
try container.encodeIfPresent(self.port, forKey: .port)
try container.encode(self.path, forKey: .path)
try container.encodeIfPresent(self.query, forKey: .query)
try container.encodeIfPresent(self.fragment, forKey: .fragment)
}
}
| apache-2.0 | a65bc1eb4863c2902a5dfd6918ebafa6 | 54.017408 | 541 | 0.681304 | 4.796627 | false | false | false | false |
neoneye/SwiftyFORM | Source/Form/TableViewCellArray.swift | 1 | 1350 | // MIT license. Copyright (c) 2021 SwiftyFORM. All rights reserved.
import UIKit
public class TableViewCellArrayItem {
public let cell: UITableViewCell
public var hidden: Bool
public init(cell: UITableViewCell, hidden: Bool) {
self.cell = cell
self.hidden = hidden
}
}
public class TableViewCellArray {
fileprivate(set) var allItems: [TableViewCellArrayItem]
fileprivate(set) var visibleItems = [TableViewCellArrayItem]()
public static func create(cells: [UITableViewCell]) -> TableViewCellArray {
let items = cells.map { TableViewCellArrayItem(cell: $0, hidden: false) }
return TableViewCellArray(allItems: items)
}
public static func createEmpty() -> TableViewCellArray {
TableViewCellArray(allItems: [])
}
public init(allItems: [TableViewCellArrayItem]) {
self.allItems = allItems
reloadVisibleItems()
}
public func reloadVisibleItems() {
visibleItems = allItems.filter { $0.hidden == false }
}
public subscript(index: Int) -> UITableViewCell {
visibleItems[index].cell
}
public var count: Int {
visibleItems.count
}
public func append(_ cell: UITableViewCell) {
let item = TableViewCellArrayItem(cell: cell, hidden: false)
allItems.append(item)
}
public func appendHidden(_ cell: UITableViewCell) {
let item = TableViewCellArrayItem(cell: cell, hidden: true)
allItems.append(item)
}
}
| mit | fe287ac114317e35f71a1bf4521fcfe9 | 24.471698 | 76 | 0.742222 | 3.868195 | false | false | false | false |
laant/mqtt_chat_swift | App/ViewController.swift | 1 | 10508 | //
// ViewController.swift
// App
//
// Created by Laan on 2016. 6. 17..
// Copyright © 2016년 Laan. All rights reserved.
//
import UIKit
class ViewController: UIViewController, MQTTSessionManagerDelegate, UITableViewDataSource, UITableViewDelegate, UITextViewDelegate {
@IBOutlet weak var tableView: UITableView!
var items = [(sender:String, msg:String)]()
var manager: MQTTSessionManager!
var mqttSettings:NSDictionary!
let device_id = UIDevice.currentDevice().identifierForVendor!.UUIDString //UIDevice.currentDevice().name
var urlInfo:NSURL!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let mqttPlistUrl = NSBundle.mainBundle().bundleURL.URLByAppendingPathComponent("mqtt.plist")
mqttSettings = NSDictionary(contentsOfURL: mqttPlistUrl)
if manager == nil {
manager = MQTTSessionManager()
manager.delegate = self
manager.subscriptions = ["\(mqttSettings["base"]!)/#": NSNumber(unsignedChar: MQTTQosLevel.ExactlyOnce.rawValue)]
manager.connectTo(
mqttSettings["host"]! as! String
, port: Int((mqttSettings["port"])! as! NSNumber)
, tls: (mqttSettings["tls"]?.boolValue)!
, keepalive: 60
, clean: true
, auth: false
, user: nil
, pass: nil
, willTopic: "\(mqttSettings["base"])/\(device_id)"
, will: "offline".dataUsingEncoding(NSUTF8StringEncoding)
, willQos: MQTTQosLevel.ExactlyOnce
, willRetainFlag: false
, withClientId: nil
)
}
else {
manager.connectToLast()
}
manager.addObserver(self, forKeyPath: "state", options: NSKeyValueObservingOptions.Initial, context: nil)
tableView.estimatedRowHeight = 70
tableView.rowHeight = UITableViewAutomaticDimension
}
override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
switch manager.state {
case .Closed:
print("Closed")
case .Closing:
print("Closing")
case .Connected:
print("Connected")
manager.sendData("joins chat".dataUsingEncoding(NSUTF8StringEncoding), topic: "\(mqttSettings["base"]!)/\(device_id)", qos: .ExactlyOnce, retain: false)
case .Connecting:
print("Connecting")
case .Error:
print("Error")
case .Starting:
print("Starting")
}
}
func connect() {
manager.connectToLast()
}
func disconnect() {
manager.sendData("leaves chat".dataUsingEncoding(NSUTF8StringEncoding), topic: "\(mqttSettings["base"]!)/\(device_id)", qos: .ExactlyOnce, retain: false)
NSRunLoop.currentRunLoop().runUntilDate(NSDate(timeIntervalSinceNow: 1.0))
manager.disconnect()
}
@IBAction func pressedLongText(sender: AnyObject) {
manager.sendData("pressedLongText pressedLongTextpressedLongText pressedLongTextpressedLongTextpressedLongText pressedLongTextpressedLongTextpressedLongTextpressedLongText pressedLongTextpressedLongTextpressedLongTextpressedLongTextpressedLongText pressedLongTextpressedLongTextpressedLongTextpressedLongTextpressedLongTextpressedLongText pressedLongTextpressedLongTextpressedLongTextpressedLongTextpressedLongTextpressedLongTextpressedLongText".dataUsingEncoding(NSUTF8StringEncoding), topic: "\(mqttSettings["base"]!)/\(device_id)", qos: .ExactlyOnce, retain: false)
}
@IBAction func pressedMiddleText(sender: AnyObject) {
manager.sendData("pressedMiddleTextpressedMiddleText pressedMiddleTextpressedMiddleText pressedMiddleTextpressedMiddleText".dataUsingEncoding(NSUTF8StringEncoding), topic: "\(mqttSettings["base"]!)/\(device_id)", qos: .ExactlyOnce, retain: false)
}
@IBAction func pressedShortText(sender: AnyObject) {
let htmlText: String =
"폰트컬러 블루<font color=\"blue\">파랑</font>선택선택선택선택선택선택선택선택선택선택。<br>" +
"폰트컬러 레드<font color=\"red\">빨강</font>선택。<br>" +
"<hr width=\"100%\" size=\"1\" noshade>" +
"타이드스퀘어<a href=\"http://m.priviatravel.com/\"><strong>프리비아여행</strong></a><br>" +
"CSS Style<strong style=\"color:#663399;\">#663399</strong>...。"
manager.sendData("[html]\(htmlText)".dataUsingEncoding(NSUTF8StringEncoding), topic: "\(mqttSettings["base"]!)/\(device_id)", qos: .ExactlyOnce, retain: false)
}
@IBAction func pressedImageUrl(sender: AnyObject) {
let images = [
"http://file3.funshop.co.kr/abroad/012/6270/thumbnail_1.jpg",
"http://file3.funshop.co.kr/abroad/012/6258/thumbnail_1.jpg",
"http://file3.funshop.co.kr/abroad/012/6248/thumbnail_1.jpg",
"http://file3.funshop.co.kr/abroad/012/6247/thumbnail_1.jpg",
"http://file3.funshop.co.kr/abroad/012/6246/thumbnail_1.jpg",
"http://file3.funshop.co.kr/abroad/012/6245/thumbnail_1.jpg",
"http://file3.funshop.co.kr/abroad/012/6244/thumbnail_1.jpg",
"http://file3.funshop.co.kr/abroad/012/6243/thumbnail_1.jpg",
"http://file3.funshop.co.kr/abroad/012/6242/thumbnail_1.jpg",
"http://file3.funshop.co.kr/abroad/012/6241/thumbnail_1.jpg"
]
manager.sendData("[image]\(images[Utility.random(images.count)])".dataUsingEncoding(NSUTF8StringEncoding), topic: "\(mqttSettings["base"]!)/\(device_id)", qos: .ExactlyOnce, retain: false)
}
// MARK - MQTTSessionManagerDelegate
func handleMessage(data: NSData!, onTopic topic: String!, retained: Bool) {
// process received message
let dataString = NSString(data: data, encoding: NSUTF8StringEncoding)!
let senderString = topic.substringFromIndex("\(mqttSettings["base"]!)/".endIndex)
print("\(senderString):\(dataString)")
items.append((senderString, dataString as String))
tableView.reloadData()
scrollToLast()
}
// MARK: - UITableViewDatasource, UITableViewdelegate
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return items.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let item = items[indexPath.row]
let cell:TextTalkCell
if item.msg.containsString("[image]") {
if item.sender == device_id {
cell = self.tableView.dequeueReusableCellWithIdentifier("send_image")! as! TextTalkCell
}
else {
cell = self.tableView.dequeueReusableCellWithIdentifier("recv_image")! as! TextTalkCell
}
cell.image_view.downloadByImageUrl(item.msg.substringFromIndex("[image]".endIndex))
}
else if item.msg.containsString("[html]") {
if item.sender == device_id {
cell = self.tableView.dequeueReusableCellWithIdentifier("send_text")! as! TextTalkCell
}
else {
cell = self.tableView.dequeueReusableCellWithIdentifier("recv_text")! as! TextTalkCell
}
let htmlText = item.msg.substringFromIndex("[html]".endIndex)
let encodedData = htmlText.dataUsingEncoding(NSUTF8StringEncoding)!
let attributedOptions : [String : AnyObject] = [
NSDocumentTypeDocumentAttribute : NSHTMLTextDocumentType,
NSCharacterEncodingDocumentAttribute: NSUTF8StringEncoding,
]
do {
let attributedString = try NSAttributedString(data: encodedData, options: attributedOptions, documentAttributes: nil)
cell.textView.attributedText = attributedString
cell.textViewWidthConstraint.constant = UIScreen.mainScreen().bounds.size.width*0.7
cell.textView.delegate = self
}
catch {
print("error")
}
}
else {
if item.sender == device_id {
cell = self.tableView.dequeueReusableCellWithIdentifier("send_text")! as! TextTalkCell
}
else {
cell = self.tableView.dequeueReusableCellWithIdentifier("recv_text")! as! TextTalkCell
}
cell.textView.text = item.msg
cell.textViewWidthConstraint.constant = UIScreen.mainScreen().bounds.size.width*0.7
cell.textView.delegate = self
}
return cell
}
// MARK - UITextViewDelegate
func textViewDidChange(textView: UITextView) {
tableView.beginUpdates()
tableView.endUpdates()
// let currentOffset = tableView.contentOffset
// UIView.setAnimationsEnabled(false)
// tableView.beginUpdates()
// tableView.endUpdates()
// UIView.setAnimationsEnabled(true)
// tableView.setContentOffset(currentOffset, animated: false)
}
func textView(textView: UITextView, shouldInteractWithURL URL: NSURL, inRange characterRange: NSRange) -> Bool {
print("shouldInteractWithURL : \(URL)")
urlInfo = URL
self.performSegueWithIdentifier("goWeb", sender: self)
return false
}
// MARK - Etc Function
func scrollToLast() {
let last_item_index = items.count-1
let lastIndexPath = NSIndexPath(forItem: last_item_index, inSection: 0)
tableView.scrollToRowAtIndexPath(lastIndexPath, atScrollPosition: UITableViewScrollPosition.Bottom, animated: false)
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "goWeb" {
let vc:WebViewController = segue.destinationViewController as! WebViewController
vc.reqUrl = urlInfo
}
}
}
| mit | 7cd387a914ddf17e93c4b9ab99eff2da | 41.794239 | 576 | 0.622464 | 5.15057 | false | false | false | false |
google/android-auto-companion-ios | Sources/AndroidAutoConnectedDeviceManagerMocks/AssociatedCarsManagerMock.swift | 1 | 1823 | // Copyright 2021 Google LLC
//
// 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.
@testable import AndroidAutoConnectedDeviceManager
/// A mock of `AssociatedCarsManager` that simply sets its identifier internally and allows
/// assertions of its methods.
public class AssociatedCarsManagerMock: AssociatedCarsManager {
private(set) var data: [String: String?] = [:]
public var setIdentifierCalled = false
public var clearIdentifierCalled = false
public var identifiers: Set<String> {
return Set(data.keys)
}
public var cars: Set<Car> {
return Set(data.lazy.map { Car(id: $0, name: $1) })
}
public var count: Int {
return data.count
}
public init() {}
public func addAssociatedCar(identifier: String, name: String?) {
setIdentifierCalled = true
data[identifier] = name
}
public func clearIdentifiers() {
data = [:]
}
public func clearIdentifier(_ identifier: String) {
clearIdentifierCalled = true
data[identifier] = nil
}
public func renameCar(identifier: String, to name: String) -> Bool {
if data[identifier] == nil {
return false
}
data[identifier] = name
return true
}
/// Resets this mock back to its default initialization state
public func reset() {
data = [:]
setIdentifierCalled = false
}
}
| apache-2.0 | c088ae63c71d784b92a5d282104e318f | 26.621212 | 91 | 0.702139 | 4.259346 | false | false | false | false |
MaddTheSane/WWDC | WWDC/LiveEventObserver.swift | 2 | 6108 | //
// LiveEventObserver.swift
// WWDC
//
// Created by Guilherme Rambo on 16/05/15.
// Copyright (c) 2015 Guilherme Rambo. All rights reserved.
//
import Cocoa
public let LiveEventNextInfoChangedNotification = "LiveEventNextInfoChangedNotification"
public let LiveEventTitleAvailableNotification = "LiveEventTitleAvailableNotification"
public let LiveEventWillStartPlayingNotification = "LiveEventWillStartPlayingNotification"
private let _sharedInstance = LiveEventObserver()
class LiveEventObserver: NSObject, NSUserNotificationCenterDelegate {
var nextEvent: LiveSession? {
didSet {
NSNotificationCenter.defaultCenter().postNotificationName(LiveEventNextInfoChangedNotification, object: nil)
}
}
private var lastEventFound: LiveSession?
private var timer: NSTimer?
private var liveEventPlayerController: VideoWindowController?
class func SharedObserver() -> LiveEventObserver {
return _sharedInstance
}
func start() {
NSUserNotificationCenter.defaultUserNotificationCenter().delegate = self
timer = NSTimer.scheduledTimerWithTimeInterval(Preferences.SharedPreferences().liveEventCheckInterval, target: self, selector: "checkNow", userInfo: nil, repeats: true)
checkNow()
}
func checkNow() {
checkForLiveEvent { available, event in
dispatch_async(dispatch_get_main_queue()) {
if !available && self.liveEventPlayerController != nil {
self.liveEventPlayerController?.close()
return
}
// an event is available
if available && event != nil {
self.lastEventFound = event
self.playEvent(event!)
}
}
}
fetchNextLiveEvent { available, event in
dispatch_async(dispatch_get_main_queue()) {
self.nextEvent = event
}
}
}
func playEvent(event: LiveSession) {
if Preferences.SharedPreferences().autoplayLiveEvents || overrideAutoplayPreference {
doPlayEvent(event)
}
showNotification(event)
}
private func doPlayEvent(event: LiveSession) {
// we already have a live event playing, just return
if liveEventPlayerController != nil {
NSNotificationCenter.defaultCenter().postNotificationName(LiveEventTitleAvailableNotification, object: event.title)
return
}
NSNotificationCenter.defaultCenter().postNotificationName(LiveEventWillStartPlayingNotification, object: nil)
liveEventPlayerController = VideoWindowController(event: event, videoURL: event.streamURL!.absoluteString)
liveEventPlayerController?.showWindow(nil)
}
// MARK: User notifications
let liveEventNotificationIdentifier = "LiveEvent"
var overrideAutoplayPreference = false
func checkNowAndPlay() {
overrideAutoplayPreference = true
if let event = lastEventFound {
doPlayEvent(event)
} else {
checkNow()
}
}
func showNotification(event: LiveSession) {
let notification = NSUserNotification()
notification.title = "\(event.title) is live!"
notification.informativeText = "Watch \(event.title) right now!"
notification.hasActionButton = true
notification.actionButtonTitle = "Watch"
notification.deliveryDate = NSDate()
notification.identifier = liveEventNotificationIdentifier
NSUserNotificationCenter.defaultUserNotificationCenter().scheduleNotification(notification)
}
func userNotificationCenter(center: NSUserNotificationCenter, didActivateNotification notification: NSUserNotification) {
if notification.identifier == liveEventNotificationIdentifier {
checkNowAndPlay()
}
}
private let _liveServiceURL = "http://wwdc.guilhermerambo.me/live.json"
private let _liveNextServiceURL = "http://wwdc.guilhermerambo.me/next.json"
private var liveURL: NSURL {
get {
sranddev()
// adds a random number as a parameter to completely prevent any caching
return NSURL(string: "\(_liveServiceURL)?t=\(rand())&s=\(NSDate.timeIntervalSinceReferenceDate())")!
}
}
private var liveNextURL: NSURL {
get {
sranddev()
// adds a random number as a parameter to completely prevent any caching
return NSURL(string: "\(_liveNextServiceURL)?t=\(rand())&s=\(NSDate.timeIntervalSinceReferenceDate())")!
}
}
let URLSession2 = NSURLSession(configuration: NSURLSessionConfiguration.ephemeralSessionConfiguration())
func checkForLiveEvent(completionHandler: (Bool, LiveSession?) -> ()) {
let task = URLSession2.dataTaskWithURL(liveURL) { data, response, error in
if data == nil {
completionHandler(false, nil)
return
}
let jsonData = JSON(data: data!)
let event = LiveSession(jsonObject: jsonData)
if event.isLiveRightNow {
completionHandler(true, event)
} else {
completionHandler(false, nil)
}
}
task.resume()
}
func fetchNextLiveEvent(completionHandler: (Bool, LiveSession?) -> ()) {
let task = URLSession2.dataTaskWithURL(liveNextURL) { data, response, error in
if data == nil {
completionHandler(false, nil)
return
}
let jsonData = JSON(data: data!)
let event = LiveSession(jsonObject: jsonData)
if event.title != "" {
completionHandler(true, event)
} else {
completionHandler(false, nil)
}
}
task.resume()
}
}
| bsd-2-clause | 1684b97b3c69162c4655318af438b436 | 34.306358 | 176 | 0.620825 | 5.811608 | false | false | false | false |
dsaved/africhat-platform-0.1 | actor-apps/app-ios/ActorSwift/Strings.swift | 19 | 2379 | //
// Copyright (c) 2014-2015 Actor LLC. <https://actor.im>
//
import Foundation
extension String {
var size: Int { return count(self) }
func trim() -> String {
return stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet());
}
subscript (i: Int) -> Character {
return self[advance(self.startIndex, i)]
}
subscript (i: Int) -> String {
return String(self[i] as Character)
}
func first(count: Int) -> String {
let realCount = min(count, size);
return substringToIndex(advance(startIndex, realCount));
}
func strip(set: NSCharacterSet) -> String {
return "".join(componentsSeparatedByCharactersInSet(set))
}
func toLong() -> Int64? {
return NSNumberFormatter().numberFromString(self)?.longLongValue
}
func smallValue() -> String {
let trimmed = trim();
if (trimmed.isEmpty){
return "#";
}
let letters = NSCharacterSet.letterCharacterSet()
var res: String = self[0];
if (res.rangeOfCharacterFromSet(letters) != nil) {
return res.uppercaseString;
} else {
return "#";
}
}
func hasPrefixInWords(prefix: String) -> Bool {
var components = self.componentsSeparatedByString(" ")
for i in 0..<components.count {
if components[i].lowercaseString.hasPrefix(prefix.lowercaseString) {
return true
}
}
return false
}
func contains(text: String) -> Bool {
return self.rangeOfString(text, options: NSStringCompareOptions.CaseInsensitiveSearch, range: nil, locale: nil) != nil
}
func rangesOfString(text: String) -> [Range<String.Index>] {
var res = [Range<String.Index>]()
var searchRange = Range<String.Index>(start: self.startIndex, end: self.endIndex)
while true {
var found = self.rangeOfString(text, options: NSStringCompareOptions.CaseInsensitiveSearch, range: searchRange, locale: nil)
if found != nil {
res.append(found!)
searchRange = Range<String.Index>(start: found!.endIndex, end: self.endIndex)
} else {
break
}
}
return res
}
}
| mit | 46b280bb1d09e2f4c535950122390780 | 26.988235 | 136 | 0.57377 | 4.855102 | false | false | false | false |
sarvex/SwiftRecepies | Multimedia/Playing Video Files/Playing Video Files/ViewController.swift | 1 | 4304 | //
// ViewController.swift
// Playing Video Files
//
// Created by Vandad Nahavandipoor on 7/10/14.
// Copyright (c) 2014 Pixolity Ltd. All rights reserved.
//
// These example codes are written for O'Reilly's iOS 8 Swift Programming Cookbook
// If you use these solutions in your apps, you can give attribution to
// Vandad Nahavandipoor for his work. Feel free to visit my blog
// at http://vandadnp.wordpress.com for daily tips and tricks in Swift
// and Objective-C and various other programming languages.
//
// You can purchase "iOS 8 Swift Programming Cookbook" from
// the following URL:
// http://shop.oreilly.com/product/0636920034254.do
//
// If you have any questions, you can contact me directly
// at [email protected]
// Similarly, if you find an error in these sample codes, simply
// report them to O'Reilly at the following URL:
// http://www.oreilly.com/catalog/errata.csp?isbn=0636920034254
import UIKit
import MediaPlayer
class ViewController: UIViewController {
var moviePlayer: MPMoviePlayerController?
var playButton: UIButton?
func videoHasFinishedPlaying(notification: NSNotification){
println("Video finished playing")
/* Find out what the reason was for the player to stop */
let reason =
notification.userInfo![MPMoviePlayerPlaybackDidFinishReasonUserInfoKey]
as! NSNumber?
if let theReason = reason{
let reasonValue = MPMovieFinishReason(rawValue: theReason.integerValue)
switch reasonValue!{
case .PlaybackEnded:
/* The movie ended normally */
println("Playback Ended")
case .PlaybackError:
/* An error happened and the movie ended */
println("Error happened")
case .UserExited:
/* The user exited the player */
println("User exited")
default:
println("Another event happened")
}
println("Finish Reason = \(theReason)")
stopPlayingVideo()
}
}
func stopPlayingVideo() {
if let player = moviePlayer{
NSNotificationCenter.defaultCenter().removeObserver(self)
player.stop()
player.view.removeFromSuperview()
}
}
func startPlayingVideo(){
/* First let's construct the URL of the file in our application bundle
that needs to get played by the movie player */
let mainBundle = NSBundle.mainBundle()
let url = mainBundle.URLForResource("Sample", withExtension: "m4v")
/* If we have already created a movie player before,
let's try to stop it */
if let player = moviePlayer{
stopPlayingVideo()
}
/* Now create a new movie player using the URL */
moviePlayer = MPMoviePlayerController(contentURL: url)
if let player = moviePlayer{
/* Listen for the notification that the movie player sends us
whenever it finishes playing */
NSNotificationCenter.defaultCenter().addObserver(self,
selector: "videoHasFinishedPlaying:",
name: MPMoviePlayerPlaybackDidFinishNotification,
object: nil)
println("Successfully instantiated the movie player")
/* Scale the movie player to fit the aspect ratio */
player.scalingMode = .AspectFit
view.addSubview(player.view)
player.setFullscreen(true, animated: false)
/* Let's start playing the video in full screen mode */
player.play()
} else {
println("Failed to instantiate the movie player")
}
}
override func viewDidLoad() {
super.viewDidLoad()
playButton = UIButton.buttonWithType(.System) as? UIButton
if let button = playButton{
/* Add our button to the screen. Pressing this button
will start the video playback */
button.frame = CGRect(x: 0, y: 0, width: 70, height: 37)
button.center = view.center
button.autoresizingMask =
.FlexibleTopMargin |
.FlexibleLeftMargin |
.FlexibleBottomMargin |
.FlexibleRightMargin
button.addTarget(self,
action: "startPlayingVideo",
forControlEvents: .TouchUpInside)
button.setTitle("Play", forState: .Normal)
view.addSubview(button)
}
}
}
| isc | b34c2ac6341050f204beacaca7e2fc43 | 27.693333 | 83 | 0.65381 | 4.941447 | false | false | false | false |
benlangmuir/swift | benchmark/single-source/SortArrayInClass.swift | 7 | 2484 | //===--- SortArrayInClass.swift -------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2019 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
// This benchmark is derived from user code that encountered a major
// performance problem in normal usage. Contributed by Saleem
// Abdulrasool (compnerd).
//
//===----------------------------------------------------------------------===//
import TestsUtils
// Specifically tests efficient access to Array subscript when the
// array is a class property, but also generally tests quicksort in a
// class which needs a slew of array optimizations, uniqueness, bounds
// and exclusivity optimizations.
public let benchmarks = [
BenchmarkInfo(
name: "SortArrayInClass",
runFunction: run_SortArrayInClass,
tags: [.abstraction, .safetychecks, .exclusivity, .algorithm, .api, .Array])
]
let largeArraySize = 10000
class Sorter {
var array: [Int]
init(size: Int) {
array = Array((0..<size).reversed())
}
private func _swap(i: Int, j: Int) {
let t = array[i]
// This currently copies the entire array. Assigning to a
// temporary, or using swapAt would avoid the copy, but users
// shouldn't need to know that.
array[i] = array[j]
array[j] = t
}
private func _quicksort(left: Int, right: Int) {
if left < right {
let pivot = array[left + ((right - left) / 2)]
var left_new = left
var right_new = right
repeat {
while array[left_new] < pivot {
left_new += 1
}
while pivot < array[right_new] {
right_new -= 1
}
if left_new <= right_new {
_swap(i:left_new, j:right_new)
left_new += 1
right_new -= 1
}
} while left_new <= right_new
_quicksort(left: left, right: right_new)
_quicksort(left: left_new, right:right)
}
}
func quicksort() {
_quicksort(left:0, right:array.count - 1);
}
}
public func run_SortArrayInClass(_ n: Int) {
for _ in 1...n {
// The array needs to be reinitialized before each sort, so it
// can't be a setup/tearDown function.
let sorter = Sorter(size: largeArraySize)
sorter.quicksort()
}
}
| apache-2.0 | b8765a8916a0d7d24bffecdfd9193ffc | 28.223529 | 80 | 0.609098 | 3.968051 | false | false | false | false |
kwonye/calcupad | Calcupad/AppDelegate.swift | 2 | 6103 | //
// AppDelegate.swift
// Calcupad
//
// Created by Will Kwon on 7/30/16.
// Copyright © 2016 Will Kwon. All rights reserved.
//
import UIKit
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
// Saves changes in the application's managed object context before the application terminates.
self.saveContext()
}
// MARK: - Core Data stack
lazy var applicationDocumentsDirectory: URL = {
// The directory the application uses to store the Core Data store file. This code uses a directory named "com.willkwon.Calcupad" in the application's documents Application Support directory.
let urls = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
return urls[urls.count-1]
}()
lazy var managedObjectModel: NSManagedObjectModel = {
// The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model.
let modelURL = Bundle.main.url(forResource: "Calcupad", withExtension: "momd")!
return NSManagedObjectModel(contentsOf: modelURL)!
}()
lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = {
// The persistent store coordinator for the application. This implementation creates and returns a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail.
// Create the coordinator and store
let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
let url = self.applicationDocumentsDirectory.appendingPathComponent("SingleViewCoreData.sqlite")
var failureReason = "There was an error creating or loading the application's saved data."
do {
try coordinator.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: url, options: nil)
} catch {
// Report any error we got.
var dict = [String: AnyObject]()
dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data" as AnyObject?
dict[NSLocalizedFailureReasonErrorKey] = failureReason as AnyObject?
dict[NSUnderlyingErrorKey] = error as NSError
let wrappedError = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict)
// Replace this with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog("Unresolved error \(wrappedError), \(wrappedError.userInfo)")
abort()
}
return coordinator
}()
lazy var managedObjectContext: NSManagedObjectContext = {
// Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail.
let coordinator = self.persistentStoreCoordinator
var managedObjectContext = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType)
managedObjectContext.persistentStoreCoordinator = coordinator
return managedObjectContext
}()
// MARK: - Core Data Saving support
func saveContext () {
if managedObjectContext.hasChanges {
do {
try managedObjectContext.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
let nserror = error as NSError
NSLog("Unresolved error \(nserror), \(nserror.userInfo)")
abort()
}
}
}
}
| mit | ff779aa4ef43170235dab0180afd0d63 | 53.972973 | 291 | 0.71665 | 5.805899 | false | false | false | false |
18775134221/SwiftBase | SwiftTest/SwiftTest/Classes/Main/View/StartView.swift | 2 | 1502 | //
// StartView.swift
// SwiftTest
//
// Created by MAC on 2016/12/27.
// Copyright © 2016年 MAC. All rights reserved.
//
import UIKit
import Foundation
class StartView: UIView {
private let kStarCount: Int = 5
var level: CGFloat! {
didSet{
var fullCount: Int = Int(level)
// 满星部分
for i in 0..<fullCount {
self.makeStarView(imageNameStr: "", startPosition: i);
}
let m: CGFloat = level - CGFloat(fullCount)
if m > 0 {
self.makeStarView(imageNameStr: "", startPosition: fullCount);
fullCount += 1
}
for j in fullCount..<kStarCount {
self.makeStarView(imageNameStr: "", startPosition: j);
}
}
}
fileprivate func makeStarView(imageNameStr: String, startPosition: NSInteger) {
var imageView: UIImageView?
if subviews.count == kStarCount {
imageView = subviews[startPosition] as? UIImageView
imageView?.image = UIImage(named: imageNameStr)
return
}
imageView = UIImageView()
imageView?.image = UIImage(named: imageNameStr)
imageView?.sizeToFit()
imageView?.frame = CGRect(x: (imageView?.frame.size.width)! * CGFloat(startPosition), y: 0, width: (imageView?.frame.size.width)!, height: (imageView?.frame.size.height)!)
addSubview(imageView!)
}
}
| apache-2.0 | 08140cdb0062c010ba66260c51fcadd5 | 29.428571 | 179 | 0.56338 | 4.464072 | false | false | false | false |
leonereveel/Moya | Demo/Tests/MoyaProviderIntegrationTests.swift | 1 | 11511 | import Quick
import Moya
import Nimble
import OHHTTPStubs
import Alamofire
func beIndenticalToResponse(expectedValue: Moya.Response) -> MatcherFunc<Moya.Response> {
return MatcherFunc { actualExpression, failureMessage in
do {
let instance = try actualExpression.evaluate()
return instance === expectedValue
} catch {
return false
}
}
}
class MoyaProviderIntegrationTests: QuickSpec {
override func spec() {
let userMessage = NSString(data: GitHub.UserProfile("ashfurrow").sampleData, encoding: NSUTF8StringEncoding)
let zenMessage = NSString(data: GitHub.Zen.sampleData, encoding: NSUTF8StringEncoding)
beforeEach {
OHHTTPStubs.stubRequestsPassingTest({$0.URL!.path == "/zen"}) { _ in
return OHHTTPStubsResponse(data: GitHub.Zen.sampleData, statusCode: 200, headers: nil)
}
OHHTTPStubs.stubRequestsPassingTest({$0.URL!.path == "/users/ashfurrow"}) { _ in
return OHHTTPStubsResponse(data: GitHub.UserProfile("ashfurrow").sampleData, statusCode: 200, headers: nil)
}
OHHTTPStubs.stubRequestsPassingTest({$0.URL!.path == "/basic-auth/user/passwd"}) { _ in
return OHHTTPStubsResponse(data: HTTPBin.BasicAuth.sampleData, statusCode: 200, headers: nil)
}
}
afterEach {
OHHTTPStubs.removeAllStubs()
}
describe("valid endpoints") {
describe("with live data") {
describe("a provider") {
var provider: MoyaProvider<GitHub>!
beforeEach {
provider = MoyaProvider<GitHub>()
}
it("returns real data for zen request") {
var message: String?
waitUntil { done in
provider.request(.Zen) { result in
if case let .Success(response) = result {
message = NSString(data: response.data, encoding: NSUTF8StringEncoding) as? String
}
done()
}
}
expect(message) == zenMessage
}
it("returns real data for user profile request") {
var message: String?
waitUntil { done in
let target: GitHub = .UserProfile("ashfurrow")
provider.request(target) { result in
if case let .Success(response) = result {
message = NSString(data: response.data, encoding: NSUTF8StringEncoding) as? String
}
done()
}
}
expect(message) == userMessage
}
it("uses a custom Alamofire.Manager request generation") {
let manager = StubManager()
let provider = MoyaProvider<GitHub>(manager: manager)
waitUntil { done in
provider.request(GitHub.Zen) { _ in done() }
}
expect(manager.called) == true
}
it("uses other background queue") {
var isMainThread: Bool?
let queue = dispatch_queue_create("background_queue", DISPATCH_QUEUE_CONCURRENT)
let target: GitHub = .Zen
waitUntil { done in
provider.request(target, queue:queue) { _ in
isMainThread = NSThread.isMainThread()
done()
}
}
expect(isMainThread) == false
}
it("uses main queue") {
var isMainThread: Bool?
let target: GitHub = .Zen
waitUntil { done in
provider.request(target) { _ in
isMainThread = NSThread.isMainThread()
done()
}
}
expect(isMainThread) == true
}
}
describe("a provider with credential plugin") {
it("credential closure returns nil") {
var called = false
let plugin = CredentialsPlugin { _ in
called = true
return nil
}
let provider = MoyaProvider<HTTPBin>(plugins: [plugin])
expect(provider.plugins.count).to(equal(1))
waitUntil { done in
provider.request(.BasicAuth) { _ in done() }
}
expect(called) == true
}
it("credential closure returns valid username and password") {
var called = false
var returnedData: NSData?
let plugin = CredentialsPlugin { _ in
called = true
return NSURLCredential(user: "user", password: "passwd", persistence: .None)
}
let provider = MoyaProvider<HTTPBin>(plugins: [plugin])
let target = HTTPBin.BasicAuth
waitUntil { done in
provider.request(target) { result in
if case let .Success(response) = result {
returnedData = response.data
}
done()
}
}
expect(called) == true
expect(returnedData) == target.sampleData
}
}
describe("a provider with network activity plugin") {
it("notifies at the beginning of network requests") {
var called = false
let plugin = NetworkActivityPlugin { change in
if change == .Began {
called = true
}
}
let provider = MoyaProvider<GitHub>(plugins: [plugin])
waitUntil { done in
provider.request(.Zen) { _ in done() }
}
expect(called) == true
}
it("notifies at the end of network requests") {
var called = false
let plugin = NetworkActivityPlugin { change in
if change == .Ended {
called = true
}
}
let provider = MoyaProvider<GitHub>(plugins: [plugin])
waitUntil { done in
provider.request(.Zen) { _ in done() }
}
expect(called) == true
}
}
describe("a provider with network logger plugin") {
var log = ""
var plugin: NetworkLoggerPlugin!
beforeEach {
log = ""
plugin = NetworkLoggerPlugin(verbose: true, output: { printing in
//mapping the Any... from items to a string that can be compared
let stringArray: [String] = printing.items.map { $0 as? String }.flatMap { $0 }
let string: String = stringArray.reduce("") { $0 + $1 + " " }
log += string
})
}
it("logs the request") {
let provider = MoyaProvider<GitHub>(plugins: [plugin])
waitUntil { done in
provider.request(GitHub.Zen) { _ in done() }
}
expect(log).to( contain("Request:") )
expect(log).to( contain("{ URL: https://api.github.com/zen }") )
expect(log).to( contain("Request Headers: [:]") )
expect(log).to( contain("HTTP Request Method: GET") )
expect(log).to( contain("Response:") )
expect(log).to( contain("{ URL: https://api.github.com/zen } { status code: 200, headers") )
expect(log).to( contain("\"Content-Length\" = 43;") )
}
}
}
describe("a reactive provider with SignalProducer") {
var provider: ReactiveCocoaMoyaProvider<GitHub>!
beforeEach {
provider = ReactiveCocoaMoyaProvider<GitHub>()
}
it("returns some data for zen request") {
var message: String?
waitUntil { done in
provider.request(.Zen).startWithNext { response in
message = NSString(data: response.data, encoding: NSUTF8StringEncoding) as? String
done()
}
}
expect(message) == zenMessage
}
it("returns some data for user profile request") {
var message: String?
waitUntil { done in
let target: GitHub = .UserProfile("ashfurrow")
provider.request(target).startWithNext { response in
message = NSString(data: response.data, encoding: NSUTF8StringEncoding) as? String
done()
}
}
expect(message) == userMessage
}
}
}
}
}
class StubManager: Manager {
var called = false
override func request(URLRequest: URLRequestConvertible) -> Request {
called = true
return super.request(URLRequest)
}
}
| mit | 2dd5ab666b8163184340ddef1482fc00 | 40.858182 | 123 | 0.396925 | 7.010353 | false | false | false | false |
gottesmm/swift | test/attr/attr_inlineable.swift | 2 | 8253 | // RUN: %target-typecheck-verify-swift -swift-version 4
@_inlineable struct TestInlineableStruct {}
// expected-error@-1 {{@_inlineable cannot be applied to this declaration}}
private func privateFunction() {}
// expected-note@-1 5{{global function 'privateFunction()' is not '@_versioned' or public}}
fileprivate func fileprivateFunction() {}
// expected-note@-1 5{{global function 'fileprivateFunction()' is not '@_versioned' or public}}
func internalFunction() {}
// expected-note@-1 5{{global function 'internalFunction()' is not '@_versioned' or public}}
@_versioned func versionedFunction() {}
public func publicFunction() {}
func internalIntFunction() -> Int {}
// expected-note@-1 2{{global function 'internalIntFunction()' is not '@_versioned' or public}}
private struct PrivateStruct {}
// expected-note@-1 3{{struct 'PrivateStruct' is not '@_versioned' or public}}
struct InternalStruct {}
// expected-note@-1 4{{struct 'InternalStruct' is not '@_versioned' or public}}
@_versioned struct VersionedStruct {
@_versioned init() {}
}
public struct PublicStruct {
public init() {}
}
public struct Struct {
@_transparent
public func publicTransparentMethod() {
struct Nested {}
// expected-error@-1 {{type 'Nested' cannot be nested inside a '@_transparent' function}}
publicFunction()
// OK
versionedFunction()
// OK
internalFunction()
// expected-error@-1 {{global function 'internalFunction()' is internal and cannot be referenced from a '@_transparent' function}}
fileprivateFunction()
// expected-error@-1 {{global function 'fileprivateFunction()' is fileprivate and cannot be referenced from a '@_transparent' function}}
privateFunction()
// expected-error@-1 {{global function 'privateFunction()' is private and cannot be referenced from a '@_transparent' function}}
}
@_inlineable
public func publicInlineableMethod() {
struct Nested {}
// expected-error@-1 {{type 'Nested' cannot be nested inside an '@_inlineable' function}}
let _: PublicStruct
let _: VersionedStruct
let _: InternalStruct
// expected-error@-1 {{struct 'InternalStruct' is internal and cannot be referenced from an '@_inlineable' function}}
let _: PrivateStruct
// expected-error@-1 {{struct 'PrivateStruct' is private and cannot be referenced from an '@_inlineable' function}}
let _ = PublicStruct.self
let _ = VersionedStruct.self
let _ = InternalStruct.self
// expected-error@-1 {{struct 'InternalStruct' is internal and cannot be referenced from an '@_inlineable' function}}
let _ = PrivateStruct.self
// expected-error@-1 {{struct 'PrivateStruct' is private and cannot be referenced from an '@_inlineable' function}}
let _ = PublicStruct()
let _ = VersionedStruct()
let _ = InternalStruct()
// expected-error@-1 {{struct 'InternalStruct' is internal and cannot be referenced from an '@_inlineable' function}}
let _ = PrivateStruct()
// expected-error@-1 {{struct 'PrivateStruct' is private and cannot be referenced from an '@_inlineable' function}}
}
@inline(__always)
public func publicInlineAlwaysMethod(x: Any) {
struct Nested {}
// expected-error@-1 {{type 'Nested' cannot be nested inside an '@inline(__always)' function}}
switch x {
case is InternalStruct:
// expected-error@-1 {{struct 'InternalStruct' is internal and cannot be referenced from an '@inline(__always)' function}}
_ = ()
}
}
private func privateMethod() {}
// expected-note@-1 {{instance method 'privateMethod()' is not '@_versioned' or public}}
@_transparent
@_versioned
func versionedTransparentMethod() {
struct Nested {}
// expected-error@-1 {{type 'Nested' cannot be nested inside a '@_transparent' function}}
privateMethod()
// expected-error@-1 {{instance method 'privateMethod()' is private and cannot be referenced from a '@_transparent' function}}
}
@_inlineable
@_versioned
func versionedInlineableMethod() {
struct Nested {}
// expected-error@-1 {{type 'Nested' cannot be nested inside an '@_inlineable' function}}
}
@inline(__always)
@_versioned
func versionedInlineAlwaysMethod() {
struct Nested {}
// expected-error@-1 {{type 'Nested' cannot be nested inside an '@inline(__always)' function}}
}
@_transparent
func internalTransparentMethod() {
struct Nested {}
// OK
}
@_inlineable
func internalInlineableMethod() {
struct Nested {}
// OK
}
@inline(__always)
func internalInlineAlwaysMethod() {
struct Nested {}
// OK
}
}
func internalFunctionWithDefaultValue(
x: Int = {
struct Nested {}
// OK
publicFunction()
// OK
versionedFunction()
// OK
internalFunction()
// OK
fileprivateFunction()
// OK
privateFunction()
// OK
return 0
}(),
y: Int = internalIntFunction()) {}
@_versioned func versionedFunctionWithDefaultValue(
x: Int = {
struct Nested {}
// expected-error@-1 {{type 'Nested' cannot be nested inside a default argument value}}
// FIXME: Some errors below are diagnosed twice
publicFunction()
// OK
versionedFunction()
// OK
internalFunction()
// expected-error@-1 2{{global function 'internalFunction()' is internal and cannot be referenced from a default argument value}}
fileprivateFunction()
// expected-error@-1 2{{global function 'fileprivateFunction()' is fileprivate and cannot be referenced from a default argument value}}
privateFunction()
// expected-error@-1 2{{global function 'privateFunction()' is private and cannot be referenced from a default argument value}}
return 0
}(),
y: Int = internalIntFunction()) {}
// expected-error@-1 {{global function 'internalIntFunction()' is internal and cannot be referenced from a default argument value}}
public func publicFunctionWithDefaultValue(
x: Int = {
struct Nested {}
// expected-error@-1 {{type 'Nested' cannot be nested inside a default argument value}}
// FIXME: Some errors below are diagnosed twice
publicFunction()
// OK
versionedFunction()
// OK
internalFunction()
// expected-error@-1 2{{global function 'internalFunction()' is internal and cannot be referenced from a default argument value}}
fileprivateFunction()
// expected-error@-1 2{{global function 'fileprivateFunction()' is fileprivate and cannot be referenced from a default argument value}}
privateFunction()
// expected-error@-1 2{{global function 'privateFunction()' is private and cannot be referenced from a default argument value}}
return 0
}(),
y: Int = internalIntFunction()) {}
// expected-error@-1 {{global function 'internalIntFunction()' is internal and cannot be referenced from a default argument value}}
// Make sure protocol extension members can reference protocol requirements
// (which do not inherit the @_versioned attribute).
@_versioned
protocol VersionedProtocol {
associatedtype T
func requirement() -> T
}
extension VersionedProtocol {
func internalMethod() {}
// expected-note@-1 {{instance method 'internalMethod()' is not '@_versioned' or public}}
@_inlineable
@_versioned
func versionedMethod() -> T {
internalMethod()
// expected-error@-1 {{instance method 'internalMethod()' is internal and cannot be referenced from an '@_inlineable' function}}
return requirement()
}
}
protocol InternalProtocol {
associatedtype T
func requirement() -> T
}
extension InternalProtocol {
func internalMethod() {}
// FIXME: https://bugs.swift.org/browse/SR-3684
//
// This should either complain that the method cannot be '@_versioned' since
// we're inside an extension of an internal protocol, or if such methods are
// allowed, we should diagnose the reference to 'internalMethod()' from the
// body.
@_inlineable
@_versioned
func versionedMethod() -> T {
internalMethod()
return requirement()
}
// Ditto, except s/@_versioned/public/.
@_inlineable
public func publicMethod() -> T {
internalMethod()
return requirement()
}
}
| apache-2.0 | a6eaec4f62975d39d414766ab46b0a40 | 32.278226 | 141 | 0.681449 | 4.803842 | false | false | false | false |
bravelocation/yeltzland-ios | watchkitapp Extension/Views/LeagueTableView.swift | 1 | 2962 | //
// LeagueTableView.swift
// watchkitapp Extension
//
// Created by John Pollard on 29/05/2022.
// Copyright © 2022 John Pollard. All rights reserved.
//
import SwiftUI
struct LeagueTableView: View {
@ObservedObject var tableData: LeagueTableData
let numberFontSize = 22.0
var body: some View {
VStack {
if self.tableData.table == nil {
Text("League table not available").padding()
}
List(self.tableData.table?.teams ?? []) { team in
VStack(alignment: .leading) {
Spacer()
HStack(alignment: .center) {
Text(team.displayPosition)
.foregroundColor(team.watchPositionColor)
Text(team.displayName)
.font(.headline)
}
HStack(alignment: .firstTextBaseline) {
Text("P")
.foregroundColor(Color("light-blue"))
.font(.footnote)
Text("\(team.allMatches.played)")
.font(.system(size: numberFontSize))
Text("Pts")
.foregroundColor(Color("light-blue"))
.font(.footnote)
Text("\(team.totalPoints)")
.font(.system(size: numberFontSize))
Text("GD")
.foregroundColor(Color("light-blue"))
.font(.footnote)
Text("\(team.goalDifference)")
.font(.footnote.italic())
}
Spacer()
}
.listRowPlatterColor(team.isYeltz ? Color("yeltz-blue") : Color("dark-blue"))
.frame(minHeight: 76.0, alignment: .topLeading)
}
.listStyle(PlainListStyle())
}
.overlay(
Button(action: {
self.tableData.refreshData()
}, label: {
Image(systemName: "arrow.clockwise")
.font(.footnote)
.padding()
})
.frame(width: 24.0, height: 24.0, alignment: .center)
.background(Color.gray.opacity(0.5))
.cornerRadius(12), alignment: .topTrailing
)
.onAppear {
self.tableData.refreshData()
}
.navigationBarTitle(Text(self.tableData.state == .isLoading ? "Loading ..." : "League Table"))
}
}
#if DEBUG
struct LeagueTableView_Previews: PreviewProvider {
static var previews: some View {
LeagueTableView(tableData: LeagueTableData(dataProvider: PreviewLeagueTableDataProvider()))
}
}
#endif
| mit | 4d082ee831c0eb577810baae954f961f | 33.430233 | 102 | 0.456265 | 5.4631 | false | false | false | false |
vulgur/Sources | CodeReader/View/CommitFileListViewController.swift | 1 | 3798 | //
// CommitFileListViewController.swift
// CodeReader
//
// Created by vulgur on 2016/10/19.
// Copyright © 2016年 MAD. All rights reserved.
//
import UIKit
import Crashlytics
class CommitFileListViewController: BaseTableViewController {
var viewModel: CommitFileListViewModel!
let CommitFileCellIdentifier = "CommitFileCell"
override func viewDidLoad() {
super.viewDidLoad()
self.navigationItem.title = "Commit Files"
self.tableView.hideEmptyCells()
Answers.logCustomEvent(withName: "Show Commit File List", customAttributes: nil)
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
bindViewModel()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: Private methods
private func bindViewModel() {
viewModel.commitFiles.asDriver()
.drive(tableView.rx.items(cellIdentifier: CommitFileCellIdentifier, cellType: CommitFileCell.self)) { (row, commitFile, cell) in
if let filename = commitFile.filename {
cell.filenameLabel.text = self.shortenFilename(filename: filename)
}
if let additions = commitFile.additions {
cell.additionsLabel.text = "+\(additions)"
}
if let deletions = commitFile.deletions {
cell.deletionsLabel.text = "-\(deletions)"
}
switch commitFile.status! {
case "added": cell.statusImageView.image = #imageLiteral(resourceName: "file_addition")
case "modified": cell.statusImageView.image = #imageLiteral(resourceName: "file_modification")
case "deleted": cell.statusImageView.image = #imageLiteral(resourceName: "file_deletion")
default: cell.statusImageView.image = #imageLiteral(resourceName: "file_addition")
}
}.addDisposableTo(disposeBag)
viewModel.loadCommitFileList().subscribe(onNext: { [unowned self] (commitFiles) in
self.viewModel.commitFiles.value = commitFiles
}).addDisposableTo(disposeBag)
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return viewModel.commitFiles.value.count
}
private func shortenFilename(filename: String) -> String {
let paths = filename.components(separatedBy: "/")
if paths.count > 2 {
return ".../".appending(paths[paths.count-2]).appending("/").appending(paths.last!)
}
return filename
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
// performSegue(withIdentifier: "ShowFileChange", sender: indexPath)
}
// MARK: - Navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "ShowFileChange" {
if let destinationVC = segue.destination as? FileChangeViewController,
let indexPath = self.tableView.indexPathForSelectedRow {
let file = viewModel.commitFiles.value[indexPath.row]
destinationVC.patchString = file.patch
destinationVC.navigationItem.title = file.filename?.fileBaseName
}
}
}
}
| mit | a6d02eb922c23be58542928b2c722d59 | 36.205882 | 140 | 0.631094 | 5.352609 | false | false | false | false |
Fenrikur/ef-app_ios | EurofurenceTests/Presenter Tests/Dealer Detail/Presenter Tests/WhenBindingDealerLocationAndAvailability_DealerDetailPresenterShould.swift | 1 | 2972 | @testable import Eurofurence
import EurofurenceModel
import XCTest
class WhenBindingDealerLocationAndAvailability_DealerDetailPresenterShould: XCTestCase {
func testBindTheProducedMapGraphicFromTheViewModelOntoTheComponent() {
let locationAndAvailabilityViewModel = DealerDetailLocationAndAvailabilityViewModel.random
let viewModel = FakeDealerDetailLocationAndAvailabilityViewModel(location: locationAndAvailabilityViewModel)
let interactor = FakeDealerDetailInteractor(viewModel: viewModel)
let context = DealerDetailPresenterTestBuilder().with(interactor).build()
context.simulateSceneDidLoad()
context.bindComponent(at: 0)
XCTAssertEqual(locationAndAvailabilityViewModel.mapPNGGraphicData, context.boundLocationAndAvailabilityComponent?.capturedMapPNGGraphicData)
}
func testBindTheLimitedAvailabilityWarningFromTheViewModelOntoTheComponent() {
let locationAndAvailabilityViewModel = DealerDetailLocationAndAvailabilityViewModel.random
let viewModel = FakeDealerDetailLocationAndAvailabilityViewModel(location: locationAndAvailabilityViewModel)
let interactor = FakeDealerDetailInteractor(viewModel: viewModel)
let context = DealerDetailPresenterTestBuilder().with(interactor).build()
context.simulateSceneDidLoad()
context.bindComponent(at: 0)
XCTAssertEqual(locationAndAvailabilityViewModel.limitedAvailabilityWarning, context.boundLocationAndAvailabilityComponent?.capturedLimitedAvailabilityWarning)
}
func testBindTheLocatedInAfterDarkDealersDenNoticeOntoTheComponent() {
let locationAndAvailabilityViewModel = DealerDetailLocationAndAvailabilityViewModel.random
let viewModel = FakeDealerDetailLocationAndAvailabilityViewModel(location: locationAndAvailabilityViewModel)
let interactor = FakeDealerDetailInteractor(viewModel: viewModel)
let context = DealerDetailPresenterTestBuilder().with(interactor).build()
context.simulateSceneDidLoad()
context.bindComponent(at: 0)
let expected = locationAndAvailabilityViewModel.locatedInAfterDarkDealersDenMessage
let actual = context.boundLocationAndAvailabilityComponent?.capturedLocatedInAfterDarkDealersDenMessage
XCTAssertEqual(expected, actual)
}
func testBindTheLocationAndAvailabilityTitleOntoTheComponent() {
let locationAndAvailabilityViewModel = DealerDetailLocationAndAvailabilityViewModel.random
let viewModel = FakeDealerDetailLocationAndAvailabilityViewModel(location: locationAndAvailabilityViewModel)
let interactor = FakeDealerDetailInteractor(viewModel: viewModel)
let context = DealerDetailPresenterTestBuilder().with(interactor).build()
context.simulateSceneDidLoad()
context.bindComponent(at: 0)
XCTAssertEqual(locationAndAvailabilityViewModel.title, context.boundLocationAndAvailabilityComponent?.capturedTitle)
}
}
| mit | 6e423075fbebb06bbec4bbd2213d6218 | 55.075472 | 166 | 0.809892 | 8.054201 | false | true | false | false |
DerrickQin2853/SinaWeibo-Swift | SinaWeibo/SinaWeibo/AppDelegate.swift | 1 | 1586 | //
// AppDelegate.swift
// SinaWeibo
//
// Created by admin on 16/9/22.
// Copyright © 2016年 Derrick_Qin. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
registerNotification()
window = UIWindow(frame: UIScreen.main.bounds)
window?.backgroundColor = UIColor.white
window?.rootViewController = DQUserAccountViewModel.sharedViewModel.userLogin ? DQWelcomeViewController() : DQTabBarController()
window?.makeKeyAndVisible()
return true
}
//注册通知
private func registerNotification() {
NotificationCenter.default.addObserver(self, selector: #selector(setRootViewController(notification:)), name: Notification.Name(rawValue:kChangeRootControllerNotification), object: nil)
}
//响应通知,切换根控制器
@objc private func setRootViewController(notification: NSNotification) {
if (notification.object as! NSString).isEqual(to: "TabBar") {
window?.rootViewController = DQTabBarController()
}
else if (notification.object as! NSString).isEqual(to: "Welcome") {
window?.rootViewController = DQWelcomeViewController()
}
}
//没有逻辑意义,但保持代码美观
deinit {
NotificationCenter.default.removeObserver(self)
}
}
| mit | 3f9f01975849a4e26c08dad11a71a08a | 30.770833 | 193 | 0.683934 | 5.083333 | false | false | false | false |
danielmartinprieto/AudioPlayer | AudioPlayer/AudioPlayer/player/extensions/AudioPlayer+Queue.swift | 2 | 2992 | //
// AudioPlayer+Queue.swift
// AudioPlayer
//
// Created by Kevin DELANNOY on 29/03/16.
// Copyright © 2016 Kevin Delannoy. All rights reserved.
//
extension AudioPlayer {
/// The items in the queue if any.
public var items: [AudioItem]? {
return queue?.queue
}
/// The current item index in queue.
public var currentItemIndexInQueue: Int? {
return currentItem.flatMap { queue?.items.firstIndex(of: $0) }
}
/// A boolean value indicating whether there is a next item to play or not.
public var hasNext: Bool {
return queue?.hasNextItem ?? false
}
/// A boolean value indicating whether there is a previous item to play or not.
public var hasPrevious: Bool {
return queue?.hasPreviousItem ?? false
}
/// Plays an item.
///
/// - Parameter item: The item to play.
public func play(item: AudioItem) {
play(items: [item])
}
/// Creates a queue according to the current mode and plays it.
///
/// - Parameters:
/// - items: The items to play.
/// - index: The index to start the player with.
public func play(items: [AudioItem], startAtIndex index: Int = 0) {
if !items.isEmpty {
queue = AudioItemQueue(items: items, mode: mode)
queue?.delegate = self
if let realIndex = queue?.queue.firstIndex(of: items[index]) {
queue?.nextPosition = realIndex
}
currentItem = queue?.nextItem()
} else {
stop()
queue = nil
}
}
/// Adds an item at the end of the queue. If queue is empty and player isn't playing, the behaviour will be similar
/// to `play(item:)`.
///
/// - Parameter item: The item to add.
public func add(item: AudioItem) {
add(items: [item])
}
/// Adds items at the end of the queue. If the queue is empty and player isn't playing, the behaviour will be
/// similar to `play(items:)`.
///
/// - Parameter items: The items to add.
public func add(items: [AudioItem]) {
if let queue = queue {
queue.add(items: items)
} else {
play(items: items)
}
}
/// Removes an item at a specific index in the queue.
///
/// - Parameter index: The index of the item to remove.
public func removeItem(at index: Int) {
queue?.remove(at: index)
}
}
extension AudioPlayer: AudioItemQueueDelegate {
/// Returns a boolean value indicating whether an item should be consider playable in the queue.
///
/// - Parameters:
/// - queue: The queue.
/// - item: The item we ask the information for.
/// - Returns: A boolean value indicating whether an item should be consider playable in the queue.
func audioItemQueue(_ queue: AudioItemQueue, shouldConsiderItem item: AudioItem) -> Bool {
return delegate?.audioPlayer(self, shouldStartPlaying: item) ?? true
}
}
| mit | b01be348c3504f4fe80159a09e3b301f | 30.819149 | 119 | 0.60214 | 4.303597 | false | false | false | false |
NghiaTranUIT/Unofficial-Uber-macOS | UberGo/UberGo/SearchCollectionView.swift | 1 | 5568 | //
// SearchCollectionView.swift
// UberGo
//
// Created by Nghia Tran on 6/11/17.
// Copyright © 2017 Nghia Tran. All rights reserved.
//
import Cocoa
import RxSwift
import UberGoCore
protocol SearchCollectionViewDelegate: class {
func searchCollectionViewSearchPersonalPlace(_ placeObj: PlaceObj)
func searchCollectionViewDidSelectPlace(_ placeObj: PlaceObj)
}
class SearchCollectionView: NSView {
// MARK: - OUTLET
@IBOutlet fileprivate weak var collectionView: UberCollectionView!
// MARK: - Variable
fileprivate var viewModel: SearchViewModelProtocol!
fileprivate let disposeBag = DisposeBag()
fileprivate var placeObjs: [PlaceObj] { return viewModel.output.searchPlacesVar.value }
weak var delegate: SearchCollectionViewDelegate?
// MARK: - View Cycle
override func awakeFromNib() {
super.awakeFromNib()
initCommon()
setupCollectionView()
}
// MARK: - Public
public func setupViewModel(_ viewModel: SearchViewModelProtocol) {
self.viewModel = viewModel
binding()
}
fileprivate func binding() {
// Reload search Place collectionView
viewModel.output.searchPlacesVar
.asObservable()
.subscribe(onNext: {[weak self] placeObjs in
guard let `self` = self else { return }
Logger.info("Place Search FOUND = \(placeObjs.count)")
self.collectionView.reloadData()
})
.addDisposableTo(disposeBag)
}
}
// MARK: - Private
extension SearchCollectionView {
fileprivate func initCommon() {
translatesAutoresizingMaskIntoConstraints = false
alphaValue = 0
isHidden = true
}
fileprivate func setupCollectionView() {
collectionView.delegate = self
collectionView.dataSource = self
collectionView.allowsMultipleSelection = false
collectionView.allowsEmptySelection = false
// Register
let nib = NSNib(nibNamed: "SearchPlaceCell", bundle: nil)
collectionView.register(nib, forItemWithIdentifier: "SearchPlaceCell")
// Flow
let flow = SearchCollectionViewFlowLayout()
flow.itemSize = CGSize(width: collectionView.bounds.width, height: 57)
collectionView.collectionViewLayout = flow
}
}
// MARK: - Layout
extension SearchCollectionView {
public func configureView(parenView: NSView, searchBarView: SearchBarView) {
translatesAutoresizingMaskIntoConstraints = false
topToBottom(of: searchBarView)
left(to: parenView)
right(to: parenView)
bottom(to: parenView)
}
public func layoutStateChanged(_ newState: MapViewLayoutState) {
switch newState {
case .searchFullScreen, .expand:
isHidden = false
alphaValue = 0
// Animate
NSAnimationContext.defaultAnimate({ _ in
self.alphaValue = 1
})
case .minimal, .tripMinimunActivity, .tripFullActivity, .productSelection:
isHidden = false
alphaValue = 1
// Animate
NSAnimationContext.defaultAnimate({ _ in
self.alphaValue = 0
}, completion: {
self.isHidden = true
})
}
}
}
// MARK: - XIBInitializable
extension SearchCollectionView: XIBInitializable {
typealias XibType = SearchCollectionView
}
// MARK: - NSCollectionViewDataSource
extension SearchCollectionView: NSCollectionViewDataSource {
func numberOfSections(in collectionView: NSCollectionView) -> Int {
return 1
}
func collectionView(_ collectionView: NSCollectionView, numberOfItemsInSection section: Int) -> Int {
return placeObjs.count
}
func collectionView(_ collectionView: NSCollectionView, itemForRepresentedObjectAt indexPath: IndexPath)
-> NSCollectionViewItem {
return getSearchCell(with: collectionView, indexPath: indexPath)
}
fileprivate func getSearchCell(with collectionView: NSCollectionView, indexPath: IndexPath)
-> NSCollectionViewItem {
// Guard
guard let cell = collectionView.makeItem(withIdentifier: "SearchPlaceCell", for: indexPath)
as? SearchPlaceCell else {
return NSCollectionViewItem()
}
let placeObj = placeObjs[indexPath.item]
cell.configurePlaceCell(placeObj)
return cell
}
}
// MARK: - NSCollectionViewDelegate
extension SearchCollectionView: NSCollectionViewDelegate, NSCollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: NSCollectionView, didSelectItemsAt indexPaths: Set<IndexPath>) {
let selection = indexPaths as NSSet
guard let selectedIndexPath = selection.allObjects.last as? IndexPath else { return }
// Data
let placeObj = placeObjs[selectedIndexPath.item]
// De-select
collectionView.deselectItems(at: indexPaths)
// If invalid personal place
// Add New place
if placeObj.invalid {
// Temporary disable this feature
return
// delegate?.searchCollectionViewSearchPersonalPlace(placeObj)
// return
}
// Select and reset data
viewModel.input.selectPlaceObjPublisher.onNext(placeObj)
viewModel.input.textSearchPublish.onNext("")
// Notify delegate
delegate?.searchCollectionViewDidSelectPlace(placeObj)
}
}
| mit | 504988f3bc3d03c4c731cb171b181793 | 28.930108 | 108 | 0.657266 | 5.674822 | false | false | false | false |
yuxiuyu/TrendBet | TrendBetting_0531换首页/Pods/Charts/Source/Charts/Renderers/LegendRenderer.swift | 4 | 20337 | //
// LegendRenderer.swift
// Charts
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/Charts
//
import Foundation
import CoreGraphics
#if !os(OSX)
import UIKit
#endif
@objc(ChartLegendRenderer)
open class LegendRenderer: Renderer
{
/// the legend object this renderer renders
@objc open var legend: Legend?
@objc public init(viewPortHandler: ViewPortHandler, legend: Legend?)
{
super.init(viewPortHandler: viewPortHandler)
self.legend = legend
}
/// Prepares the legend and calculates all needed forms, labels and colors.
@objc open func computeLegend(data: ChartData)
{
guard let legend = legend else { return }
if !legend.isLegendCustom
{
var entries: [LegendEntry] = []
// loop for building up the colors and labels used in the legend
for i in 0..<data.dataSetCount
{
guard let dataSet = data.getDataSetByIndex(i) else { continue }
var clrs: [NSUIColor] = dataSet.colors
let entryCount = dataSet.entryCount
// if we have a barchart with stacked bars
if dataSet is IBarChartDataSet &&
(dataSet as! IBarChartDataSet).isStacked
{
let bds = dataSet as! IBarChartDataSet
var sLabels = bds.stackLabels
for j in 0..<min(clrs.count, bds.stackSize)
{
entries.append(
LegendEntry(
label: sLabels[j % sLabels.count],
form: dataSet.form,
formSize: dataSet.formSize,
formLineWidth: dataSet.formLineWidth,
formLineDashPhase: dataSet.formLineDashPhase,
formLineDashLengths: dataSet.formLineDashLengths,
formColor: clrs[j]
)
)
}
if dataSet.label != nil
{
// add the legend description label
entries.append(
LegendEntry(
label: dataSet.label,
form: .none,
formSize: CGFloat.nan,
formLineWidth: CGFloat.nan,
formLineDashPhase: 0.0,
formLineDashLengths: nil,
formColor: nil
)
)
}
}
else if dataSet is IPieChartDataSet
{
let pds = dataSet as! IPieChartDataSet
for j in 0..<min(clrs.count, entryCount)
{
entries.append(
LegendEntry(
label: (pds.entryForIndex(j) as? PieChartDataEntry)?.label,
form: dataSet.form,
formSize: dataSet.formSize,
formLineWidth: dataSet.formLineWidth,
formLineDashPhase: dataSet.formLineDashPhase,
formLineDashLengths: dataSet.formLineDashLengths,
formColor: clrs[j]
)
)
}
if dataSet.label != nil
{
// add the legend description label
entries.append(
LegendEntry(
label: dataSet.label,
form: .none,
formSize: CGFloat.nan,
formLineWidth: CGFloat.nan,
formLineDashPhase: 0.0,
formLineDashLengths: nil,
formColor: nil
)
)
}
}
else if dataSet is ICandleChartDataSet &&
(dataSet as! ICandleChartDataSet).decreasingColor != nil
{
let candleDataSet = dataSet as! ICandleChartDataSet
entries.append(
LegendEntry(
label: nil,
form: dataSet.form,
formSize: dataSet.formSize,
formLineWidth: dataSet.formLineWidth,
formLineDashPhase: dataSet.formLineDashPhase,
formLineDashLengths: dataSet.formLineDashLengths,
formColor: candleDataSet.decreasingColor
)
)
entries.append(
LegendEntry(
label: dataSet.label,
form: dataSet.form,
formSize: dataSet.formSize,
formLineWidth: dataSet.formLineWidth,
formLineDashPhase: dataSet.formLineDashPhase,
formLineDashLengths: dataSet.formLineDashLengths,
formColor: candleDataSet.increasingColor
)
)
}
else
{ // all others
for j in 0..<min(clrs.count, entryCount)
{
let label: String?
// if multiple colors are set for a DataSet, group them
if j < clrs.count - 1 && j < entryCount - 1
{
label = nil
}
else
{ // add label to the last entry
label = dataSet.label
}
entries.append(
LegendEntry(
label: label,
form: dataSet.form,
formSize: dataSet.formSize,
formLineWidth: dataSet.formLineWidth,
formLineDashPhase: dataSet.formLineDashPhase,
formLineDashLengths: dataSet.formLineDashLengths,
formColor: clrs[j]
)
)
}
}
}
legend.entries = entries + legend.extraEntries
}
// calculate all dimensions of the legend
legend.calculateDimensions(labelFont: legend.font, viewPortHandler: viewPortHandler)
}
@objc open func renderLegend(context: CGContext)
{
guard let legend = legend else { return }
if !legend.enabled
{
return
}
let labelFont = legend.font
let labelTextColor = legend.textColor
let labelLineHeight = labelFont.lineHeight
let formYOffset = labelLineHeight / 2.0
var entries = legend.entries
let defaultFormSize = legend.formSize
let formToTextSpace = legend.formToTextSpace
let xEntrySpace = legend.xEntrySpace
let yEntrySpace = legend.yEntrySpace
let orientation = legend.orientation
let horizontalAlignment = legend.horizontalAlignment
let verticalAlignment = legend.verticalAlignment
let direction = legend.direction
// space between the entries
let stackSpace = legend.stackSpace
let yoffset = legend.yOffset
let xoffset = legend.xOffset
var originPosX: CGFloat = 0.0
switch horizontalAlignment
{
case .left:
if orientation == .vertical
{
originPosX = xoffset
}
else
{
originPosX = viewPortHandler.contentLeft + xoffset
}
if direction == .rightToLeft
{
originPosX += legend.neededWidth
}
case .right:
if orientation == .vertical
{
originPosX = viewPortHandler.chartWidth - xoffset
}
else
{
originPosX = viewPortHandler.contentRight - xoffset
}
if direction == .leftToRight
{
originPosX -= legend.neededWidth
}
case .center:
if orientation == .vertical
{
originPosX = viewPortHandler.chartWidth / 2.0
}
else
{
originPosX = viewPortHandler.contentLeft
+ viewPortHandler.contentWidth / 2.0
}
originPosX += (direction == .leftToRight
? +xoffset
: -xoffset)
// Horizontally layed out legends do the center offset on a line basis,
// So here we offset the vertical ones only.
if orientation == .vertical
{
if direction == .leftToRight
{
originPosX -= legend.neededWidth / 2.0 - xoffset
}
else
{
originPosX += legend.neededWidth / 2.0 - xoffset
}
}
}
switch orientation
{
case .horizontal:
var calculatedLineSizes = legend.calculatedLineSizes
var calculatedLabelSizes = legend.calculatedLabelSizes
var calculatedLabelBreakPoints = legend.calculatedLabelBreakPoints
var posX: CGFloat = originPosX
var posY: CGFloat
switch verticalAlignment
{
case .top:
posY = yoffset
case .bottom:
posY = viewPortHandler.chartHeight - yoffset - legend.neededHeight
case .center:
posY = (viewPortHandler.chartHeight - legend.neededHeight) / 2.0 + yoffset
}
var lineIndex: Int = 0
for i in 0 ..< entries.count
{
let e = entries[i]
let drawingForm = e.form != .none
let formSize = e.formSize.isNaN ? defaultFormSize : e.formSize
if i < calculatedLabelBreakPoints.count &&
calculatedLabelBreakPoints[i]
{
posX = originPosX
posY += labelLineHeight + yEntrySpace
}
if posX == originPosX &&
horizontalAlignment == .center &&
lineIndex < calculatedLineSizes.count
{
posX += (direction == .rightToLeft
? calculatedLineSizes[lineIndex].width
: -calculatedLineSizes[lineIndex].width) / 2.0
lineIndex += 1
}
let isStacked = e.label == nil // grouped forms have null labels
if drawingForm
{
if direction == .rightToLeft
{
posX -= formSize
}
drawForm(
context: context,
x: posX,
y: posY + formYOffset,
entry: e,
legend: legend)
if direction == .leftToRight
{
posX += formSize
}
}
if !isStacked
{
if drawingForm
{
posX += direction == .rightToLeft ? -formToTextSpace : formToTextSpace
}
if direction == .rightToLeft
{
posX -= calculatedLabelSizes[i].width
}
drawLabel(
context: context,
x: posX,
y: posY,
label: e.label!,
font: labelFont,
textColor: labelTextColor)
if direction == .leftToRight
{
posX += calculatedLabelSizes[i].width
}
posX += direction == .rightToLeft ? -xEntrySpace : xEntrySpace
}
else
{
posX += direction == .rightToLeft ? -stackSpace : stackSpace
}
}
case .vertical:
// contains the stacked legend size in pixels
var stack = CGFloat(0.0)
var wasStacked = false
var posY: CGFloat = 0.0
switch verticalAlignment
{
case .top:
posY = (horizontalAlignment == .center
? 0.0
: viewPortHandler.contentTop)
posY += yoffset
case .bottom:
posY = (horizontalAlignment == .center
? viewPortHandler.chartHeight
: viewPortHandler.contentBottom)
posY -= legend.neededHeight + yoffset
case .center:
posY = viewPortHandler.chartHeight / 2.0 - legend.neededHeight / 2.0 + legend.yOffset
}
for i in 0 ..< entries.count
{
let e = entries[i]
let drawingForm = e.form != .none
let formSize = e.formSize.isNaN ? defaultFormSize : e.formSize
var posX = originPosX
if drawingForm
{
if direction == .leftToRight
{
posX += stack
}
else
{
posX -= formSize - stack
}
drawForm(
context: context,
x: posX,
y: posY + formYOffset,
entry: e,
legend: legend)
if direction == .leftToRight
{
posX += formSize
}
}
if e.label != nil
{
if drawingForm && !wasStacked
{
posX += direction == .leftToRight ? formToTextSpace : -formToTextSpace
}
else if wasStacked
{
posX = originPosX
}
if direction == .rightToLeft
{
posX -= (e.label as NSString!).size(withAttributes: [NSAttributedStringKey.font: labelFont]).width
}
if !wasStacked
{
drawLabel(context: context, x: posX, y: posY, label: e.label!, font: labelFont, textColor: labelTextColor)
}
else
{
posY += labelLineHeight + yEntrySpace
drawLabel(context: context, x: posX, y: posY, label: e.label!, font: labelFont, textColor: labelTextColor)
}
// make a step down
posY += labelLineHeight + yEntrySpace
stack = 0.0
}
else
{
stack += formSize + stackSpace
wasStacked = true
}
}
}
}
private var _formLineSegmentsBuffer = [CGPoint](repeating: CGPoint(), count: 2)
/// Draws the Legend-form at the given position with the color at the given index.
@objc open func drawForm(
context: CGContext,
x: CGFloat,
y: CGFloat,
entry: LegendEntry,
legend: Legend)
{
guard
let formColor = entry.formColor,
formColor != NSUIColor.clear
else { return }
var form = entry.form
if form == .default
{
form = legend.form
}
let formSize = entry.formSize.isNaN ? legend.formSize : entry.formSize
context.saveGState()
defer { context.restoreGState() }
switch form
{
case .none:
// Do nothing
break
case .empty:
// Do not draw, but keep space for the form
break
case .default: fallthrough
case .circle:
context.setFillColor(formColor.cgColor)
context.fillEllipse(in: CGRect(x: x, y: y - formSize / 2.0, width: formSize, height: formSize))
case .square:
context.setFillColor(formColor.cgColor)
context.fill(CGRect(x: x, y: y - formSize / 2.0, width: formSize, height: formSize))
case .line:
let formLineWidth = entry.formLineWidth.isNaN ? legend.formLineWidth : entry.formLineWidth
let formLineDashPhase = entry.formLineDashPhase.isNaN ? legend.formLineDashPhase : entry.formLineDashPhase
let formLineDashLengths = entry.formLineDashLengths == nil ? legend.formLineDashLengths : entry.formLineDashLengths
context.setLineWidth(formLineWidth)
if formLineDashLengths != nil && formLineDashLengths!.count > 0
{
context.setLineDash(phase: formLineDashPhase, lengths: formLineDashLengths!)
}
else
{
context.setLineDash(phase: 0.0, lengths: [])
}
context.setStrokeColor(formColor.cgColor)
_formLineSegmentsBuffer[0].x = x
_formLineSegmentsBuffer[0].y = y
_formLineSegmentsBuffer[1].x = x + formSize
_formLineSegmentsBuffer[1].y = y
context.strokeLineSegments(between: _formLineSegmentsBuffer)
}
}
/// Draws the provided label at the given position.
@objc open func drawLabel(context: CGContext, x: CGFloat, y: CGFloat, label: String, font: NSUIFont, textColor: NSUIColor)
{
ChartUtils.drawText(context: context, text: label, point: CGPoint(x: x, y: y), align: .left, attributes: [NSAttributedStringKey.font: font, NSAttributedStringKey.foregroundColor: textColor])
}
}
| apache-2.0 | 56a9ffffc7ba0bd526111ff3ce1cc179 | 34.678947 | 198 | 0.420564 | 7.160915 | false | false | false | false |
haskellswift/swift-package-manager | Tests/BasicTests/OutputByteStreamTests.swift | 2 | 5868 | /*
This source file is part of the Swift.org open source project
Copyright 2015 - 2016 Apple Inc. and the Swift project authors
Licensed under Apache License v2.0 with Runtime Library Exception
See http://swift.org/LICENSE.txt for license information
See http://swift.org/CONTRIBUTORS.txt for Swift project authors
*/
import XCTest
import Basic
class OutputByteStreamTests: XCTestCase {
func testBasics() {
let stream = BufferedOutputByteStream()
stream.write("Hello")
stream.write(Character(","))
stream.write(Character(" "))
stream.write([UInt8]("wor".utf8))
stream.write([UInt8]("world".utf8)[3..<5])
let streamable: TextOutputStreamable = Character("!")
stream.write(streamable)
XCTAssertEqual(stream.position, "Hello, world!".utf8.count)
stream.flush()
XCTAssertEqual(stream.bytes, "Hello, world!")
}
func testStreamOperator() {
let stream = BufferedOutputByteStream()
let streamable: TextOutputStreamable = Character("!")
stream <<< "Hello" <<< Character(",") <<< Character(" ") <<< [UInt8]("wor".utf8) <<< [UInt8]("world".utf8)[3..<5] <<< streamable
XCTAssertEqual(stream.position, "Hello, world!".utf8.count)
XCTAssertEqual(stream.bytes, "Hello, world!")
let stream2 = BufferedOutputByteStream()
stream2 <<< (0..<5)
XCTAssertEqual(stream2.bytes, [0, 1, 2, 3, 4])
}
func testBufferCorrectness() {
let smallBlock = [UInt8](repeating: 2, count: 1 << 14)
// Check small / big interleavings for various block sizes (to prove buffer transfer optimizations).
for blockSize in [1 << 10, 1 << 12, 1 << 13, 1 << 14] {
let bigBlock = [UInt8](repeating: 1, count: blockSize)
var stream = BufferedOutputByteStream()
stream <<< smallBlock <<< bigBlock
XCTAssertEqual(stream.bytes, ByteString(smallBlock + bigBlock))
stream = BufferedOutputByteStream()
stream <<< bigBlock <<< smallBlock
XCTAssertEqual(stream.bytes, ByteString(bigBlock + smallBlock))
stream = BufferedOutputByteStream()
stream <<< bigBlock <<< bigBlock
XCTAssertEqual(stream.bytes, ByteString(bigBlock + bigBlock))
}
}
func testJSONEncoding() {
// Test string encoding.
func asJSON(_ value: String) -> ByteString {
let stream = BufferedOutputByteStream()
stream.writeJSONEscaped(value)
return stream.bytes
}
XCTAssertEqual(asJSON("a'\"\\"), "a'\\\"\\\\")
XCTAssertEqual(asJSON("\u{0008}"), "\\b")
XCTAssertEqual(asJSON("\u{000C}"), "\\f")
XCTAssertEqual(asJSON("\n"), "\\n")
XCTAssertEqual(asJSON("\r"), "\\r")
XCTAssertEqual(asJSON("\t"), "\\t")
XCTAssertEqual(asJSON("\u{0001}"), "\\u0001")
// Test other random types.
var stream = BufferedOutputByteStream()
stream <<< Format.asJSON(false)
XCTAssertEqual(stream.bytes, "false")
stream = BufferedOutputByteStream()
stream <<< Format.asJSON(1 as Int)
XCTAssertEqual(stream.bytes, "1")
stream = BufferedOutputByteStream()
stream <<< Format.asJSON(1.2 as Double)
XCTAssertEqual(stream.bytes, "1.2")
}
func testFormattedOutput() {
do {
let stream = BufferedOutputByteStream()
stream <<< Format.asJSON("\n")
XCTAssertEqual(stream.bytes, "\"\\n\"")
}
do {
let stream = BufferedOutputByteStream()
stream <<< Format.asJSON(["hello", "world\n"])
XCTAssertEqual(stream.bytes, "[\"hello\",\"world\\n\"]")
}
do {
let stream = BufferedOutputByteStream()
stream <<< Format.asJSON(["hello": "world\n"])
XCTAssertEqual(stream.bytes, "{\"hello\":\"world\\n\"}")
}
do {
struct MyThing {
let value: String
init(_ value: String) { self.value = value }
}
let stream = BufferedOutputByteStream()
stream <<< Format.asJSON([MyThing("hello"), MyThing("world\n")], transform: { $0.value })
XCTAssertEqual(stream.bytes, "[\"hello\",\"world\\n\"]")
}
do {
let stream = BufferedOutputByteStream()
stream <<< Format.asSeparatedList(["hello", "world"], separator: ", ")
XCTAssertEqual(stream.bytes, "hello, world")
}
do {
struct MyThing {
let value: String
init(_ value: String) { self.value = value }
}
let stream = BufferedOutputByteStream()
stream <<< Format.asSeparatedList([MyThing("hello"), MyThing("world")], transform: { $0.value }, separator: ", ")
XCTAssertEqual(stream.bytes, "hello, world")
}
}
func testLocalFileStream() throws {
let tempFile = try TemporaryFile()
func read() -> String? {
return try! localFileSystem.readFileContents(tempFile.path).asString
}
let stream = try LocalFileOutputByteStream(tempFile.path)
stream <<< "Hello"
stream.flush()
XCTAssertEqual(read(), "Hello")
stream <<< " World"
try stream.close()
XCTAssertEqual(read(), "Hello World")
}
static var allTests = [
("testBasics", testBasics),
("testBufferCorrectness", testBufferCorrectness),
("testStreamOperator", testStreamOperator),
("testJSONEncoding", testJSONEncoding),
("testFormattedOutput", testFormattedOutput),
("testLocalFileStream", testLocalFileStream),
]
}
| apache-2.0 | 7b5383b7a72ac150dc767834e9518c3a | 33.721893 | 136 | 0.572768 | 5.006826 | false | true | false | false |
RocketChat/Rocket.Chat.iOS | Rocket.Chat/Views/Cells/Chat/AutocompleteCell.swift | 1 | 806 | //
// AutocompleteCell.swift
// Rocket.Chat
//
// Created by Rafael K. Streit on 04/11/16.
// Copyright © 2016 Rocket.Chat. All rights reserved.
//
import UIKit
final class AutocompleteCell: UITableViewCell {
static let minimumHeight = CGFloat(44)
static let identifier = "AutocompleteCell"
@IBOutlet weak var avatarViewContainer: AvatarView! {
didSet {
avatarView.frame = avatarViewContainer.bounds
avatarViewContainer.addSubview(avatarView)
}
}
lazy var avatarView: AvatarView = {
let avatarView = AvatarView()
avatarView.layer.cornerRadius = 4
avatarView.layer.masksToBounds = true
avatarView.labelInitialsFontSize = 15
return avatarView
}()
@IBOutlet weak var labelTitle: UILabel!
}
| mit | 433484ed07465ffac78e175a96e8b131 | 24.15625 | 57 | 0.669565 | 4.763314 | false | false | false | false |
007HelloWorld/DouYuZhiBo | DYZB/DYZB/Tools/Extension/UIBarButtonItem-Extension.swift | 1 | 1606 | //
// UIBarButtonItem-Extension.swift
// DYZB
//
// Created by MacMini on 2017/8/4.
// Copyright © 2017年 MacMini. All rights reserved.
//
import UIKit
//对UIBarButtonItem进行拓展
extension UIBarButtonItem{
//对类方法进行拓展
class func createItem(imageName : String, heighImageName : String, size : CGSize) -> UIBarButtonItem {
let btn = UIButton()
btn.setImage(UIImage.init(named: imageName), for: .normal)
btn.setImage(UIImage.init(named: heighImageName), for: .highlighted)
btn.frame = CGRect.init(origin: CGPoint.zero, size: size)
return UIBarButtonItem.init(customView: btn)
}
//遍历构造函数:1.必须以convenience开头 2.在构造函数中必须明确调用一个设计的构造函数(self)
convenience init(imageName : String, heighImageName : String = "", size : CGSize = CGSize.zero) {
//对于传参的参数,进行了空值判断,进行了代码的健壮性
let btn = UIButton()
btn.setImage(UIImage.init(named: imageName), for: .normal)
if heighImageName != "" {
btn.setImage(UIImage.init(named: heighImageName), for: .highlighted)
}
if size == CGSize.zero {
btn.sizeToFit()
}else{
btn.frame = CGRect.init(origin: CGPoint.zero, size: size)
}
self.init(customView : btn)
}
}
| mit | 0187d4451ef4c156fecffae8972b5679 | 20.514706 | 106 | 0.546822 | 4.433333 | false | false | false | false |
ben-ng/swift | test/SILOptimizer/capture_promotion.swift | 7 | 834 | // RUN: %target-swift-frontend %s -emit-sil -o - -verify | %FileCheck %s
class Foo {
func foo() -> Int {
return 1
}
}
class Bar {
}
struct Baz {
var bar = Bar()
var x = 42
}
// CHECK: sil hidden @_TF17capture_promotion22test_capture_promotionFT_FT_Si
func test_capture_promotion() -> () -> Int {
var x : Int = 1; x = 1
var y : Foo = Foo(); y = Foo()
var z : Baz = Baz(); z = Baz()
// CHECK-NOT: alloc_box
// CHECK: [[CLOSURE0_PROMOTE0:%.*]] = function_ref @_TTSf2i_i_i___TFF17capture_promotion22test_capture_promotionFT_FT_SiU_FT_Si
// CHECK: partial_apply [[CLOSURE0_PROMOTE0]]({{%[0-9]*}}, {{%[0-9]*}}, {{%[0-9]*}})
return { x + y.foo() + z.x }
}
// CHECK: sil shared @_TTSf2i_i_i___TFF17capture_promotion22test_capture_promotionFT_FT_SiU_FT_Si : $@convention(thin) (Int, @owned Foo, @owned Baz) -> Int
| apache-2.0 | be3c4e30b28e338700643cbb217e0219 | 25.0625 | 155 | 0.605516 | 2.846416 | false | true | false | false |
iluuu1994/Conway-s-Game-of-Life | Conway's Game of Life/Conway's Game of Life/CGOLModel.swift | 1 | 4277 | //
// CGOLModel.swift
// Conway's Game of Life
//
// Created by Ilija Tovilo on 26/08/14.
// Copyright (c) 2014 Ilija Tovilo. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
import Foundation
public class CGOLModel: NSObject {
// --------------------
// MARK: - Properties -
// --------------------
/// Holds the tile models
private let _tiles: Matrix<TileModel!>
// --------------
// MARK: - Init -
// --------------
public init(gridWidth: Int, gridHeight: Int) {
_tiles = Matrix<TileModel!>(
width: gridWidth,
height: gridHeight,
repeatedValue: nil
)
for (x, y, _) in _tiles {
_tiles[x, y] = TileModel()
}
}
// -----------------
// MARK: - Methods -
// -----------------
public func getTile(at: TileCoordinates) -> TileModel {
return _tiles[at.x, at.y]
}
public func toggleTile(at: TileCoordinates) {
// Toggle the state of the model
var tile = _tiles[at.x, at.y]
tile.alive = !tile.alive
}
public func clear() {
for (_, _, tile) in _tiles {
tile.alive = false
}
}
// --------------------
// MARK: - Game Logic -
// --------------------
/// http://en.wikipedia.org/wiki/Conway's_Game_of_Life#Rules
/// 1. Any live cell with fewer than two live neighbours dies, as if caused by under-population.
/// 2. Any live cell with two or three live neighbours lives on to the next generation.
/// 3. Any live cell with more than three live neighbours dies, as if by overcrowding.
/// 4. Any dead cell with exactly three live neighbours becomes a live cell, as if by reproduction.
public func step() {
// Find the tiles that must be toggled and mark them
for (x, y, tile) in _tiles {
let neighbours = getNeighbours(x: x, y: y).filter { $0.alive }
if tile.alive {
if neighbours.count < 2 || neighbours.count > 3 {
tile.shouldToggleState = true
}
} else {
if neighbours.count == 3 { tile.shouldToggleState = true }
}
}
// Finally, toggle the fields that must be toggled
for (x, y, tile) in _tiles {
if tile.shouldToggleState {
tile.alive = !tile.alive
tile.shouldToggleState = false
}
}
}
public func getNeighbours(coordinates: TileCoordinates) -> [TileModel] {
var neighbours = [TileModel]()
let neighboursDelta = [(1, 0), (0, 1), (-1, 0), (0, -1),
(1, 1), (-1, 1), (-1, -1), (1, -1)]
for (deltaX, deltaY) in neighboursDelta {
let x = coordinates.x + deltaX
let y = coordinates.y + deltaY
if x < 0 || x >= _tiles.width { continue }
if y < 0 || y >= _tiles.height { continue }
neighbours.append(_tiles[x, y])
}
return neighbours
}
}
| bsd-2-clause | 66fed905c70dc12b33c9e9a3e158aa5b | 32.677165 | 103 | 0.548282 | 4.436722 | false | false | false | false |
frootloops/swift | test/IRGen/generic_types.swift | 1 | 6609 | // RUN: %target-swift-frontend %s -emit-ir | %FileCheck %s --check-prefix=CHECK --check-prefix=CHECK-%target-runtime
// REQUIRES: CPU=x86_64
// CHECK: [[A:%T13generic_types1AC]] = type <{ [[REF:%swift.refcounted]], [[INT:%TSi]] }>
// CHECK: [[INT]] = type <{ i64 }>
// CHECK: [[B:%T13generic_types1BC]] = type <{ [[REF:%swift.refcounted]], [[UNSAFE:%TSp]] }>
// CHECK: [[C:%T13generic_types1CC]] = type
// CHECK: [[D:%T13generic_types1DC]] = type
// CHECK-LABEL: @_T013generic_types1ACMP = internal global
// CHECK: %swift.type* (%swift.type_pattern*, i8**)* @create_generic_metadata_A,
// CHECK-native-SAME: i32 104,
// CHECK-objc-SAME: i32 288,
// CHECK-SAME: i16 1,
// CHECK-native-SAME: i16 24,
// CHECK-objc-SAME: i16 208,
// CHECK-SAME: [{{[0-9]+}} x i8*] zeroinitializer,
// CHECK-SAME: void ([[A]]*)* @_T013generic_types1ACfD,
// CHECK-SAME: i8** @_T0BoWV,
// CHECK-SAME: i64 0,
// CHECK-SAME: %swift.type* null,
// CHECK-native-SAME: %swift.opaque* null,
// CHECK-objc-SAME: %swift.opaque* @_objc_empty_cache,
// CHECK-SAME: %swift.opaque* null,
// CHECK-SAME: i64 1,
// CHECK-SAME: i32 3,
// CHECK-SAME: i32 0,
// CHECK-SAME: i32 24,
// CHECK-SAME: i16 7,
// CHECK-SAME: i16 0,
// CHECK-SAME: i32 152,
// CHECK-SAME: i32 16,
// -- nominal type descriptor
// CHECK-SAME: @_T013generic_types1ACMn,
// -- ivar destroyer
// CHECK-SAME: i8* null
// CHECK-SAME: }
// CHECK-LABEL: @_T013generic_types1BCMP = internal global
// CHECK-SAME: %swift.type* (%swift.type_pattern*, i8**)* @create_generic_metadata_B,
// CHECK-native-SAME: i32 104,
// CHECK-objc-SAME: i32 288,
// CHECK-SAME: i16 1,
// CHECK-native-SAME: i16 24,
// CHECK-objc-SAME: i16 208,
// CHECK-SAME: [{{[0-9]+}} x i8*] zeroinitializer,
// CHECK-SAME: void ([[B]]*)* @_T013generic_types1BCfD,
// CHECK-SAME: i8** @_T0BoWV,
// CHECK-SAME: i64 0,
// CHECK-SAME: %swift.type* null,
// CHECK-native-SAME: %swift.opaque* null,
// CHECK-objc-SAME: %swift.opaque* @_objc_empty_cache,
// CHECK-SAME: %swift.opaque* null,
// CHECK-SAME: i64 1,
// CHECK-SAME: i32 3,
// CHECK-SAME: i32 0,
// CHECK-SAME: i32 24,
// CHECK-SAME: i16 7,
// CHECK-SAME: i16 0,
// CHECK-SAME: i32 144,
// CHECK-SAME: i32 16,
// -- nominal type descriptor
// CHECK-SAME: @_T013generic_types1BCMn,
// -- ivar destroyer
// CHECK-SAME: i8* null
// CHECK-SAME: }
// CHECK-LABEL: @_T013generic_types1CCMP = internal global
// CHECK-SAME: void ([[C]]*)* @_T013generic_types1CCfD,
// CHECK-SAME: i8** @_T0BoWV,
// CHECK-SAME: i64 0,
// CHECK-SAME: %swift.type* null,
// CHECK-native-SAME: %swift.opaque* null,
// CHECK-objc-SAME: %swift.opaque* @_objc_empty_cache,
// CHECK-SAME: %swift.opaque* null,
// CHECK-SAME: i64 1,
// CHECK-SAME: i32 3,
// CHECK-SAME: i32 0,
// CHECK-SAME: i32 24,
// CHECK-SAME: i16 7,
// CHECK-SAME: i16 0,
// CHECK-SAME: i32 160,
// CHECK-SAME: i32 16,
// -- nominal type descriptor
// CHECK-SAME: @_T013generic_types1CCMn,
// -- ivar destroyer
// CHECK-SAME: i8* null
// CHECK-SAME: }
// CHECK-LABEL: @_T013generic_types1DCMP = internal global
// CHECK-SAME: void ([[D]]*)* @_T013generic_types1DCfD,
// CHECK-SAME: i8** @_T0BoWV,
// CHECK-SAME: i64 0,
// CHECK-SAME: %swift.type* null,
// CHECK-native-SAME: %swift.opaque* null,
// CHECK-objc-SAME: %swift.opaque* @_objc_empty_cache,
// CHECK-SAME: %swift.opaque* null,
// CHECK-SAME: i64 1,
// CHECK-SAME: i32 3,
// CHECK-SAME: i32 0,
// CHECK-SAME: i32 24,
// CHECK-SAME: i16 7,
// CHECK-SAME: i16 0,
// CHECK-SAME: i32 160,
// CHECK-SAME: i32 16,
// -- nominal type descriptor
// CHECK-SAME: @_T013generic_types1DCMn,
// -- ivar destroyer
// CHECK-SAME: i8* null
// CHECK-SAME: }
// CHECK-LABEL: define{{( protected)?}} private %swift.type* @create_generic_metadata_A(%swift.type_pattern*, i8**) {{.*}} {
// CHECK: [[T0:%.*]] = bitcast i8** %1 to %swift.type**
// CHECK: %T = load %swift.type*, %swift.type** [[T0]],
// CHECK-native: [[METADATA:%.*]] = call %swift.type* @swift_allocateGenericClassMetadata(%swift.type_pattern* %0, i8** %1, %objc_class* null, i64 7)
// CHECK-objc: [[T0:%.*]] = load %objc_class*, %objc_class** @"OBJC_CLASS_REF_$_SwiftObject"
// CHECK-objc: [[SUPER:%.*]] = call %objc_class* @swift_rt_swift_getInitializedObjCClass(%objc_class* [[T0]])
// CHECK-objc: [[METADATA:%.*]] = call %swift.type* @swift_allocateGenericClassMetadata(%swift.type_pattern* %0, i8** %1, %objc_class* [[SUPER]], i64 7)
// CHECK: [[SELF_ARRAY:%.*]] = bitcast %swift.type* [[METADATA]] to i8**
// CHECK: [[T1:%.*]] = getelementptr inbounds i8*, i8** [[SELF_ARRAY]], i32 10
// CHECK: [[T0:%.*]] = bitcast %swift.type* %T to i8*
// CHECK: store i8* [[T0]], i8** [[T1]], align 8
// CHECK: ret %swift.type* [[METADATA]]
// CHECK: }
// CHECK-LABEL: define{{( protected)?}} private %swift.type* @create_generic_metadata_B(%swift.type_pattern*, i8**) {{.*}} {
// CHECK: [[T0:%.*]] = bitcast i8** %1 to %swift.type**
// CHECK: %T = load %swift.type*, %swift.type** [[T0]],
// CHECK-native: [[METADATA:%.*]] = call %swift.type* @swift_allocateGenericClassMetadata(%swift.type_pattern* %0, i8** %1, %objc_class* null, i64 6)
// CHECK-objc: [[T0:%.*]] = load %objc_class*, %objc_class** @"OBJC_CLASS_REF_$_SwiftObject"
// CHECK-objc: [[SUPER:%.*]] = call %objc_class* @swift_rt_swift_getInitializedObjCClass(%objc_class* [[T0]])
// CHECK-objc: [[METADATA:%.*]] = call %swift.type* @swift_allocateGenericClassMetadata(%swift.type_pattern* %0, i8** %1, %objc_class* [[SUPER]], i64 6)
// CHECK: [[SELF_ARRAY:%.*]] = bitcast %swift.type* [[METADATA]] to i8**
// CHECK: [[T1:%.*]] = getelementptr inbounds i8*, i8** [[SELF_ARRAY]], i32 10
// CHECK: [[T0:%.*]] = bitcast %swift.type* %T to i8*
// CHECK: store i8* [[T0]], i8** [[T1]], align 8
// CHECK: ret %swift.type* [[METADATA]]
// CHECK: }
class A<T> {
var x = 0
func run(_ t: T) {}
init(y : Int) {}
}
class B<T> {
var ptr : UnsafeMutablePointer<T>
init(ptr: UnsafeMutablePointer<T>) {
self.ptr = ptr
}
deinit {
ptr.deinitialize(count: 1)
}
}
class C<T> : A<Int> {}
class D<T> : A<Int> {
override func run(_ t: Int) {}
}
struct E<T> {
var x : Int
func foo() { bar() }
func bar() {}
}
class ClassA {}
class ClassB {}
// This type is fixed-size across specializations, but it needs to use
// a different implementation in IR-gen so that types match up.
// It just asserts if we get it wrong.
struct F<T: AnyObject> {
var value: T
}
func testFixed() {
var a = F(value: ClassA()).value
var b = F(value: ClassB()).value
}
| apache-2.0 | bdea04521bb62d77bd489160a71490e6 | 35.313187 | 154 | 0.609623 | 2.76296 | false | false | false | false |
frootloops/swift | stdlib/public/SDK/Foundation/URL.swift | 2 | 66071 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
@_exported import Foundation // Clang module
/**
URLs to file system resources support the properties defined below. Note that not all property values will exist for all file system URLs. For example, if a file is located on a volume that does not support creation dates, it is valid to request the creation date property, but the returned value will be nil, and no error will be generated.
Only the fields requested by the keys you pass into the `URL` function to receive this value will be populated. The others will return `nil` regardless of the underlying property on the file system.
As a convenience, volume resource values can be requested from any file system URL. The value returned will reflect the property value for the volume on which the resource is located.
*/
public struct URLResourceValues {
fileprivate var _values: [URLResourceKey: Any]
fileprivate var _keys: Set<URLResourceKey>
public init() {
_values = [:]
_keys = []
}
fileprivate init(keys: Set<URLResourceKey>, values: [URLResourceKey: Any]) {
_values = values
_keys = keys
}
private func contains(_ key: URLResourceKey) -> Bool {
return _keys.contains(key)
}
private func _get<T>(_ key : URLResourceKey) -> T? {
return _values[key] as? T
}
private func _get(_ key : URLResourceKey) -> Bool? {
return (_values[key] as? NSNumber)?.boolValue
}
private func _get(_ key: URLResourceKey) -> Int? {
return (_values[key] as? NSNumber)?.intValue
}
private mutating func _set(_ key : URLResourceKey, newValue : Any?) {
_keys.insert(key)
_values[key] = newValue
}
private mutating func _set(_ key : URLResourceKey, newValue : String?) {
_keys.insert(key)
_values[key] = newValue as NSString?
}
private mutating func _set(_ key : URLResourceKey, newValue : [String]?) {
_keys.insert(key)
_values[key] = newValue as NSObject?
}
private mutating func _set(_ key : URLResourceKey, newValue : Date?) {
_keys.insert(key)
_values[key] = newValue as NSDate?
}
private mutating func _set(_ key : URLResourceKey, newValue : URL?) {
_keys.insert(key)
_values[key] = newValue as NSURL?
}
private mutating func _set(_ key : URLResourceKey, newValue : Bool?) {
_keys.insert(key)
if let value = newValue {
_values[key] = NSNumber(value: value)
} else {
_values[key] = nil
}
}
private mutating func _set(_ key : URLResourceKey, newValue : Int?) {
_keys.insert(key)
if let value = newValue {
_values[key] = NSNumber(value: value)
} else {
_values[key] = nil
}
}
/// A loosely-typed dictionary containing all keys and values.
///
/// If you have set temporary keys or non-standard keys, you can find them in here.
public var allValues : [URLResourceKey : Any] {
return _values
}
/// The resource name provided by the file system.
public var name: String? {
get { return _get(.nameKey) }
set { _set(.nameKey, newValue: newValue) }
}
/// Localized or extension-hidden name as displayed to users.
public var localizedName: String? { return _get(.localizedNameKey) }
/// True for regular files.
public var isRegularFile: Bool? { return _get(.isRegularFileKey) }
/// True for directories.
public var isDirectory: Bool? { return _get(.isDirectoryKey) }
/// True for symlinks.
public var isSymbolicLink: Bool? { return _get(.isSymbolicLinkKey) }
/// True for the root directory of a volume.
public var isVolume: Bool? { return _get(.isVolumeKey) }
/// True for packaged directories.
///
/// - note: You can only set or clear this property on directories; if you try to set this property on non-directory objects, the property is ignored. If the directory is a package for some other reason (extension type, etc), setting this property to false will have no effect.
public var isPackage: Bool? {
get { return _get(.isPackageKey) }
set { _set(.isPackageKey, newValue: newValue) }
}
/// True if resource is an application.
@available(OSX 10.11, iOS 9.0, *)
public var isApplication: Bool? { return _get(.isApplicationKey) }
#if os(macOS)
/// True if the resource is scriptable. Only applies to applications.
@available(OSX 10.11, *)
public var applicationIsScriptable: Bool? { return _get(.applicationIsScriptableKey) }
#endif
/// True for system-immutable resources.
public var isSystemImmutable: Bool? { return _get(.isSystemImmutableKey) }
/// True for user-immutable resources
public var isUserImmutable: Bool? {
get { return _get(.isUserImmutableKey) }
set { _set(.isUserImmutableKey, newValue: newValue) }
}
/// True for resources normally not displayed to users.
///
/// - note: If the resource is a hidden because its name starts with a period, setting this property to false will not change the property.
public var isHidden: Bool? {
get { return _get(.isHiddenKey) }
set { _set(.isHiddenKey, newValue: newValue) }
}
/// True for resources whose filename extension is removed from the localized name property.
public var hasHiddenExtension: Bool? {
get { return _get(.hasHiddenExtensionKey) }
set { _set(.hasHiddenExtensionKey, newValue: newValue) }
}
/// The date the resource was created.
public var creationDate: Date? {
get { return _get(.creationDateKey) }
set { _set(.creationDateKey, newValue: newValue) }
}
/// The date the resource was last accessed.
public var contentAccessDate: Date? {
get { return _get(.contentAccessDateKey) }
set { _set(.contentAccessDateKey, newValue: newValue) }
}
/// The time the resource content was last modified.
public var contentModificationDate: Date? {
get { return _get(.contentModificationDateKey) }
set { _set(.contentModificationDateKey, newValue: newValue) }
}
/// The time the resource's attributes were last modified.
public var attributeModificationDate: Date? { return _get(.attributeModificationDateKey) }
/// Number of hard links to the resource.
public var linkCount: Int? { return _get(.linkCountKey) }
/// The resource's parent directory, if any.
public var parentDirectory: URL? { return _get(.parentDirectoryURLKey) }
/// URL of the volume on which the resource is stored.
public var volume: URL? { return _get(.volumeURLKey) }
/// Uniform type identifier (UTI) for the resource.
public var typeIdentifier: String? { return _get(.typeIdentifierKey) }
/// User-visible type or "kind" description.
public var localizedTypeDescription: String? { return _get(.localizedTypeDescriptionKey) }
/// The label number assigned to the resource.
public var labelNumber: Int? {
get { return _get(.labelNumberKey) }
set { _set(.labelNumberKey, newValue: newValue) }
}
/// The user-visible label text.
public var localizedLabel: String? {
get { return _get(.localizedLabelKey) }
}
/// An identifier which can be used to compare two file system objects for equality using `isEqual`.
///
/// Two object identifiers are equal if they have the same file system path or if the paths are linked to same inode on the same file system. This identifier is not persistent across system restarts.
public var fileResourceIdentifier: (NSCopying & NSCoding & NSSecureCoding & NSObjectProtocol)? { return _get(.fileResourceIdentifierKey) }
/// An identifier that can be used to identify the volume the file system object is on.
///
/// Other objects on the same volume will have the same volume identifier and can be compared using for equality using `isEqual`. This identifier is not persistent across system restarts.
public var volumeIdentifier: (NSCopying & NSCoding & NSSecureCoding & NSObjectProtocol)? { return _get(.volumeIdentifierKey) }
/// The optimal block size when reading or writing this file's data, or nil if not available.
public var preferredIOBlockSize: Int? { return _get(.preferredIOBlockSizeKey) }
/// True if this process (as determined by EUID) can read the resource.
public var isReadable: Bool? { return _get(.isReadableKey) }
/// True if this process (as determined by EUID) can write to the resource.
public var isWritable: Bool? { return _get(.isWritableKey) }
/// True if this process (as determined by EUID) can execute a file resource or search a directory resource.
public var isExecutable: Bool? { return _get(.isExecutableKey) }
/// The file system object's security information encapsulated in a FileSecurity object.
public var fileSecurity: NSFileSecurity? {
get { return _get(.fileSecurityKey) }
set { _set(.fileSecurityKey, newValue: newValue) }
}
/// True if resource should be excluded from backups, false otherwise.
///
/// This property is only useful for excluding cache and other application support files which are not needed in a backup. Some operations commonly made to user documents will cause this property to be reset to false and so this property should not be used on user documents.
public var isExcludedFromBackup: Bool? {
get { return _get(.isExcludedFromBackupKey) }
set { _set(.isExcludedFromBackupKey, newValue: newValue) }
}
#if os(macOS)
/// The array of Tag names.
public var tagNames: [String]? { return _get(.tagNamesKey) }
#endif
/// The URL's path as a file system path.
public var path: String? { return _get(.pathKey) }
/// The URL's path as a canonical absolute file system path.
@available(OSX 10.12, iOS 10.0, tvOS 10.0, watchOS 3.0, *)
public var canonicalPath: String? { return _get(.canonicalPathKey) }
/// True if this URL is a file system trigger directory. Traversing or opening a file system trigger will cause an attempt to mount a file system on the trigger directory.
public var isMountTrigger: Bool? { return _get(.isMountTriggerKey) }
/// An opaque generation identifier which can be compared using `==` to determine if the data in a document has been modified.
///
/// For URLs which refer to the same file inode, the generation identifier will change when the data in the file's data fork is changed (changes to extended attributes or other file system metadata do not change the generation identifier). For URLs which refer to the same directory inode, the generation identifier will change when direct children of that directory are added, removed or renamed (changes to the data of the direct children of that directory will not change the generation identifier). The generation identifier is persistent across system restarts. The generation identifier is tied to a specific document on a specific volume and is not transferred when the document is copied to another volume. This property is not supported by all volumes.
@available(OSX 10.10, iOS 8.0, *)
public var generationIdentifier: (NSCopying & NSCoding & NSSecureCoding & NSObjectProtocol)? { return _get(.generationIdentifierKey) }
/// The document identifier -- a value assigned by the kernel to a document (which can be either a file or directory) and is used to identify the document regardless of where it gets moved on a volume.
///
/// The document identifier survives "safe save" operations; i.e it is sticky to the path it was assigned to (`replaceItem(at:,withItemAt:,backupItemName:,options:,resultingItem:) throws` is the preferred safe-save API). The document identifier is persistent across system restarts. The document identifier is not transferred when the file is copied. Document identifiers are only unique within a single volume. This property is not supported by all volumes.
@available(OSX 10.10, iOS 8.0, *)
public var documentIdentifier: Int? { return _get(.documentIdentifierKey) }
/// The date the resource was created, or renamed into or within its parent directory. Note that inconsistent behavior may be observed when this attribute is requested on hard-linked items. This property is not supported by all volumes.
@available(OSX 10.10, iOS 8.0, *)
public var addedToDirectoryDate: Date? { return _get(.addedToDirectoryDateKey) }
#if os(macOS)
/// The quarantine properties as defined in LSQuarantine.h. To remove quarantine information from a file, pass `nil` as the value when setting this property.
@available(OSX 10.10, *)
public var quarantineProperties: [String : Any]? {
get {
let value = _values[.quarantinePropertiesKey]
// If a caller has caused us to stash NSNull in the dictionary (via set), make sure to return nil instead of NSNull
if value is NSNull {
return nil
} else {
return value as? [String : Any]
}
}
set {
// Use NSNull for nil, a special case for deleting quarantine
// properties
_set(.quarantinePropertiesKey, newValue: newValue ?? NSNull())
}
}
#endif
/// Returns the file system object type.
public var fileResourceType: URLFileResourceType? { return _get(.fileResourceTypeKey) }
/// The user-visible volume format.
public var volumeLocalizedFormatDescription : String? { return _get(.volumeLocalizedFormatDescriptionKey) }
/// Total volume capacity in bytes.
public var volumeTotalCapacity : Int? { return _get(.volumeTotalCapacityKey) }
/// Total free space in bytes.
public var volumeAvailableCapacity : Int? { return _get(.volumeAvailableCapacityKey) }
#if os(macOS) || os(iOS)
/// Total available capacity in bytes for "Important" resources, including space expected to be cleared by purging non-essential and cached resources. "Important" means something that the user or application clearly expects to be present on the local system, but is ultimately replaceable. This would include items that the user has explicitly requested via the UI, and resources that an application requires in order to provide functionality.
/// Examples: A video that the user has explicitly requested to watch but has not yet finished watching or an audio file that the user has requested to download.
/// This value should not be used in determining if there is room for an irreplaceable resource. In the case of irreplaceable resources, always attempt to save the resource regardless of available capacity and handle failure as gracefully as possible.
@available(OSX 10.13, iOS 11.0, *) @available(tvOS, unavailable) @available(watchOS, unavailable)
public var volumeAvailableCapacityForImportantUsage: Int64? { return _get(.volumeAvailableCapacityForImportantUsageKey) }
/// Total available capacity in bytes for "Opportunistic" resources, including space expected to be cleared by purging non-essential and cached resources. "Opportunistic" means something that the user is likely to want but does not expect to be present on the local system, but is ultimately non-essential and replaceable. This would include items that will be created or downloaded without an explicit request from the user on the current device.
/// Examples: A background download of a newly available episode of a TV series that a user has been recently watching, a piece of content explicitly requested on another device, and a new document saved to a network server by the current user from another device.
@available(OSX 10.13, iOS 11.0, *) @available(tvOS, unavailable) @available(watchOS, unavailable)
public var volumeAvailableCapacityForOpportunisticUsage: Int64? { return _get(.volumeAvailableCapacityForOpportunisticUsageKey) }
#endif
/// Total number of resources on the volume.
public var volumeResourceCount : Int? { return _get(.volumeResourceCountKey) }
/// true if the volume format supports persistent object identifiers and can look up file system objects by their IDs.
public var volumeSupportsPersistentIDs : Bool? { return _get(.volumeSupportsPersistentIDsKey) }
/// true if the volume format supports symbolic links.
public var volumeSupportsSymbolicLinks : Bool? { return _get(.volumeSupportsSymbolicLinksKey) }
/// true if the volume format supports hard links.
public var volumeSupportsHardLinks : Bool? { return _get(.volumeSupportsHardLinksKey) }
/// true if the volume format supports a journal used to speed recovery in case of unplanned restart (such as a power outage or crash). This does not necessarily mean the volume is actively using a journal.
public var volumeSupportsJournaling : Bool? { return _get(.volumeSupportsJournalingKey) }
/// true if the volume is currently using a journal for speedy recovery after an unplanned restart.
public var volumeIsJournaling : Bool? { return _get(.volumeIsJournalingKey) }
/// true if the volume format supports sparse files, that is, files which can have 'holes' that have never been written to, and thus do not consume space on disk. A sparse file may have an allocated size on disk that is less than its logical length.
public var volumeSupportsSparseFiles : Bool? { return _get(.volumeSupportsSparseFilesKey) }
/// For security reasons, parts of a file (runs) that have never been written to must appear to contain zeroes. true if the volume keeps track of allocated but unwritten runs of a file so that it can substitute zeroes without actually writing zeroes to the media.
public var volumeSupportsZeroRuns : Bool? { return _get(.volumeSupportsZeroRunsKey) }
/// true if the volume format treats upper and lower case characters in file and directory names as different. Otherwise an upper case character is equivalent to a lower case character, and you can't have two names that differ solely in the case of the characters.
public var volumeSupportsCaseSensitiveNames : Bool? { return _get(.volumeSupportsCaseSensitiveNamesKey) }
/// true if the volume format preserves the case of file and directory names. Otherwise the volume may change the case of some characters (typically making them all upper or all lower case).
public var volumeSupportsCasePreservedNames : Bool? { return _get(.volumeSupportsCasePreservedNamesKey) }
/// true if the volume supports reliable storage of times for the root directory.
public var volumeSupportsRootDirectoryDates : Bool? { return _get(.volumeSupportsRootDirectoryDatesKey) }
/// true if the volume supports returning volume size values (`volumeTotalCapacity` and `volumeAvailableCapacity`).
public var volumeSupportsVolumeSizes : Bool? { return _get(.volumeSupportsVolumeSizesKey) }
/// true if the volume can be renamed.
public var volumeSupportsRenaming : Bool? { return _get(.volumeSupportsRenamingKey) }
/// true if the volume implements whole-file flock(2) style advisory locks, and the O_EXLOCK and O_SHLOCK flags of the open(2) call.
public var volumeSupportsAdvisoryFileLocking : Bool? { return _get(.volumeSupportsAdvisoryFileLockingKey) }
/// true if the volume implements extended security (ACLs).
public var volumeSupportsExtendedSecurity : Bool? { return _get(.volumeSupportsExtendedSecurityKey) }
/// true if the volume should be visible via the GUI (i.e., appear on the Desktop as a separate volume).
public var volumeIsBrowsable : Bool? { return _get(.volumeIsBrowsableKey) }
/// The largest file size (in bytes) supported by this file system, or nil if this cannot be determined.
public var volumeMaximumFileSize : Int? { return _get(.volumeMaximumFileSizeKey) }
/// true if the volume's media is ejectable from the drive mechanism under software control.
public var volumeIsEjectable : Bool? { return _get(.volumeIsEjectableKey) }
/// true if the volume's media is removable from the drive mechanism.
public var volumeIsRemovable : Bool? { return _get(.volumeIsRemovableKey) }
/// true if the volume's device is connected to an internal bus, false if connected to an external bus, or nil if not available.
public var volumeIsInternal : Bool? { return _get(.volumeIsInternalKey) }
/// true if the volume is automounted. Note: do not mistake this with the functionality provided by kCFURLVolumeSupportsBrowsingKey.
public var volumeIsAutomounted : Bool? { return _get(.volumeIsAutomountedKey) }
/// true if the volume is stored on a local device.
public var volumeIsLocal : Bool? { return _get(.volumeIsLocalKey) }
/// true if the volume is read-only.
public var volumeIsReadOnly : Bool? { return _get(.volumeIsReadOnlyKey) }
/// The volume's creation date, or nil if this cannot be determined.
public var volumeCreationDate : Date? { return _get(.volumeCreationDateKey) }
/// The `URL` needed to remount a network volume, or nil if not available.
public var volumeURLForRemounting : URL? { return _get(.volumeURLForRemountingKey) }
/// The volume's persistent `UUID` as a string, or nil if a persistent `UUID` is not available for the volume.
public var volumeUUIDString : String? { return _get(.volumeUUIDStringKey) }
/// The name of the volume
public var volumeName : String? {
get { return _get(.volumeNameKey) }
set { _set(.volumeNameKey, newValue: newValue) }
}
/// The user-presentable name of the volume
public var volumeLocalizedName : String? { return _get(.volumeLocalizedNameKey) }
/// true if the volume is encrypted.
@available(OSX 10.12, iOS 10.0, tvOS 10.0, watchOS 3.0, *)
public var volumeIsEncrypted : Bool? { return _get(.volumeIsEncryptedKey) }
/// true if the volume is the root filesystem.
@available(OSX 10.12, iOS 10.0, tvOS 10.0, watchOS 3.0, *)
public var volumeIsRootFileSystem : Bool? { return _get(.volumeIsRootFileSystemKey) }
/// true if the volume supports transparent decompression of compressed files using decmpfs.
@available(OSX 10.12, iOS 10.0, tvOS 10.0, watchOS 3.0, *)
public var volumeSupportsCompression : Bool? { return _get(.volumeSupportsCompressionKey) }
/// true if this item is synced to the cloud, false if it is only a local file.
public var isUbiquitousItem : Bool? { return _get(.isUbiquitousItemKey) }
/// true if this item has conflicts outstanding.
public var ubiquitousItemHasUnresolvedConflicts : Bool? { return _get(.ubiquitousItemHasUnresolvedConflictsKey) }
/// true if data is being downloaded for this item.
public var ubiquitousItemIsDownloading : Bool? { return _get(.ubiquitousItemIsDownloadingKey) }
/// true if there is data present in the cloud for this item.
public var ubiquitousItemIsUploaded : Bool? { return _get(.ubiquitousItemIsUploadedKey) }
/// true if data is being uploaded for this item.
public var ubiquitousItemIsUploading : Bool? { return _get(.ubiquitousItemIsUploadingKey) }
/// returns the download status of this item.
public var ubiquitousItemDownloadingStatus : URLUbiquitousItemDownloadingStatus? { return _get(.ubiquitousItemDownloadingStatusKey) }
/// returns the error when downloading the item from iCloud failed, see the NSUbiquitousFile section in FoundationErrors.h
public var ubiquitousItemDownloadingError : NSError? { return _get(.ubiquitousItemDownloadingErrorKey) }
/// returns the error when uploading the item to iCloud failed, see the NSUbiquitousFile section in FoundationErrors.h
public var ubiquitousItemUploadingError : NSError? { return _get(.ubiquitousItemUploadingErrorKey) }
/// returns whether a download of this item has already been requested with an API like `startDownloadingUbiquitousItem(at:) throws`.
@available(OSX 10.10, iOS 8.0, *)
public var ubiquitousItemDownloadRequested : Bool? { return _get(.ubiquitousItemDownloadRequestedKey) }
/// returns the name of this item's container as displayed to users.
@available(OSX 10.10, iOS 8.0, *)
public var ubiquitousItemContainerDisplayName : String? { return _get(.ubiquitousItemContainerDisplayNameKey) }
#if os(macOS) || os(iOS)
// true if ubiquitous item is shared.
@available(OSX 10.13, iOS 11.0, *) @available(tvOS, unavailable) @available(watchOS, unavailable)
public var ubiquitousItemIsShared: Bool? { return _get(.ubiquitousItemIsSharedKey) }
// The current user's role for this shared item, or nil if not shared
@available(OSX 10.13, iOS 11.0, *) @available(tvOS, unavailable) @available(watchOS, unavailable)
public var ubiquitousSharedItemCurrentUserRole: URLUbiquitousSharedItemRole? { return _get(.ubiquitousSharedItemCurrentUserRoleKey) }
// The permissions for the current user, or nil if not shared.
@available(OSX 10.13, iOS 11.0, *) @available(tvOS, unavailable) @available(watchOS, unavailable)
public var ubiquitousSharedItemCurrentUserPermissions: URLUbiquitousSharedItemPermissions? { return _get(.ubiquitousSharedItemCurrentUserPermissionsKey) }
// The name components for the owner, or nil if not shared.
@available(OSX 10.13, iOS 11.0, *) @available(tvOS, unavailable) @available(watchOS, unavailable)
public var ubiquitousSharedItemOwnerNameComponents: PersonNameComponents? { return _get(.ubiquitousSharedItemOwnerNameComponentsKey) }
// The name components for the most recent editor, or nil if not shared.
@available(OSX 10.13, iOS 11.0, *) @available(tvOS, unavailable) @available(watchOS, unavailable)
public var ubiquitousSharedItemMostRecentEditorNameComponents: PersonNameComponents? { return _get(.ubiquitousSharedItemMostRecentEditorNameComponentsKey) }
#endif
#if !os(macOS)
/// The protection level for this file
@available(iOS 9.0, *)
public var fileProtection : URLFileProtection? { return _get(.fileProtectionKey) }
#endif
/// Total file size in bytes
///
/// - note: Only applicable to regular files.
public var fileSize : Int? { return _get(.fileSizeKey) }
/// Total size allocated on disk for the file in bytes (number of blocks times block size)
///
/// - note: Only applicable to regular files.
public var fileAllocatedSize : Int? { return _get(.fileAllocatedSizeKey) }
/// Total displayable size of the file in bytes (this may include space used by metadata), or nil if not available.
///
/// - note: Only applicable to regular files.
public var totalFileSize : Int? { return _get(.totalFileSizeKey) }
/// Total allocated size of the file in bytes (this may include space used by metadata), or nil if not available. This can be less than the value returned by `totalFileSize` if the resource is compressed.
///
/// - note: Only applicable to regular files.
public var totalFileAllocatedSize : Int? { return _get(.totalFileAllocatedSizeKey) }
/// true if the resource is a Finder alias file or a symlink, false otherwise
///
/// - note: Only applicable to regular files.
public var isAliasFile : Bool? { return _get(.isAliasFileKey) }
}
/**
A URL is a type that can potentially contain the location of a resource on a remote server, the path of a local file on disk, or even an arbitrary piece of encoded data.
You can construct URLs and access their parts. For URLs that represent local files, you can also manipulate properties of those files directly, such as changing the file's last modification date. Finally, you can pass URLs to other APIs to retrieve the contents of those URLs. For example, you can use the URLSession classes to access the contents of remote resources, as described in URL Session Programming Guide.
URLs are the preferred way to refer to local files. Most objects that read data from or write data to a file have methods that accept a URL instead of a pathname as the file reference. For example, you can get the contents of a local file URL as `String` by calling `func init(contentsOf:encoding) throws`, or as a `Data` by calling `func init(contentsOf:options) throws`.
*/
public struct URL : ReferenceConvertible, Equatable {
public typealias ReferenceType = NSURL
fileprivate var _url : NSURL
public typealias BookmarkResolutionOptions = NSURL.BookmarkResolutionOptions
public typealias BookmarkCreationOptions = NSURL.BookmarkCreationOptions
/// Initialize with string.
///
/// Returns `nil` if a `URL` cannot be formed with the string (for example, if the string contains characters that are illegal in a URL, or is an empty string).
public init?(string: String) {
guard !string.isEmpty else { return nil }
if let inner = NSURL(string: string) {
_url = URL._converted(from: inner)
} else {
return nil
}
}
/// Initialize with string, relative to another URL.
///
/// Returns `nil` if a `URL` cannot be formed with the string (for example, if the string contains characters that are illegal in a URL, or is an empty string).
public init?(string: String, relativeTo url: URL?) {
guard !string.isEmpty else { return nil }
if let inner = NSURL(string: string, relativeTo: url) {
_url = URL._converted(from: inner)
} else {
return nil
}
}
/// Initializes a newly created file URL referencing the local file or directory at path, relative to a base URL.
///
/// If an empty string is used for the path, then the path is assumed to be ".".
/// - note: This function avoids an extra file system access to check if the file URL is a directory. You should use it if you know the answer already.
@available(OSX 10.11, iOS 9.0, *)
public init(fileURLWithPath path: String, isDirectory: Bool, relativeTo base: URL?) {
_url = URL._converted(from: NSURL(fileURLWithPath: path.isEmpty ? "." : path, isDirectory: isDirectory, relativeTo: base))
}
/// Initializes a newly created file URL referencing the local file or directory at path, relative to a base URL.
///
/// If an empty string is used for the path, then the path is assumed to be ".".
@available(OSX 10.11, iOS 9.0, *)
public init(fileURLWithPath path: String, relativeTo base: URL?) {
_url = URL._converted(from: NSURL(fileURLWithPath: path.isEmpty ? "." : path, relativeTo: base))
}
/// Initializes a newly created file URL referencing the local file or directory at path.
///
/// If an empty string is used for the path, then the path is assumed to be ".".
/// - note: This function avoids an extra file system access to check if the file URL is a directory. You should use it if you know the answer already.
public init(fileURLWithPath path: String, isDirectory: Bool) {
_url = URL._converted(from: NSURL(fileURLWithPath: path.isEmpty ? "." : path, isDirectory: isDirectory))
}
/// Initializes a newly created file URL referencing the local file or directory at path.
///
/// If an empty string is used for the path, then the path is assumed to be ".".
public init(fileURLWithPath path: String) {
_url = URL._converted(from: NSURL(fileURLWithPath: path.isEmpty ? "." : path))
}
/// Initializes a newly created URL using the contents of the given data, relative to a base URL.
///
/// If the data representation is not a legal URL string as ASCII bytes, the URL object may not behave as expected. If the URL cannot be formed then this will return nil.
@available(OSX 10.11, iOS 9.0, *)
public init?(dataRepresentation: Data, relativeTo url: URL?, isAbsolute: Bool = false) {
guard dataRepresentation.count > 0 else { return nil }
if isAbsolute {
_url = URL._converted(from: NSURL(absoluteURLWithDataRepresentation: dataRepresentation, relativeTo: url))
} else {
_url = URL._converted(from: NSURL(dataRepresentation: dataRepresentation, relativeTo: url))
}
}
/// Initializes a URL that refers to a location specified by resolving bookmark data.
public init?(resolvingBookmarkData data: Data, options: BookmarkResolutionOptions = [], relativeTo url: URL? = nil, bookmarkDataIsStale: inout Bool) throws {
var stale : ObjCBool = false
_url = URL._converted(from: try NSURL(resolvingBookmarkData: data, options: options, relativeTo: url, bookmarkDataIsStale: &stale))
bookmarkDataIsStale = stale.boolValue
}
/// Creates and initializes an NSURL that refers to the location specified by resolving the alias file at url. If the url argument does not refer to an alias file as defined by the NSURLIsAliasFileKey property, the NSURL returned is the same as url argument. This method fails and returns nil if the url argument is unreachable, or if the original file or directory could not be located or is not reachable, or if the original file or directory is on a volume that could not be located or mounted. The URLBookmarkResolutionWithSecurityScope option is not supported by this method.
@available(OSX 10.10, iOS 8.0, *)
public init(resolvingAliasFileAt url: URL, options: BookmarkResolutionOptions = []) throws {
self.init(reference: try NSURL(resolvingAliasFileAt: url, options: options))
}
/// Initializes a newly created URL referencing the local file or directory at the file system representation of the path. File system representation is a null-terminated C string with canonical UTF-8 encoding.
public init(fileURLWithFileSystemRepresentation path: UnsafePointer<Int8>, isDirectory: Bool, relativeTo baseURL: URL?) {
_url = URL._converted(from: NSURL(fileURLWithFileSystemRepresentation: path, isDirectory: isDirectory, relativeTo: baseURL))
}
public var hashValue: Int {
return _url.hash
}
// MARK: -
/// Returns the data representation of the URL's relativeString.
///
/// If the URL was initialized with `init?(dataRepresentation:relativeTo:isAbsolute:)`, the data representation returned are the same bytes as those used at initialization; otherwise, the data representation returned are the bytes of the `relativeString` encoded with UTF8 string encoding.
@available(OSX 10.11, iOS 9.0, *)
public var dataRepresentation: Data {
return _url.dataRepresentation
}
// MARK: -
// Future implementation note:
// NSURL (really CFURL, which provides its implementation) has quite a few quirks in its processing of some more esoteric (and some not so esoteric) strings. We would like to move much of this over to the more modern NSURLComponents, but binary compat concerns have made this difficult.
// Hopefully soon, we can replace some of the below delegation to NSURL with delegation to NSURLComponents instead. It cannot be done piecemeal, because otherwise we will get inconsistent results from the API.
/// Returns the absolute string for the URL.
public var absoluteString: String {
if let string = _url.absoluteString {
return string
} else {
// This should never fail for non-file reference URLs
return ""
}
}
/// The relative portion of a URL.
///
/// If `baseURL` is nil, or if the receiver is itself absolute, this is the same as `absoluteString`.
public var relativeString: String {
return _url.relativeString
}
/// Returns the base URL.
///
/// If the URL is itself absolute, then this value is nil.
public var baseURL: URL? {
return _url.baseURL
}
/// Returns the absolute URL.
///
/// If the URL is itself absolute, this will return self.
public var absoluteURL: URL {
if let url = _url.absoluteURL {
return url
} else {
// This should never fail for non-file reference URLs
return self
}
}
// MARK: -
/// Returns the scheme of the URL.
public var scheme: String? {
return _url.scheme
}
/// Returns true if the scheme is `file:`.
public var isFileURL: Bool {
return _url.isFileURL
}
// This thing was never really part of the URL specs
@available(*, unavailable, message: "Use `path`, `query`, and `fragment` instead")
public var resourceSpecifier: String {
fatalError()
}
/// If the URL conforms to RFC 1808 (the most common form of URL), returns the host component of the URL; otherwise it returns nil.
///
/// - note: This function will resolve against the base `URL`.
public var host: String? {
return _url.host
}
/// If the URL conforms to RFC 1808 (the most common form of URL), returns the port component of the URL; otherwise it returns nil.
///
/// - note: This function will resolve against the base `URL`.
public var port: Int? {
return _url.port?.intValue
}
/// If the URL conforms to RFC 1808 (the most common form of URL), returns the user component of the URL; otherwise it returns nil.
///
/// - note: This function will resolve against the base `URL`.
public var user: String? {
return _url.user
}
/// If the URL conforms to RFC 1808 (the most common form of URL), returns the password component of the URL; otherwise it returns nil.
///
/// - note: This function will resolve against the base `URL`.
public var password: String? {
return _url.password
}
/// If the URL conforms to RFC 1808 (the most common form of URL), returns the path component of the URL; otherwise it returns an empty string.
///
/// If the URL contains a parameter string, it is appended to the path with a `;`.
/// - note: This function will resolve against the base `URL`.
/// - returns: The path, or an empty string if the URL has an empty path.
public var path: String {
if let parameterString = _url.parameterString {
if let path = _url.path {
return path + ";" + parameterString
} else {
return ";" + parameterString
}
} else if let path = _url.path {
return path
} else {
return ""
}
}
/// If the URL conforms to RFC 1808 (the most common form of URL), returns the relative path of the URL; otherwise it returns nil.
///
/// This is the same as path if baseURL is nil.
/// If the URL contains a parameter string, it is appended to the path with a `;`.
///
/// - note: This function will resolve against the base `URL`.
/// - returns: The relative path, or an empty string if the URL has an empty path.
public var relativePath: String {
if let parameterString = _url.parameterString {
if let path = _url.relativePath {
return path + ";" + parameterString
} else {
return ";" + parameterString
}
} else if let path = _url.relativePath {
return path
} else {
return ""
}
}
/// If the URL conforms to RFC 1808 (the most common form of URL), returns the fragment component of the URL; otherwise it returns nil.
///
/// - note: This function will resolve against the base `URL`.
public var fragment: String? {
return _url.fragment
}
@available(*, unavailable, message: "use the 'path' property")
public var parameterString: String? {
fatalError()
}
/// If the URL conforms to RFC 1808 (the most common form of URL), returns the query of the URL; otherwise it returns nil.
///
/// - note: This function will resolve against the base `URL`.
public var query: String? {
return _url.query
}
/// Returns true if the URL path represents a directory.
@available(OSX 10.11, iOS 9.0, *)
public var hasDirectoryPath: Bool {
return _url.hasDirectoryPath
}
/// Passes the URL's path in file system representation to `block`.
///
/// File system representation is a null-terminated C string with canonical UTF-8 encoding.
/// - note: The pointer is not valid outside the context of the block.
@available(OSX 10.9, iOS 7.0, *)
public func withUnsafeFileSystemRepresentation<ResultType>(_ block: (UnsafePointer<Int8>?) throws -> ResultType) rethrows -> ResultType {
return try block(_url.fileSystemRepresentation)
}
// MARK: -
// MARK: Path manipulation
/// Returns the path components of the URL, or an empty array if the path is an empty string.
public var pathComponents: [String] {
// In accordance with our above change to never return a nil path, here we return an empty array.
return _url.pathComponents ?? []
}
/// Returns the last path component of the URL, or an empty string if the path is an empty string.
public var lastPathComponent: String {
return _url.lastPathComponent ?? ""
}
/// Returns the path extension of the URL, or an empty string if the path is an empty string.
public var pathExtension: String {
return _url.pathExtension ?? ""
}
/// Returns a URL constructed by appending the given path component to self.
///
/// - parameter pathComponent: The path component to add.
/// - parameter isDirectory: If `true`, then a trailing `/` is added to the resulting path.
public func appendingPathComponent(_ pathComponent: String, isDirectory: Bool) -> URL {
if let result = _url.appendingPathComponent(pathComponent, isDirectory: isDirectory) {
return result
} else {
// Now we need to do something more expensive
if var c = URLComponents(url: self, resolvingAgainstBaseURL: true) {
c.path = (c.path as NSString).appendingPathComponent(pathComponent)
if let result = c.url {
return result
} else {
// Couldn't get url from components
// Ultimate fallback:
return self
}
} else {
return self
}
}
}
/// Returns a URL constructed by appending the given path component to self.
///
/// - note: This function performs a file system operation to determine if the path component is a directory. If so, it will append a trailing `/`. If you know in advance that the path component is a directory or not, then use `func appendingPathComponent(_:isDirectory:)`.
/// - parameter pathComponent: The path component to add.
public func appendingPathComponent(_ pathComponent: String) -> URL {
if let result = _url.appendingPathComponent(pathComponent) {
return result
} else {
// Now we need to do something more expensive
if var c = URLComponents(url: self, resolvingAgainstBaseURL: true) {
c.path = (c.path as NSString).appendingPathComponent(pathComponent)
if let result = c.url {
return result
} else {
// Couldn't get url from components
// Ultimate fallback:
return self
}
} else {
// Ultimate fallback:
return self
}
}
}
/// Returns a URL constructed by removing the last path component of self.
///
/// This function may either remove a path component or append `/..`.
///
/// If the URL has an empty path (e.g., `http://www.example.com`), then this function will return the URL unchanged.
public func deletingLastPathComponent() -> URL {
// This is a slight behavior change from NSURL, but better than returning "http://www.example.com../".
if path.isEmpty {
return self
}
if let result = _url.deletingLastPathComponent.map({ URL(reference: $0 as NSURL) }) {
return result
} else {
return self
}
}
/// Returns a URL constructed by appending the given path extension to self.
///
/// If the URL has an empty path (e.g., `http://www.example.com`), then this function will return the URL unchanged.
///
/// Certain special characters (for example, Unicode Right-To-Left marks) cannot be used as path extensions. If any of those are contained in `pathExtension`, the function will return the URL unchanged.
/// - parameter pathExtension: The extension to append.
public func appendingPathExtension(_ pathExtension: String) -> URL {
if path.isEmpty {
return self
}
if let result = _url.appendingPathExtension(pathExtension) {
return result
} else {
return self
}
}
/// Returns a URL constructed by removing any path extension.
///
/// If the URL has an empty path (e.g., `http://www.example.com`), then this function will return the URL unchanged.
public func deletingPathExtension() -> URL {
if path.isEmpty {
return self
}
if let result = _url.deletingPathExtension.map({ URL(reference: $0 as NSURL) }) {
return result
} else {
return self
}
}
/// Appends a path component to the URL.
///
/// - parameter pathComponent: The path component to add.
/// - parameter isDirectory: Use `true` if the resulting path is a directory.
public mutating func appendPathComponent(_ pathComponent: String, isDirectory: Bool) {
self = appendingPathComponent(pathComponent, isDirectory: isDirectory)
}
/// Appends a path component to the URL.
///
/// - note: This function performs a file system operation to determine if the path component is a directory. If so, it will append a trailing `/`. If you know in advance that the path component is a directory or not, then use `func appendingPathComponent(_:isDirectory:)`.
/// - parameter pathComponent: The path component to add.
public mutating func appendPathComponent(_ pathComponent: String) {
self = appendingPathComponent(pathComponent)
}
/// Appends the given path extension to self.
///
/// If the URL has an empty path (e.g., `http://www.example.com`), then this function will do nothing.
/// Certain special characters (for example, Unicode Right-To-Left marks) cannot be used as path extensions. If any of those are contained in `pathExtension`, the function will return the URL unchanged.
/// - parameter pathExtension: The extension to append.
public mutating func appendPathExtension(_ pathExtension: String) {
self = appendingPathExtension(pathExtension)
}
/// Returns a URL constructed by removing the last path component of self.
///
/// This function may either remove a path component or append `/..`.
///
/// If the URL has an empty path (e.g., `http://www.example.com`), then this function will do nothing.
public mutating func deleteLastPathComponent() {
self = deletingLastPathComponent()
}
/// Returns a URL constructed by removing any path extension.
///
/// If the URL has an empty path (e.g., `http://www.example.com`), then this function will do nothing.
public mutating func deletePathExtension() {
self = deletingPathExtension()
}
/// Returns a `URL` with any instances of ".." or "." removed from its path.
public var standardized : URL {
// The NSURL API can only return nil in case of file reference URL, which we should not be
if let result = _url.standardized.map({ URL(reference: $0 as NSURL) }) {
return result
} else {
return self
}
}
/// Standardizes the path of a file URL.
///
/// If the `isFileURL` is false, this method does nothing.
public mutating func standardize() {
self = self.standardized
}
/// Standardizes the path of a file URL.
///
/// If the `isFileURL` is false, this method returns `self`.
public var standardizedFileURL : URL {
// NSURL should not return nil here unless this is a file reference URL, which should be impossible
if let result = _url.standardizingPath.map({ URL(reference: $0 as NSURL) }) {
return result
} else {
return self
}
}
/// Resolves any symlinks in the path of a file URL.
///
/// If the `isFileURL` is false, this method returns `self`.
public func resolvingSymlinksInPath() -> URL {
// NSURL should not return nil here unless this is a file reference URL, which should be impossible
if let result = _url.resolvingSymlinksInPath.map({ URL(reference: $0 as NSURL) }) {
return result
} else {
return self
}
}
/// Resolves any symlinks in the path of a file URL.
///
/// If the `isFileURL` is false, this method does nothing.
public mutating func resolveSymlinksInPath() {
self = self.resolvingSymlinksInPath()
}
// MARK: - Reachability
/// Returns whether the URL's resource exists and is reachable.
///
/// This method synchronously checks if the resource's backing store is reachable. Checking reachability is appropriate when making decisions that do not require other immediate operations on the resource, e.g. periodic maintenance of UI state that depends on the existence of a specific document. When performing operations such as opening a file or copying resource properties, it is more efficient to simply try the operation and handle failures. This method is currently applicable only to URLs for file system resources. For other URL types, `false` is returned.
public func checkResourceIsReachable() throws -> Bool {
var error : NSError?
let result = _url.checkResourceIsReachableAndReturnError(&error)
if let e = error {
throw e
} else {
return result
}
}
/// Returns whether the promised item URL's resource exists and is reachable.
///
/// This method synchronously checks if the resource's backing store is reachable. Checking reachability is appropriate when making decisions that do not require other immediate operations on the resource, e.g. periodic maintenance of UI state that depends on the existence of a specific document. When performing operations such as opening a file or copying resource properties, it is more efficient to simply try the operation and handle failures. This method is currently applicable only to URLs for file system resources. For other URL types, `false` is returned.
@available(OSX 10.10, iOS 8.0, *)
public func checkPromisedItemIsReachable() throws -> Bool {
var error : NSError?
let result = _url.checkPromisedItemIsReachableAndReturnError(&error)
if let e = error {
throw e
} else {
return result
}
}
// MARK: - Resource Values
/// Sets the resource value identified by a given resource key.
///
/// This method writes the new resource values out to the backing store. Attempts to set a read-only resource property or to set a resource property not supported by the resource are ignored and are not considered errors. This method is currently applicable only to URLs for file system resources.
///
/// `URLResourceValues` keeps track of which of its properties have been set. Those values are the ones used by this function to determine which properties to write.
public mutating func setResourceValues(_ values: URLResourceValues) throws {
try _url.setResourceValues(values._values)
}
/// Return a collection of resource values identified by the given resource keys.
///
/// This method first checks if the URL object already caches the resource value. If so, it returns the cached resource value to the caller. If not, then this method synchronously obtains the resource value from the backing store, adds the resource value to the URL object's cache, and returns the resource value to the caller. The type of the resource value varies by resource property (see resource key definitions). If this method does not throw and the resulting value in the `URLResourceValues` is populated with nil, it means the resource property is not available for the specified resource and no errors occurred when determining the resource property was not available. This method is currently applicable only to URLs for file system resources.
///
/// When this function is used from the main thread, resource values cached by the URL (except those added as temporary properties) are removed the next time the main thread's run loop runs. `func removeCachedResourceValue(forKey:)` and `func removeAllCachedResourceValues()` also may be used to remove cached resource values.
///
/// Only the values for the keys specified in `keys` will be populated.
public func resourceValues(forKeys keys: Set<URLResourceKey>) throws -> URLResourceValues {
return URLResourceValues(keys: keys, values: try _url.resourceValues(forKeys: Array(keys)))
}
/// Sets a temporary resource value on the URL object.
///
/// Temporary resource values are for client use. Temporary resource values exist only in memory and are never written to the resource's backing store. Once set, a temporary resource value can be copied from the URL object with `func resourceValues(forKeys:)`. The values are stored in the loosely-typed `allValues` dictionary property.
///
/// To remove a temporary resource value from the URL object, use `func removeCachedResourceValue(forKey:)`. Care should be taken to ensure the key that identifies a temporary resource value is unique and does not conflict with system defined keys (using reverse domain name notation in your temporary resource value keys is recommended). This method is currently applicable only to URLs for file system resources.
public mutating func setTemporaryResourceValue(_ value : Any, forKey key: URLResourceKey) {
_url.setTemporaryResourceValue(value, forKey: key)
}
/// Removes all cached resource values and all temporary resource values from the URL object.
///
/// This method is currently applicable only to URLs for file system resources.
public mutating func removeAllCachedResourceValues() {
_url.removeAllCachedResourceValues()
}
/// Removes the cached resource value identified by a given resource value key from the URL object.
///
/// Removing a cached resource value may remove other cached resource values because some resource values are cached as a set of values, and because some resource values depend on other resource values (temporary resource values have no dependencies). This method is currently applicable only to URLs for file system resources.
public mutating func removeCachedResourceValue(forKey key: URLResourceKey) {
_url.removeCachedResourceValue(forKey: key)
}
/// Get resource values from URLs of 'promised' items.
///
/// A promised item is not guaranteed to have its contents in the file system until you use `FileCoordinator` to perform a coordinated read on its URL, which causes the contents to be downloaded or otherwise generated. Promised item URLs are returned by various APIs, including currently:
/// NSMetadataQueryUbiquitousDataScope
/// NSMetadataQueryUbiquitousDocumentsScope
/// A `FilePresenter` presenting the contents of the directory located by -URLForUbiquitousContainerIdentifier: or a subdirectory thereof
///
/// The following methods behave identically to their similarly named methods above (`func resourceValues(forKeys:)`, etc.), except that they allow you to get resource values and check for presence regardless of whether the promised item's contents currently exist at the URL. You must use these APIs instead of the normal URL resource value APIs if and only if any of the following are true:
/// You are using a URL that you know came directly from one of the above APIs
/// You are inside the accessor block of a coordinated read or write that used NSFileCoordinatorReadingImmediatelyAvailableMetadataOnly, NSFileCoordinatorWritingForDeleting, NSFileCoordinatorWritingForMoving, or NSFileCoordinatorWritingContentIndependentMetadataOnly
///
/// Most of the URL resource value keys will work with these APIs. However, there are some that are tied to the item's contents that will not work, such as `contentAccessDateKey` or `generationIdentifierKey`. If one of these keys is used, the method will return a `URLResourceValues` value, but the value for that property will be nil.
@available(OSX 10.10, iOS 8.0, *)
public func promisedItemResourceValues(forKeys keys: Set<URLResourceKey>) throws -> URLResourceValues {
return URLResourceValues(keys: keys, values: try _url.promisedItemResourceValues(forKeys: Array(keys)))
}
@available(*, unavailable, message: "Use struct URLResourceValues and URL.setResourceValues(_:) instead")
public func setResourceValue(_ value: AnyObject?, forKey key: URLResourceKey) throws {
fatalError()
}
@available(*, unavailable, message: "Use struct URLResourceValues and URL.setResourceValues(_:) instead")
public func setResourceValues(_ keyedValues: [URLResourceKey : AnyObject]) throws {
fatalError()
}
@available(*, unavailable, message: "Use struct URLResourceValues and URL.setResourceValues(_:) instead")
public func getResourceValue(_ value: AutoreleasingUnsafeMutablePointer<AnyObject?>, forKey key: URLResourceKey) throws {
fatalError()
}
// MARK: - Bookmarks and Alias Files
/// Returns bookmark data for the URL, created with specified options and resource values.
public func bookmarkData(options: BookmarkCreationOptions = [], includingResourceValuesForKeys keys: Set<URLResourceKey>? = nil, relativeTo url: URL? = nil) throws -> Data {
let result = try _url.bookmarkData(options: options, includingResourceValuesForKeys: keys.flatMap { Array($0) }, relativeTo: url)
return result as Data
}
/// Returns the resource values for properties identified by a specified array of keys contained in specified bookmark data. If the result dictionary does not contain a resource value for one or more of the requested resource keys, it means those resource properties are not available in the bookmark data.
public static func resourceValues(forKeys keys: Set<URLResourceKey>, fromBookmarkData data: Data) -> URLResourceValues? {
return NSURL.resourceValues(forKeys: Array(keys), fromBookmarkData: data).map { URLResourceValues(keys: keys, values: $0) }
}
/// Creates an alias file on disk at a specified location with specified bookmark data. bookmarkData must have been created with the URLBookmarkCreationSuitableForBookmarkFile option. bookmarkFileURL must either refer to an existing file (which will be overwritten), or to location in an existing directory.
public static func writeBookmarkData(_ data : Data, to url: URL) throws {
// Options are unused
try NSURL.writeBookmarkData(data, to: url, options: 0)
}
/// Initializes and returns bookmark data derived from an alias file pointed to by a specified URL. If bookmarkFileURL refers to an alias file created prior to OS X v10.6 that contains Alias Manager information but no bookmark data, this method synthesizes bookmark data for the file.
public static func bookmarkData(withContentsOf url: URL) throws -> Data {
let result = try NSURL.bookmarkData(withContentsOf: url)
return result as Data
}
/// Given an NSURL created by resolving a bookmark data created with security scope, make the resource referenced by the url accessible to the process. When access to this resource is no longer needed the client must call stopAccessingSecurityScopedResource. Each call to startAccessingSecurityScopedResource must be balanced with a call to stopAccessingSecurityScopedResource (Note: this is not reference counted).
@available(OSX 10.7, iOS 8.0, *)
public func startAccessingSecurityScopedResource() -> Bool {
return _url.startAccessingSecurityScopedResource()
}
/// Revokes the access granted to the url by a prior successful call to startAccessingSecurityScopedResource.
@available(OSX 10.7, iOS 8.0, *)
public func stopAccessingSecurityScopedResource() {
_url.stopAccessingSecurityScopedResource()
}
// MARK: - Bridging Support
/// We must not store an NSURL without running it through this function. This makes sure that we do not hold a file reference URL, which changes the nullability of many NSURL functions.
private static func _converted(from url: NSURL) -> NSURL {
// Future readers: file reference URL here is not the same as playgrounds "file reference"
if url.isFileReferenceURL() {
// Convert to a file path URL, or use an invalid scheme
return (url.filePathURL ?? URL(string: "com-apple-unresolvable-file-reference-url:")!) as NSURL
} else {
return url
}
}
fileprivate init(reference: NSURL) {
_url = URL._converted(from: reference).copy() as! NSURL
}
private var reference : NSURL {
return _url
}
public static func ==(lhs: URL, rhs: URL) -> Bool {
return lhs.reference.isEqual(rhs.reference)
}
}
extension URL : _ObjectiveCBridgeable {
@_semantics("convertToObjectiveC")
public func _bridgeToObjectiveC() -> NSURL {
return _url
}
public static func _forceBridgeFromObjectiveC(_ source: NSURL, result: inout URL?) {
if !_conditionallyBridgeFromObjectiveC(source, result: &result) {
fatalError("Unable to bridge \(_ObjectiveCType.self) to \(self)")
}
}
public static func _conditionallyBridgeFromObjectiveC(_ source: NSURL, result: inout URL?) -> Bool {
result = URL(reference: source)
return true
}
public static func _unconditionallyBridgeFromObjectiveC(_ source: NSURL?) -> URL {
var result: URL?
_forceBridgeFromObjectiveC(source!, result: &result)
return result!
}
}
extension URL : CustomStringConvertible, CustomDebugStringConvertible {
public var description: String {
return _url.description
}
public var debugDescription: String {
return _url.debugDescription
}
}
extension NSURL : _HasCustomAnyHashableRepresentation {
// Must be @nonobjc to avoid infinite recursion during bridging.
@nonobjc
public func _toCustomAnyHashable() -> AnyHashable? {
return AnyHashable(self as URL)
}
}
extension URL : CustomPlaygroundQuickLookable {
public var customPlaygroundQuickLook: PlaygroundQuickLook {
return .url(absoluteString)
}
}
extension URL : Codable {
private enum CodingKeys : Int, CodingKey {
case base
case relative
}
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
let relative = try container.decode(String.self, forKey: .relative)
let base = try container.decodeIfPresent(URL.self, forKey: .base)
guard let url = URL(string: relative, relativeTo: base) else {
throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: decoder.codingPath,
debugDescription: "Invalid URL string."))
}
self = url
}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(self.relativeString, forKey: .relative)
if let base = self.baseURL {
try container.encode(base, forKey: .base)
}
}
}
//===----------------------------------------------------------------------===//
// File references, for playgrounds.
//===----------------------------------------------------------------------===//
extension URL : _ExpressibleByFileReferenceLiteral {
public init(fileReferenceLiteralResourceName name: String) {
self = Bundle.main.url(forResource: name, withExtension: nil)!
}
}
public typealias _FileReferenceLiteralType = URL
| apache-2.0 | b5fe643d41132c1c96cc7f1f38af4760 | 51.941506 | 765 | 0.68555 | 4.98762 | false | false | false | false |
things-nyc/mapthethings-ios | MapTheThings/MapViewController.swift | 1 | 6143 | //
// MapViewController.swift
// MapTheThings
//
// Created by Frank on 2016/6/30.
// Copyright © 2016 The Things Network New York. All rights reserved.
//
import UIKit
import CoreLocation
import MapKit
// Wrote up here: http://stackoverflow.com/a/38236363/1207583
extension MKMapView {
func edgePoints() -> Edges {
let corners = [
CGPoint(x: self.bounds.minX, y: self.bounds.minY),
CGPoint(x: self.bounds.minX, y: self.bounds.maxY),
CGPoint(x: self.bounds.maxX, y: self.bounds.maxY),
CGPoint(x: self.bounds.maxX, y: self.bounds.minY)
]
let coords = corners.map { corner in
self.convert(corner, toCoordinateFrom: self)
}
let startBounds = (
n: coords[0].latitude, s: coords[0].latitude,
e: coords[0].longitude, w: coords[0].longitude)
let bounds = coords.reduce(startBounds) { b, c in
let n = max(b.n, c.latitude)
let s = min(b.s, c.latitude)
let e = max(b.e, c.longitude)
let w = min(b.w, c.longitude)
return (n: n, s: s, e: e, w: w)
}
return (ne: CLLocationCoordinate2D(latitude: bounds.n, longitude: bounds.e),
sw: CLLocationCoordinate2D(latitude: bounds.s, longitude: bounds.w))
}
}
class MapViewController: AppStateUIViewController, MKMapViewDelegate, UIGestureRecognizerDelegate {
@IBOutlet weak var timestamp: UILabel!
@IBOutlet weak var toggle: UIButton!
@IBOutlet weak var notice: UILabel!
@IBOutlet weak var mapView: MKMapView!
var lastSamples: Set<SampleAnnotation>?
var mapDragRecognizer: UIPanGestureRecognizer!
override func viewDidLoad() {
super.viewDidLoad()
mapView.delegate = self
// Wire up gesture recognizer so that we can stop tracking when the user moves map elsewhere
mapDragRecognizer = UIPanGestureRecognizer(target: self, action: #selector(didDragMap))
mapDragRecognizer.delegate = self
mapView.addGestureRecognizer(mapDragRecognizer)
}
func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith
otherGestureRecognizer: UIGestureRecognizer) -> Bool {
// Thanks http://stackoverflow.com/a/5089553/1207583
return true
}
func didDragMap(_ gestureRecognizer: UIGestureRecognizer) {
if (gestureRecognizer.state == .began) {
updateAppState { (old) -> AppState in
var state = old
state.map.tracking = false
return state
}
}
}
func mapView(_ mapView: MKMapView, regionDidChangeAnimated animated: Bool) {
let edges = mapView.edgePoints()
updateAppState { (old) -> AppState in
var state = old
state.map.bounds = (edges.ne, edges.sw)
return state
}
}
@IBAction func toggleTracking(_ event: UIEvent) {
updateAppState { (old) -> AppState in
var state = old
state.map.tracking = !state.map.tracking
return state
}
}
override func renderAppState(_ oldState: AppState, state: AppState) {
if let location = state.map.currentLocation {
// Show current location in lat/lon on top of view
let cordinateLong = location.coordinate.longitude
let cordinateLat = location.coordinate.latitude
let truncatedCoordinates = String(format: "Lat: %.3f, Lon: %.3f", cordinateLat, cordinateLong)
self.timestamp.text = truncatedCoordinates
}
self.toggle.setTitle("Toggle Tracking: " + (state.map.tracking ? "True" : "False"), for: UIControlState())
if (state.map.tracking) {
mapView.setUserTrackingMode(MKUserTrackingMode.follow, animated:true)
}
else {
mapView.setUserTrackingMode(MKUserTrackingMode.none, animated:true)
}
var ls: String? = Optional.none
switch state.map.locationAuthStatus {
case .authorizedAlways, .authorizedWhenInUse: break;
case .denied: ls = String("Denied"); break;
case .restricted: ls = String("Restricted"); break;
case .notDetermined: ls = String("Unknown"); break;
}
if let status = ls {
notice.text = "Location Services \(status)"
notice.isHidden = false
}
else {
notice.isHidden = true
}
// TODO
// - In Sampling mode, show last sample info
let samples = state.map.samples.map { (s) -> SampleAnnotation in
return SampleAnnotation(sample: s)
}
let transmissions = state.map.transmissions.map { (s) -> SampleAnnotation in
return SampleAnnotation(transSample: s)
}
let new = Set<SampleAnnotation>(samples).union(Set<SampleAnnotation>(transmissions))
if let last = self.lastSamples {
// Figure out what remains, what gets added, and what gets removed
let same = last.intersection(new)
let add = new.subtracting(same)
let remove = last.subtracting(same)
if !remove.isEmpty {
//debugPrint("Removing", remove.count)
switch remove.count {
case 1: self.mapView.removeAnnotation(remove.first!)
default: self.mapView.removeAnnotations([SampleAnnotation](remove))
}
}
if !add.isEmpty {
//debugPrint("Adding", add.count)
self.mapView.addAnnotations([SampleAnnotation](add))
}
self.lastSamples = same.union(add)
}
else {
// No prior samples - add all annotations
self.mapView.addAnnotations([SampleAnnotation](new))
self.lastSamples = new
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| mit | 49471a06e2525739312abdafecf32ea0 | 36.680982 | 114 | 0.598665 | 4.70291 | false | false | false | false |
gobetti/Swift | SwiftLoginScreen/SwiftLoginScreen/LoginVC.swift | 1 | 8289 | //
// LoginVC.swift
// SwiftLoginScreen
//
// Created by Carlos Butron on 12/04/14.
// Copyright (c) 2015 Carlos Butron. All rights reserved.
//
// This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public
// License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later
// version.
// This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied
// warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
// You should have received a copy of the GNU General Public License along with this program. If not, see
// http:/www.gnu.org/licenses/.
//
import UIKit
class LoginVC: UIViewController,UITextFieldDelegate {
@IBOutlet var txtUsername : UITextField!
@IBOutlet var txtPassword : UITextField!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// #pragma 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.
}
*/
@IBAction func signinTapped(sender : UIButton) {
let username:NSString = (txtUsername.text)!
let password:NSString = (txtPassword.text)!
if ( username.isEqualToString("") || password.isEqualToString("") ) {
let alertController = UIAlertController(title: "Sign in Failed!", message: "Please enter Username and Password", preferredStyle:UIAlertControllerStyle.Alert)
let OKAction = UIAlertAction(title: "OK", style: .Default) { (action:UIAlertAction!) in
print("you have pressed OK button");
}
alertController.addAction(OKAction)
self.presentViewController(alertController, animated: true, completion:{ () -> Void in
//your code here
})
} else {
let post:NSString = "username=\(username)&password=\(password)"
NSLog("PostData: %@",post);
let url:NSURL = NSURL(string:"http://carlosbutron.es/iOS/jsonlogin2.php")!
let postData:NSData = post.dataUsingEncoding(NSASCIIStringEncoding)!
let postLength:NSString = String( postData.length )
let request:NSMutableURLRequest = NSMutableURLRequest(URL: url)
request.HTTPMethod = "POST"
request.HTTPBody = postData
request.setValue(postLength as String, forHTTPHeaderField: "Content-Length")
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
request.setValue("application/json", forHTTPHeaderField: "Accept")
var reponseError: NSError?
var response: NSURLResponse?
var urlData: NSData?
do {
urlData = try NSURLConnection.sendSynchronousRequest(request, returningResponse:&response)
} catch let error as NSError {
reponseError = error
urlData = nil
}
if ( urlData != nil ) {
let res = response as! NSHTTPURLResponse!;
NSLog("Response code: %ld", res.statusCode);
if (res.statusCode >= 200 && res.statusCode < 300)
{
let responseData:NSString = NSString(data:urlData!, encoding:NSUTF8StringEncoding)!
NSLog("Response ==> %@", responseData);
let jsonData:NSDictionary = (try! NSJSONSerialization.JSONObjectWithData(urlData!, options:NSJSONReadingOptions.MutableContainers )) as! NSDictionary
let success:NSInteger = jsonData.valueForKey("success") as! NSInteger
//[jsonData[@"success"] integerValue];
NSLog("Success: %ld", success);
if(success == 1)
{
NSLog("Login SUCCESS");
let prefs:NSUserDefaults = NSUserDefaults.standardUserDefaults()
prefs.setObject(username, forKey: "USERNAME")
prefs.setInteger(1, forKey: "ISLOGGEDIN")
prefs.synchronize()
self.dismissViewControllerAnimated(true, completion: nil)
} else {
var error_msg:NSString
if jsonData["error_message"] as? NSString != nil {
error_msg = jsonData["error_message"] as! NSString
} else {
error_msg = "Unknown Error"
}
let alertController = UIAlertController(title: "Sign in Failed!", message: error_msg as String, preferredStyle:UIAlertControllerStyle.Alert)
let OKAction = UIAlertAction(title: "OK", style: .Default) { (action:UIAlertAction!) in
print("you have pressed OK button");
}
alertController.addAction(OKAction)
self.presentViewController(alertController, animated: true, completion:{ () -> Void in
//your code here
})
}
} else {
let alertController = UIAlertController(title: "Sign in Failed!", message: "Connection Failed", preferredStyle:UIAlertControllerStyle.Alert)
let OKAction = UIAlertAction(title: "OK", style: .Default) { (action:UIAlertAction!) in
print("you have pressed OK button");
}
alertController.addAction(OKAction)
self.presentViewController(alertController, animated: true, completion:{ () -> Void in
//your code here
})
}
} else {
let alertController = UIAlertController(title: "Sign in Failed!", message: "Connection Failure", preferredStyle:UIAlertControllerStyle.Alert)
if let error = reponseError {
alertController.message = (error.localizedDescription)
}
let OKAction = UIAlertAction(title: "OK", style: .Default) { (action:UIAlertAction!) in
print("you have pressed OK button");
}
alertController.addAction(OKAction)
self.presentViewController(alertController, animated: true, completion:{ () -> Void in
//your code here
})
}
}
}
func textFieldShouldReturn(textField: UITextField) -> Bool { //delegate method
textField.resignFirstResponder()
return true
}
}
| mit | bf4999dbf30316d7244e8388e12d0b70 | 39.237864 | 169 | 0.514175 | 6.410673 | false | false | false | false |
LoveZYForever/HXWeiboPhotoPicker | Pods/HXPHPicker/Sources/HXPHPicker/Camera/Model/CameraFilter.swift | 1 | 5354 | //
// CameraFilter.swift
// HXPHPicker
//
// Created by Slience on 2022/2/15.
//
import UIKit
import Accelerate
import VideoToolbox
public protocol CameraFilter {
/// 滤镜名称
var filterName: String { get }
/// 准备滤镜
func prepare(_ size: CGSize)
/// 添加滤镜
func render(_ pixelBuffer: CVPixelBuffer) -> CIImage?
func render(
_ pixelBuffer: CVPixelBuffer,
_ pixelBufferPool: CVPixelBufferPool,
_ context: CIContext
) -> CVPixelBuffer?
/// 重置
func reset()
}
public extension CameraFilter {
func prepare(_ size: CGSize) { }
func render(_ pixelBuffer: CVPixelBuffer) -> CIImage? { nil }
func render(
_ pixelBuffer: CVPixelBuffer,
_ pixelBufferPool: CVPixelBufferPool,
_ context: CIContext
) -> CVPixelBuffer? { nil }
func reset() { }
}
public class ToasterFilter: CameraFilter {
public var filterName: String {
"怀旧".localized
}
var filter: CIFilter?
public func prepare(_ size: CGSize) {
let width = size.width
let height = size.height
let centerWidth = width / 2.0
let centerHeight = height / 2.0
let radius0 = min(width / 4.0, height / 4.0)
let radius1 = min(width / 1.5, height / 1.5)
let color0 = PhotoTools.getColor(red: 128, green: 78, blue: 15, alpha: 255)
let color1 = PhotoTools.getColor(red: 79, green: 0, blue: 79, alpha: 255)
let filter = CIFilter(name: "CIRadialGradient", parameters: [
"inputCenter": CIVector(x: centerWidth, y: centerHeight),
"inputRadius0": radius0,
"inputRadius1": radius1,
"inputColor0": color0,
"inputColor1": color1
])
self.filter = filter
}
public func render(_ pixelBuffer: CVPixelBuffer) -> CIImage? {
let sourceImage = CIImage(cvImageBuffer: pixelBuffer)
guard let toasterImage = filter?
.outputImage?
.cropped(to: sourceImage.extent)
else {
return nil
}
let filteredImage = sourceImage
.applyingFilter(
"CIColorControls",
parameters: [
"inputSaturation": 1.0,
"inputBrightness": 0.01,
"inputContrast": 1.1
]
)
.applyingFilter(
"CIScreenBlendMode",
parameters: [
"inputBackgroundImage": toasterImage
]
)
return filteredImage
}
public func reset() {
filter = nil
}
public init() { }
}
public class InstantFilter: CameraFilter {
public var filterName: String {
"梦幻".localized
}
var filter: CIFilter?
public func prepare(_ size: CGSize) {
let filter = CIFilter(name: "CIPhotoEffectInstant", parameters: [:])
self.filter = filter
}
public func render(_ pixelBuffer: CVPixelBuffer) -> CIImage? {
let sourceImage = CIImage(cvImageBuffer: pixelBuffer)
filter?.setValue(sourceImage, forKey: kCIInputImageKey)
return filter?.outputImage?.cropped(to: sourceImage.extent)
}
public func reset() {
filter = nil
}
public init() { }
}
public class Apply1977Filter: CameraFilter {
public var filterName: String {
"1977".localized
}
public func render(_ pixelBuffer: CVPixelBuffer) -> CIImage? {
let sourceImage = CIImage(cvImageBuffer: pixelBuffer)
let filterImage = PhotoTools.getColorImage(
red: 243, green: 106, blue: 188, alpha: Int(255 * 0.1),
rect: sourceImage.extent
)
let backgroundImage = sourceImage
.applyingFilter("CIColorControls", parameters: [
"inputSaturation": 1.3,
"inputBrightness": 0.1,
"inputContrast": 1.05
])
.applyingFilter("CIHueAdjust", parameters: [
"inputAngle": 0.3
])
return filterImage
.applyingFilter("CIScreenBlendMode", parameters: [
"inputBackgroundImage": backgroundImage
])
.applyingFilter("CIToneCurve", parameters: [
"inputPoint0": CIVector(x: 0, y: 0),
"inputPoint1": CIVector(x: 0.25, y: 0.20),
"inputPoint2": CIVector(x: 0.5, y: 0.5),
"inputPoint3": CIVector(x: 0.75, y: 0.80),
"inputPoint4": CIVector(x: 1, y: 1)
])
}
public init() { }
}
public class TransferFilter: CameraFilter {
public var filterName: String {
"岁月".localized
}
var filter: CIFilter?
public func prepare(_ size: CGSize) {
let filter = CIFilter(name: "CIPhotoEffectTransfer", parameters: [:])
self.filter = filter
}
public func render(_ pixelBuffer: CVPixelBuffer) -> CIImage? {
let sourceImage = CIImage(cvImageBuffer: pixelBuffer)
filter?.setValue(sourceImage, forKey: kCIInputImageKey)
return filter?.outputImage?.cropped(to: sourceImage.extent)
}
public func reset() {
filter = nil
}
public init() { }
}
| mit | 16c86d21ebd7035f1c9d9f6dd7fdcfe6 | 28.359116 | 83 | 0.559089 | 4.702655 | false | false | false | false |
danielgindi/Charts | Source/Charts/Data/Implementations/Standard/PieChartData.swift | 2 | 2533 | //
// PieData.swift
// Charts
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/Charts
//
import Foundation
open class PieChartData: ChartData
{
public required init()
{
super.init()
}
public override init(dataSets: [ChartDataSetProtocol])
{
super.init(dataSets: dataSets)
}
public required init(arrayLiteral elements: ChartDataSetProtocol...)
{
super.init(dataSets: elements)
}
@objc public var dataSet: PieChartDataSetProtocol?
{
get
{
return dataSets.first as? PieChartDataSetProtocol
}
set
{
if let set = newValue
{
dataSets = [set]
}
else
{
dataSets = []
}
}
}
/// - returns: All up to one dataSet object this ChartData object holds.
@objc open override var dataSets: [ChartDataSetProtocol]
{
get
{
assert(super.dataSets.count <= 1, "Found multiple data sets while pie chart only allows one")
return super.dataSets
}
set
{
super.dataSets = newValue
}
}
open override func dataSet(at index: ChartData.Index) -> ChartData.Element?
{
guard index == 0 else { return nil }
return self[index]
}
open override func dataSet(forLabel label: String, ignorecase: Bool) -> ChartDataSetProtocol?
{
if dataSets.first?.label == nil
{
return nil
}
if ignorecase
{
if let label = dataSets[0].label, label.caseInsensitiveCompare(label) == .orderedSame
{
return dataSets[0]
}
}
else
{
if label == dataSets[0].label
{
return dataSets[0]
}
}
return nil
}
@objc override open func entry(for highlight: Highlight) -> ChartDataEntry?
{
return dataSet?.entryForIndex(Int(highlight.x))
}
/// The total y-value sum across all DataSet objects the this object represents.
@objc open var yValueSum: Double
{
guard let dataSet = dataSet else { return 0.0 }
return (0..<dataSet.entryCount).reduce(into: 0) {
$0 += dataSet.entryForIndex($1)?.y ?? 0
}
}
}
| apache-2.0 | 0071984d7bd6c66694280306a1fcc54e | 22.672897 | 105 | 0.534939 | 4.85249 | false | false | false | false |
CodeEagle/SSPhotoKit | Example/Pods/SSImageBrowser/Source/SSCaptionView.swift | 1 | 4432 | //
// SSCaptionView.swift
// Pods
//
// Created by LawLincoln on 15/7/10.
//
//
import UIKit
public class SSCaptionView: UIView {
var photo: SSPhoto!
private var labelPadding: CGFloat {
return 10
}
private var label: UILabel!
convenience init(aPhoto:SSPhoto) {
let screenBound = UIScreen.mainScreen().bounds
var screenWidth = screenBound.size.width
let orientation = UIDevice.currentDevice().orientation
if orientation == .LandscapeLeft ||
orientation == .LandscapeRight {
screenWidth = screenBound.size.height
}
self.init(frame: CGRectMake(0, 0, screenWidth, 44))
photo = aPhoto
opaque = false
setBackground()
setupCaption()
}
public override init(frame: CGRect) {
super.init(frame: frame)
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
public override func layoutSubviews() {
super.layoutSubviews()
if let view = viewWithTag(101) {
view.frame = CGRectMake(0, -100, UIScreen.mainScreen().bounds.width, 130+100)
}
}
/**
To create your own custom caption view, subclass this view
and override the following two methods (as well as any other
UIView methods that you see fit):
Override -setupCaption so setup your subviews and customise the appearance
of your custom caption
You can access the photo's data by accessing the _photo ivar
If you need more data per photo then simply subclass IDMPhoto and return your
subclass to the photo browsers -photoBrowser:photoAtIndex: delegate method
*/
public func setupCaption() {
label = UILabel(frame: CGRectMake(labelPadding, 0, self.bounds.size.width-labelPadding*2, self.bounds.size.height))
label.autoresizingMask = [.FlexibleWidth, .FlexibleHeight]
label.opaque = false
label.backgroundColor = UIColor.clearColor()
label.textAlignment = .Center
label.lineBreakMode = NSLineBreakMode.ByWordWrapping
label.numberOfLines = 3
label.textColor = UIColor.whiteColor()
label.shadowColor = UIColor(white: 0, alpha: 0.5)
label.shadowOffset = CGSizeMake(0, 1)
label.font = UIFont.systemFontOfSize(17)
label.text = ""
if let cap = photo?.caption() {
label.text = cap
}
addSubview(label)
}
/**
Override -sizeThatFits: and return a CGSize specifying the height of your
custom caption view. With width property is ignored and the caption is displayed
the full width of the screen
:param: size CGSize
:returns: CGSize
*/
public override func sizeThatFits(size: CGSize) -> CGSize {
if label.text == nil {
return CGSizeZero
}
if let b = label.text?.isEmpty {
if b {
return CGSizeZero
}
}
var maxHeight: CGFloat = 9999
if label.numberOfLines > 0 {
maxHeight = label.font.leading * CGFloat(label.numberOfLines)
}
let text = label.text!
let width = size.width - labelPadding*2
let font = label.font
let attributedText = NSAttributedString(string: text, attributes: [NSFontAttributeName: font])
let rect = attributedText.boundingRectWithSize(CGSizeMake(width, maxHeight), options: NSStringDrawingOptions.UsesLineFragmentOrigin, context: nil)
let textSize = rect.size
return CGSizeMake(size.width, textSize.height + labelPadding * 2)
}
}
extension SSCaptionView {
func setBackground() {
let fadeView = UIView(frame:CGRectMake(0, -100, UIScreen.mainScreen().bounds.width, 130+100)) // Static width, autoresizingMask is not working
fadeView.tag = 101
let gradient = CAGradientLayer()
gradient.frame = fadeView.bounds
gradient.colors = [UIColor(white: 0, alpha: 0).CGColor,UIColor(white: 0, alpha: 0.8).CGColor]
fadeView.layer.insertSublayer(gradient, atIndex: 0)
fadeView.autoresizingMask = [.FlexibleWidth, .FlexibleHeight]
addSubview(fadeView)
}
}
| mit | 2e318d0b5c12334a5439b9b1b7c3069c | 32.074627 | 164 | 0.611688 | 4.902655 | false | false | false | false |
Molbie/Outlaw-SpriteKit | Sources/OutlawSpriteKit/Nodes/Constraints/SKReachConstraints+Outlaw.swift | 1 | 3413 | //
// SKReachConstraints+Outlaw.swift
// OutlawSpriteKit
//
// Created by Brian Mullen on 12/16/16.
// Copyright © 2016 Molbie LLC. All rights reserved.
//
import SpriteKit
import Outlaw
import OutlawCoreGraphics
@available(OSX 10.10, *)
public extension SKReachConstraints {
struct ExtractableKeys {
public static let lowerAngleLimit = "lowerAngleLimit"
public static let upperAngleLimit = "upperAngleLimit"
}
struct ExtractableIndexes {
public static let lowerAngleLimit: Int = 0
public static let upperAngleLimit: Int = 1
}
private typealias keys = SKReachConstraints.ExtractableKeys
private typealias indexes = SKReachConstraints.ExtractableIndexes
}
@available(OSX 10.10, *)
extension SKReachConstraints: Value {
public static func value(from object: Any) throws -> SKReachConstraints {
if let data = object as? Extractable {
let lowerAngleLimit: CGFloat = try data.value(for: keys.lowerAngleLimit)
let upperAngleLimit: CGFloat = try data.value(for: keys.upperAngleLimit)
return SKReachConstraints(lowerAngleLimit: lowerAngleLimit, upperAngleLimit: upperAngleLimit)
}
else if let data = object as? IndexExtractable {
let lowerAngleLimit: CGFloat = try data.value(for: indexes.lowerAngleLimit)
let upperAngleLimit: CGFloat = try data.value(for: indexes.upperAngleLimit)
return SKReachConstraints(lowerAngleLimit: lowerAngleLimit, upperAngleLimit: upperAngleLimit)
}
else {
let expectedType = "Extractable or IndexExtractable"
throw OutlawError.typeMismatch(expected: expectedType, actual: type(of: object))
}
}
}
@available(OSX 10.10, *)
extension SKReachConstraints: Serializable {
public func serialized() -> [String: CGFloat] {
var result = [String: CGFloat]()
result[keys.lowerAngleLimit] = self.lowerAngleLimit
result[keys.upperAngleLimit] = self.upperAngleLimit
return result
}
}
// NOTE: unable to conform due to duplicate obj-c selector
@available(OSX 10.10, *)
public extension SKReachConstraints /* IndexSerializable */ {
static func serialize(_ constraint: SKReachConstraints) -> [CGFloat] {
var result = [CGFloat](repeating: 0, count: 2)
result[indexes.lowerAngleLimit] = constraint.lowerAngleLimit
result[indexes.upperAngleLimit] = constraint.upperAngleLimit
return result
}
}
@available(OSX 10.10, *)
extension SKReachConstraints: Updatable {
public func update(with object: Extractable) throws {
if let lowerAngleLimit: CGFloat = object.optional(for: keys.lowerAngleLimit) {
self.lowerAngleLimit = lowerAngleLimit
}
if let upperAngleLimit: CGFloat = object.optional(for: keys.upperAngleLimit) {
self.upperAngleLimit = upperAngleLimit
}
}
}
@available(OSX 10.10, *)
extension SKReachConstraints: IndexUpdatable {
public func update(with object: IndexExtractable) throws {
if let lowerAngleLimit: CGFloat = object.optional(for: indexes.lowerAngleLimit) {
self.lowerAngleLimit = lowerAngleLimit
}
if let upperAngleLimit: CGFloat = object.optional(for: indexes.upperAngleLimit) {
self.upperAngleLimit = upperAngleLimit
}
}
}
| mit | 89a71e26f66c28587a12cf7a7a452c0b | 34.915789 | 105 | 0.685815 | 5.130827 | false | false | false | false |
Sharelink/Bahamut | Bahamut/BahamutUIKit/ColorUtil.swift | 1 | 2363 | //
// Common.swift
// Bahamut
//
// Created by AlexChow on 15/9/16.
// Copyright © 2015年 GStudio. All rights reserved.
//
import Foundation
import UIKit
struct ColorSets
{
static let textColors:[UIColor] =
[
UIColor.red,
UIColor.orange,
UIColor.green,
UIColor.cyan,
UIColor.blue,
UIColor.purple,
UIColor.black,
themeColor
]
static let headerColor = UIColor(red: 0.92, green: 0.92, blue: 0.92, alpha: 1)
static let footerColor = UIColor(red: 0.92, green: 0.92, blue: 0.92, alpha: 1)
static var themeColor = UIColor(hexString: "#438ccb")
static var navBarBcgColor = UIColor(hexString: "#438ccb")
static var navBarTintColor = UIColor.white
static var navBarTitleColor = UIColor.white
}
extension UIColor{
var hexValue:Int{
return Int(toHex())
}
}
extension UIColor
{
static var headerColor:UIColor{
return ColorSets.headerColor
}
static var footerColor:UIColor{
return ColorSets.footerColor
}
static var themeColor:UIColor{
return ColorSets.themeColor
}
static var navBarBcgColor:UIColor{
return ColorSets.navBarBcgColor
}
static var navBarTintColor:UIColor{
return ColorSets.navBarTintColor
}
static var navBarTitleColor:UIColor{
return ColorSets.navBarTitleColor
}
static func getRondomColorIn(_ colors:[UIColor]) -> UIColor
{
let index = Int(arc4random_uniform(UInt32(colors.count)))
return colors[index]
}
static func getRandomTextColor() -> UIColor
{
return getRondomColorIn(ColorSets.textColors)
}
static func getRandomColor() -> UIColor
{
return UIColor(hex: arc4random())
}
}
extension UIColor{
static var sky:UIColor{
return UIColor(hexString: "#66CCFF")
}
static var ice:UIColor{
return UIColor(hexString: "#66FFFF")
}
static var turquoise:UIColor{
return UIColor(hexString: "#00FFFF")
}
static var seaFoam:UIColor{
return UIColor(hexString: "#00FF80")
}
static var lime:UIColor{
return UIColor(hexString: "#80FF00")
}
static var banana:UIColor{
return UIColor(hexString: "#FFFF66")
}
}
| mit | 1da7ffb549e28a7136981612e24cb017 | 20.454545 | 82 | 0.618644 | 4.244604 | false | false | false | false |
hyharryhuang/YoureSuchA | YoureSuchAKeyboard/BottomBar.swift | 1 | 3043 | //
// BottomBar.swift
// Youre such A
//
// Created by Harry Huang on 11/12/2014.
// Copyright (c) 2014 HHH. All rights reserved.
//
import Foundation
import UIKit
protocol BottomBarDelegate : class
{
func switchKeyboardPressed()
func backspaceDown()
func backspaceUp()
func toggleNumberView()
}
class BottomBar : UIView
{
let numberOfButtons = 3
let buttonBaseTag:Int = 100
weak var delegate:BottomBarDelegate?
let titles:[String] = ["Switch", "123", "Backspace"]
override init(frame: CGRect) {
super.init(frame: frame)
}
func setUpButtons()
{
for index in 0...(numberOfButtons-1)
{
var button:UIButton = UIButton()
if(index == numberOfButtons - 1)
{
let cancelEvents: UIControlEvents = UIControlEvents.TouchUpInside|UIControlEvents.TouchUpInside|UIControlEvents.TouchDragExit|UIControlEvents.TouchUpOutside|UIControlEvents.TouchCancel|UIControlEvents.TouchDragOutside
button.addTarget(self.delegate?, action: "backspaceDown", forControlEvents: .TouchDown)
button.addTarget(self.delegate?, action: "backspaceUp", forControlEvents: cancelEvents)
} else
{
button.addTarget(self, action:"buttonTapped:" , forControlEvents: UIControlEvents.TouchUpInside)
}
button.tag = buttonBaseTag + index
button.setTitle(self.titles[index], forState: UIControlState.Normal)
button.titleLabel?.textAlignment = NSTextAlignment.Center
self.addSubview(button)
}
}
func setUpButtonFrames()
{
var buttonHeight:CGFloat = self.frame.size.height
var buttonWidth:CGFloat = self.frame.size.width / CGFloat(numberOfButtons)
for index in 0...(numberOfButtons-1)
{
var buttonTag = index + buttonBaseTag
var button = self.viewWithTag(buttonTag) as? UIButton
button?.frame = CGRect(x: buttonWidth * CGFloat(index) , y: 0, width: buttonWidth, height: buttonHeight)
}
}
func buttonTapped(sender:UIButton)
{
var actualButtonTag = sender.tag - buttonBaseTag
switch actualButtonTag {
case 0:
self.delegate?.switchKeyboardPressed()
case 1:
self.delegate?.toggleNumberView()
flipNumberButtonTitle()
default:
break
}
}
func flipNumberButtonTitle()
{
var button = self.viewWithTag(buttonBaseTag + 1) as? UIButton
if(button?.titleLabel?.text == "123")
{
button?.setTitle("YSA", forState: UIControlState.Normal)
} else
{
button?.setTitle("123", forState: UIControlState.Normal)
}
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
} | mit | bb0e1323bb46be931d8a2f6882521ec2 | 28.269231 | 233 | 0.598423 | 5.088629 | false | false | false | false |
cuzv/ExtensionKit | Sources/Extension/UIBarButtonItem+Extension.swift | 1 | 3641 | //
// UIBarButtonItem+Extension.swift
// Copyright (c) 2015-2016 Red Rain (http://mochxiao.com).
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import UIKit
// MARK: - AssociationKey
private struct AssociationKey {
fileprivate static var barButtonItemActionHandlerWrapper: String = "com.mochxiao.uibarbuttonitem.barButtonItemActionHandlerWrapper"
}
// MARK: -
public extension UIBarButtonItem {
public class func make(fixedSpace width: CGFloat) -> UIBarButtonItem {
let spacing = UIBarButtonItem(barButtonSystemItem: .fixedSpace, target: nil, action: nil)
spacing.width = width
return spacing
}
}
// MARK: -
public extension UIBarButtonItem {
fileprivate var barButtonItemActionHandlerWrapper: ClosureDecorator<UIBarButtonItem>? {
get { return associatedObject(forKey: &AssociationKey.barButtonItemActionHandlerWrapper) as? ClosureDecorator<UIBarButtonItem> }
set { associate(retainObject: newValue, forKey: &AssociationKey.barButtonItemActionHandlerWrapper) }
}
public class func make(title: String, actionHandler: ((UIBarButtonItem) -> ())?) -> UIBarButtonItem {
let barButtonItem = UIBarButtonItem(title: title, style: .plain, target: self, action: #selector(UIBarButtonItem.performActionHandler(sender:)))
if let actionHandler = actionHandler {
barButtonItem.barButtonItemActionHandlerWrapper = ClosureDecorator(actionHandler)
}
return barButtonItem
}
public class func make(image: UIImage?, actionHandler: ((UIBarButtonItem) -> ())?) -> UIBarButtonItem {
let barButtonItem = UIBarButtonItem(image: image?.original, style: .plain, target: self, action: #selector(UIBarButtonItem.performActionHandler(sender:)))
if let actionHandler = actionHandler {
barButtonItem.barButtonItemActionHandlerWrapper = ClosureDecorator(actionHandler)
}
return barButtonItem
}
public class func make(systemItem item: UIBarButtonSystemItem, actionHandler: ((UIBarButtonItem) -> ())?) -> UIBarButtonItem {
let barButtonItem = UIBarButtonItem(barButtonSystemItem: item, target: self, action: #selector(UIBarButtonItem.performActionHandler(sender:)))
if let actionHandler = actionHandler {
barButtonItem.barButtonItemActionHandlerWrapper = ClosureDecorator(actionHandler)
}
return barButtonItem
}
/// Helper func
@objc internal class func performActionHandler(sender: UIBarButtonItem) {
sender.barButtonItemActionHandlerWrapper?.invoke(sender)
}
}
| mit | 8fb030c8c295e6f5c03755c6d4e9a6f0 | 45.679487 | 162 | 0.733315 | 5.261561 | false | false | false | false |
NextFaze/FazeKit | Sources/FazeKit/Classes/NSAttributedStringAdditions.swift | 2 | 2461 | //
// NSAttributedStringAdditions.swift
// FazeKit
//
// Created by Shane Woolcock on 10/10/19.
//
import Foundation
public extension NSAttributedString {
func height(withConstrainedWidth width: CGFloat) -> CGFloat {
let constraintRect = CGSize(width: width, height: .greatestFiniteMagnitude)
let boundingBox = boundingRect(with: constraintRect, options: .usesLineFragmentOrigin, context: nil)
return ceil(boundingBox.height)
}
func width(withConstrainedHeight height: CGFloat) -> CGFloat {
let constraintRect = CGSize(width: .greatestFiniteMagnitude, height: height)
let boundingBox = boundingRect(with: constraintRect, options: .usesLineFragmentOrigin, context: nil)
return ceil(boundingBox.width)
}
// https://medium.com/@rwbutler/trimming-nsattributedstring-b8c1e58ac0a
func trimmingCharacters(in characterSet: CharacterSet) -> NSAttributedString {
guard let result = self.mutableCopy() as? NSMutableAttributedString else { fatalError() }
while let range = result.string.rangeOfCharacter(from: characterSet), range.lowerBound == result.string.startIndex {
let length = result.string.distance(from: range.lowerBound, to: range.upperBound)
result.deleteCharacters(in: NSRange(location: 0, length: length))
}
while let range = result.string.rangeOfCharacter(from: characterSet, options: .backwards), range.upperBound == result.string.endIndex {
let location = result.string.distance(from: result.string.startIndex, to: range.lowerBound)
let length = result.string.distance(from: range.lowerBound, to: range.upperBound)
result.deleteCharacters(in: NSRange(location: location, length: length))
}
return result
}
}
public extension Array where Element: NSAttributedString {
func joined(separator: String = ",") -> NSAttributedString {
return self.joined(attributedSeparator: NSAttributedString(string: separator))
}
func joined(attributedSeparator: NSAttributedString) -> NSAttributedString {
guard !self.isEmpty else { return NSAttributedString() }
let attr = NSMutableAttributedString()
for (offset, element) in self.enumerated() {
if offset > 0 {
attr.append(attributedSeparator)
}
attr.append(element)
}
return attr
}
}
| apache-2.0 | 14940365dd0f087192a7c1214d678f3f | 42.175439 | 143 | 0.684275 | 4.961694 | false | false | false | false |
debugsquad/Hyperborea | Hyperborea/Model/Search/MSearchContentModeItemDefinition.swift | 1 | 1330 | import UIKit
class MSearchContentModeItemDefinition:MSearchContentModeItem
{
private let kCellAddedHeight:CGFloat = 40
init()
{
let title:String = NSLocalizedString("MSearchContentModeItemDefinition_title", comment:"")
let symbol:String = NSLocalizedString("MSearchContentModeItemDefinition_symbol", comment:"")
let reusableIdentifier:String = VSearchContentCellDefinition.reusableIdentifier
super.init(
title:title,
symbol:symbol,
reusableIdentifier:reusableIdentifier)
}
override func selected(controller:CSearch)
{
if let modelEntry:MSearchEntry = controller.modelEntry
{
controller.showContent(modelEntry:modelEntry)
}
}
override func usingString(controller:CSearch) -> NSAttributedString?
{
let attributedString:NSAttributedString? = controller.modelEntry?.attributedString
return attributedString
}
override func contentHeight(controller:CSearch) -> CGFloat
{
let textHeight:CGFloat = heightForString(controller:controller)
var cellHeight:CGFloat = textHeight
if textHeight > 0
{
cellHeight += kCellAddedHeight
}
return cellHeight
}
}
| mit | 4360daf0fe2d54495b8496097d5da319 | 27.913043 | 100 | 0.652632 | 5.757576 | false | false | false | false |
proversity-org/edx-app-ios | Source/OEXAnalytics+Swift.swift | 1 | 9234 | //
// OEXAnalytics+Swift.swift
// edX
//
// Created by Akiva Leffert on 9/15/15.
// Copyright (c) 2015-2016 edX. All rights reserved.
//
import Foundation
//New anayltics events go here:
public enum AnalyticsCategory : String {
case Conversion = "conversion"
case Discovery = "discovery"
case AppReviews = "app-reviews"
case WhatsNew = "whats-new"
case SocialSharing = "social-sharing"
}
public enum AnalyticsDisplayName : String {
case DiscoverCourses = "Discover Courses"
case ExploreCourses = "Explore Courses"
case UserLogin = "User Login"
case CreateAccount = "Create Account Clicked"
case RegistrationSuccess = "Registration Success"
case EnrolledCourseClicked = "Course Enroll Clicked"
case EnrolledCourseSuccess = "Course Enroll Success"
case BulkDownloadToggleOn = "Bulk Download Toggle On"
case BulkDownloadToggleOff = "Bulk Download Toggle Off"
case SharedCourse = "Shared a course"
case SubjectsDiscovery = "Subject Discovery"
case CourseSearch = "Discovery: Courses Search"
}
public enum AnalyticsEventName: String {
case CourseEnrollmentClicked = "edx.bi.app.course.enroll.clicked"
case CourseEnrollmentSuccess = "edx.bi.app.course.enroll.success"
case DiscoverCourses = "edx.bi.app.discover.courses.tapped"
case ExploreSubjects = "edx.bi.app.discover.explore.tapped"
case UserLogin = "edx.bi.app.user.login"
case UserRegistrationClick = "edx.bi.app.user.register.clicked"
case UserRegistrationSuccess = "edx.bi.app.user.register.success"
case ViewRating = "edx.bi.app.app_reviews.view_rating"
case DismissRating = "edx.bi.app.app_reviews.dismiss_rating"
case SubmitRating = "edx.bi.app.app_reviews.submit_rating"
case SendFeedback = "edx.bi.app.app_reviews.send_feedback"
case MaybeLater = "edx.bi.app.app_reviews.maybe_later"
case RateTheApp = "edx.bi.app.app_reviews.rate_the_app"
case WhatsNewClose = "edx.bi.app.whats_new.close"
case WhatsNewDone = "edx.bi.app.whats_new.done"
case VideosSubsectionDelete = "edx.bi.app.video.delete.subsection"
case VideosUnitDelete = "edx.bi.app.video.delete.unit"
case BulkDownloadToggleOn = "edx.bi.app.videos.download.toggle.on"
case BulkDownloadToggleOff = "edx.bi.app.videos.download.toggle.off"
case SharedCourse = "edx.bi.app.course.shared"
case SubjectClicked = "edx.bi.app.discover.subject.clicked"
case CourseSearch = "edx.bi.app.discovery.courses_search"
}
public enum AnalyticsScreenName: String {
case AppReviews = "AppReviews: View Rating"
case CourseDates = "Course Dates"
case WhatsNew = "WhatsNew: Whats New"
case ViewTopicThreads = "Forum: View Topic Threads"
case CreateTopicThread = "Forum: Create Topic Thread"
case ViewThread = "Forum: View Thread"
case AddThreadResponse = "Forum: Add Thread Response"
case AddResponseComment = "Forum: Add Response Comment"
case ViewResponseComments = "Forum: View Response Comments"
case CourseVideos = "Videos: Course Videos"
case SubjectsDiscovery = "Discover: All Subjects"
case DiscoverProgram = "Find Programs"
case DiscoverDegree = "Find Degrees"
case ProgramInfo = "Program Info"
}
public enum AnalyticsEventDataKey: String {
case ThreadID = "thread_id"
case TopicID = "topic_id"
case ResponseID = "response_id"
case Author = "author"
case SubsectionID = "subsection_id"
case UnitID = "unit_id"
case totalDownloadableVideos = "total_downloadable_videos"
case remainingDownloadableVideos = "remaining_downloadable_videos"
case UserID = "user_id"
case SubjectID = "subject_id"
}
extension OEXAnalytics {
static func discoverCoursesEvent() -> OEXAnalyticsEvent {
let event = OEXAnalyticsEvent()
event.category = AnalyticsCategory.Discovery.rawValue
event.name = AnalyticsEventName.DiscoverCourses.rawValue
event.displayName = AnalyticsDisplayName.DiscoverCourses.rawValue
return event
}
static func exploreSubjectsEvent() -> OEXAnalyticsEvent {
let event = OEXAnalyticsEvent()
event.category = AnalyticsCategory.Discovery.rawValue
event.name = AnalyticsEventName.ExploreSubjects.rawValue
event.displayName = AnalyticsDisplayName.ExploreCourses.rawValue
return event
}
@objc static func loginEvent() -> OEXAnalyticsEvent {
let event = OEXAnalyticsEvent()
event.name = AnalyticsEventName.UserLogin.rawValue
event.displayName = AnalyticsDisplayName.UserLogin.rawValue
return event
}
@objc static func registerEvent(name: String, displayName: String) -> OEXAnalyticsEvent {
let event = OEXAnalyticsEvent()
event.name = name
event.displayName = displayName
event.category = AnalyticsCategory.Conversion.rawValue
event.label = "iOS v\(Bundle.main.oex_shortVersionString())"
return event
}
func trackCourseEnrollment(courseId: String, name: String, displayName: String) {
let event = OEXAnalyticsEvent()
event.name = name
event.displayName = displayName
event.category = AnalyticsCategory.Conversion.rawValue
event.label = courseId
trackEvent(event, forComponent: nil, withInfo: [:])
}
func trackDiscussionScreen(
withName: AnalyticsScreenName,
courseId: String,
value: String?,
threadId: String?,
topicId: String?,
responseID: String?,
author: String? = String?.none) {
var info: [String:String] = [:]
info.setObjectOrNil(threadId, forKey: AnalyticsEventDataKey.ThreadID.rawValue)
info.setObjectOrNil(topicId, forKey: AnalyticsEventDataKey.TopicID.rawValue)
info.setObjectOrNil(responseID, forKey: AnalyticsEventDataKey.ResponseID.rawValue)
info.setObjectOrNil(author, forKey: AnalyticsEventDataKey.Author.rawValue)
self.trackScreen(withName: withName.rawValue, courseID: courseId, value: value, additionalInfo: info)
}
func trackSubsectionDeleteVideos(courseID: String, subsectionID: String){
let event = OEXAnalyticsEvent()
event.courseID = courseID
event.name = AnalyticsEventName.VideosSubsectionDelete.rawValue
event.displayName = "Videos: Subsection Delete"
trackEvent(event, forComponent: nil, withInfo: [AnalyticsEventDataKey.SubsectionID.rawValue : subsectionID])
}
func trackBulkDownloadToggle(isOn: Bool, courseID: String, totalVideosCount: Int, remainingVideosCount: Int, blockID: CourseBlockID?) {
let event = OEXAnalyticsEvent()
event.courseID = courseID
event.name = isOn ? AnalyticsEventName.BulkDownloadToggleOn.rawValue : AnalyticsEventName.BulkDownloadToggleOff.rawValue
event.displayName = isOn ? AnalyticsDisplayName.BulkDownloadToggleOn.rawValue : AnalyticsDisplayName.BulkDownloadToggleOff.rawValue
var info: [String:String] = [ key_course_id : courseID, AnalyticsEventDataKey.totalDownloadableVideos.rawValue : "\(totalVideosCount)", key_component:"downloadmodule" ]
if isOn {
info[AnalyticsEventDataKey.remainingDownloadableVideos.rawValue] = "\(remainingVideosCount)"
}
if let blockID = blockID {
info[OEXAnalyticsKeyBlockID] = "\(blockID)"
}
trackEvent(event, forComponent: nil, withInfo: info)
}
func trackUnitDeleteVideo(courseID: String, unitID: String) {
let event = OEXAnalyticsEvent()
event.courseID = courseID
event.name = AnalyticsEventName.VideosUnitDelete.rawValue
event.displayName = "Videos: Unit Delete"
trackEvent(event, forComponent: nil, withInfo: [AnalyticsEventDataKey.UnitID.rawValue : unitID])
}
func trackCourseShared(courseID: String, url: String, type: String) {
let event = OEXAnalyticsEvent()
event.courseID = courseID;
event.name = AnalyticsEventName.SharedCourse.rawValue
event.displayName = AnalyticsDisplayName.SharedCourse.rawValue
event.category = AnalyticsCategory.SocialSharing.rawValue
trackEvent(event, forComponent: nil, withInfo: ["url": url, "type": type])
}
func trackSubjectDiscovery(subjectID: String) {
let event = OEXAnalyticsEvent()
event.name = AnalyticsEventName.SubjectClicked.rawValue
event.displayName = AnalyticsDisplayName.SubjectsDiscovery.rawValue
event.category = AnalyticsCategory.Discovery.rawValue
trackEvent(event, forComponent: nil, withInfo: [ AnalyticsEventDataKey.SubjectID.rawValue : subjectID ])
}
func trackCourseSearch(search query: String, action: String) {
let event = OEXAnalyticsEvent()
event.name = AnalyticsEventName.CourseSearch.rawValue
event.displayName = AnalyticsDisplayName.CourseSearch.rawValue
event.category = AnalyticsCategory.Discovery.rawValue
event.label = query
trackEvent(event, forComponent: nil, withInfo: ["action": action, "app_version": Bundle.main.oex_buildVersionString()])
}
}
| apache-2.0 | b03611e415854935d46e4ccdaee99598 | 41.75 | 176 | 0.705328 | 4.623936 | false | false | false | false |
aucd29/ios-study | ncia/day02_05_photoSlider/PhotoSlider.swift | 1 | 1706 | //
// PhotoSlider.swift
// day02_05_photoSlider
//
// Created by 최철동 on 2016. 8. 18..
// Copyright © 2016년 Burke Choi. All rights reserved.
//
import UIKit
class PhotoSlider: UIView {
let scroll = UIScrollView();
// var names: NSArray? = nil;
let margin: CGFloat = 5;
override init(frame: CGRect) {
super.init(frame: frame);
// scroll.frame = self.bounds;
scroll.frame = CGRectMake(margin * -1, 0, frame.size.width + margin, frame.size.height);
scroll.pagingEnabled = true // 페이지 처리
// scroll.backgroundColor = UIColor.blackColor();
scroll.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 1)
self.addSubview(scroll);
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// func setImageNames(names: [String]) 으로 도 사용 가능
func setImageNames(names: NSArray) {
// self.names? = names;
let cx = scroll.bounds.size.width;
scroll.contentSize = CGSizeMake(cx * CGFloat(names.count), scroll.bounds.size.height);
var frame = self.bounds;
frame.origin.x = margin;
for name in names {
// let iv = UIImageView(frame: frame);
// iv.contentMode = .ScaleAspectFit;
// iv.image = UIImage(named: name as! String);
let iv = ScaleView(frame: frame);
iv.setImage(UIImage(named: name as! String)!);
scroll.addSubview(iv);
// frame.origin.x += frame.size.width;
frame.origin.x += cx;
}
}
}
//
| apache-2.0 | 5fcaf84798a33a4224605c942383ced7 | 27.355932 | 96 | 0.561865 | 3.936471 | false | false | false | false |
algolia/algoliasearch-client-swift | Sources/AlgoliaSearchClient/Helpers/Coding/Wrappers/CustomKey.swift | 1 | 1051 | //
// CustomKey.swift
//
//
// Created by Vladislav Fitc on 13/04/2020.
//
import Foundation
@propertyWrapper
public struct CustomKey<Key: Hashable & RawRepresentable, Value: Codable>: Codable where Key.RawValue == String {
public var wrappedValue: [Key: Value]
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: DynamicKey.self)
var storage: [Key: Value] = [:]
for rawKey in container.allKeys {
guard let key = Key(rawValue: rawKey.stringValue) else { throw DecodingError.dataCorruptedError(forKey: rawKey, in: container, debugDescription: "Cannot create \(Value.self) value") }
let value = try container.decode(Value.self, forKey: rawKey)
storage[key] = value
}
self.wrappedValue = storage
}
public func encode(to encoder: Encoder) throws {
let rawWrappedSequence = wrappedValue.map { ($0.key.rawValue, $0.value) }
let rawWrappedValue = [String: Value](uniqueKeysWithValues: rawWrappedSequence)
try rawWrappedValue.encode(to: encoder)
}
}
| mit | d8e102fcfe69c0f355c5a269a2885fc8 | 31.84375 | 189 | 0.710752 | 4.042308 | false | false | false | false |
denis631/Bankathon-Vienna- | frontend/cashSlicer/cashSlicer/Transactions/TransactionsViewController.swift | 1 | 1075 | //
// TransactionsViewController.swift
// cashSlicer
//
// Created by Denis Grebennicov on 31.05.17.
// Copyright © 2017 ca$hSlicer. All rights reserved.
//
import UIKit
import RxSwift
import RxCocoa
import RxDataSources
class TransactionsViewController: UIViewController {
@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var dismissButton: UIButton!
let viewModel = TransactionsViewModel()
let disposeBag = DisposeBag()
override func viewDidLoad() {
super.viewDidLoad()
dismissButton.rx.tap.subscribe(onNext: {
self.dismiss(animated: true)
}).disposed(by: disposeBag)
viewModel.transactions.bind(to: tableView.rx.items(cellIdentifier: "Cell")) { (index, item: Transaction, cell) in
if let transactionCell = cell as? TransactionCell {
transactionCell.costLabel?.text = "\(String(describing: item.cost)) €"
transactionCell.detailLabel?.text = item.detailInfo
}
}.disposed(by: disposeBag)
}
}
| mit | dcebb070cd73148f459ddcf5940998df | 28.777778 | 121 | 0.654851 | 4.62069 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.