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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
mooneywang/MJCompatible | MJCompatible/QRCodeScanViewController.swift | 1 | 7909 | //
// QRCodeScanViewController.swift
// MJCompatible
//
// Created by Panda on 2017/10/16.
// Copyright © 2017年 MooneyWang. All rights reserved.
//
import UIKit
import AVFoundation
class QRCodeScanViewController: UIViewController {}
// var torchButton: UIButton?
//
// let detectorFrame = CGRect(x: (UIScreen.main.bounds.width - 160) * 0.5,
// y: (UIScreen.main.bounds.height - 160) * 0.5,
// width: 160, height: 160)
//// let captureDevice = AVCaptureDevice.default(for: AVMediaType(rawValue: convertFromAVMediaType(AVMediaType.video)))
// let metaDataOutput = AVCaptureMetadataOutput()
// let captureSession = AVCaptureSession()
// private let queue: DispatchQueue = DispatchQueue(label: "moody.capture-queue")
// let lineImageView = UIImageView(image: UIImage(named: "CodeScan.bundle/qrcode_scan_light_green"))
// var isAnimationing = false
//
// override func viewDidLoad() {
// super.viewDidLoad()
//
// // 设置捕捉会话
// configSession()
//
// // 视频捕捉图层
// let capturelayer = AVCaptureVideoPreviewLayer(session: captureSession)
// capturelayer.frame = self.view.bounds
// self.view.layer.addSublayer(capturelayer)
//
// // 二维码检测区域图层
// let detectImageView = UIImageView(image: UIImage(named: "CodeScan.bundle/qrcode_scan_full_net"))
// detectImageView.frame = detectorFrame
// self.view.addSubview(detectImageView)
//
// let detectRectLayer = CAShapeLayer()
// detectRectLayer.frame = detectorFrame
// detectRectLayer.borderColor = UIColor.green.cgColor
// detectRectLayer.borderWidth = 1
// self.view.layer.addSublayer(detectRectLayer)
//
// // 设置界面操作按钮
// setButtons()
// self.view.addSubview(lineImageView)
//
// // 开始捕捉
// queue.async {
// self.captureSession.startRunning()
//
// // 转换捕捉区域坐标(必须在startRunning()之后)
// let interestRect = capturelayer.metadataOutputRectConverted(fromLayerRect: self.detectorFrame)
// self.metaDataOutput.rectOfInterest = interestRect
// }
//
// self.isAnimationing = true
// self.startScanAnimation()
// }
//
// override func viewWillAppear(_ animated: Bool) {
// super.viewWillAppear(animated)
// self.navigationController?.navigationBar.isHidden = true
// }
//
// override func viewWillDisappear(_ animated: Bool) {
// super.viewWillDisappear(animated)
// self.navigationController?.navigationBar.isHidden = false
// }
//
//// private func configSession() {
//// captureSession.sessionPreset = AVCaptureSession.Preset(rawValue: convertFromAVCaptureSessionPreset(AVCaptureSession.Preset.high))
//// let input = try! AVCaptureDeviceInput(device: captureDevice)
//// captureSession.addInput(input)
//// captureSession.addOutput(metaDataOutput)
//// metaDataOutput.setMetadataObjectsDelegate(self, queue: DispatchQueue.main)
////
//// // 设置捕捉信息类型为二维码(必须在addOutput之后)
//// metaDataOutput.metadataObjectTypes = [convertFromAVMetadataObjectObjectType(AVMetadataObject.ObjectType.qr)]
//// }
//
// private func setButtons() {
// let buttonW: CGFloat = 30
// let buttonH = buttonW
// let backButtonRect = CGRect(x: 20, y: 20, width: buttonW, height: buttonH)
// let torchButtonRect = CGRect(x: (UIScreen.main.bounds.width - 65) * 0.5,
// y: UIScreen.main.bounds.height - 20 - 87,
// width: 65, height: 87)
//
// // 返回按钮
// let backButton = UIButton(frame: backButtonRect)
// backButton.setBackgroundImage(UIImage(named: "CodeScan.bundle/qrcode_scan_titlebar_back_nor"), for: .normal)
// backButton.addTarget(self, action: #selector(backButtonAction), for: UIControl.Event.touchUpInside)
// self.view.addSubview(backButton)
//
// // 闪光灯按钮
// torchButton = UIButton(frame: torchButtonRect)
// torchButton?.setBackgroundImage(UIImage(named: "CodeScan.bundle/qrcode_scan_btn_flash_nor"), for: .normal)
// torchButton?.setBackgroundImage(UIImage(named: "CodeScan.bundle/qrcode_scan_btn_scan_off"), for: .selected)
// torchButton?.addTarget(self, action: #selector(torchButtonAction), for: UIControl.Event.touchUpInside)
// if torchButton != nil {
// self.view.addSubview(torchButton!)
// }
// }
//
// @objc func backButtonAction() {
// guard let device = captureDevice else {
// return
// }
// if device.hasTorch {
// if device.isTorchActive {
// guard let _ = try? device.lockForConfiguration() else {
// return
// }
// device.torchMode = AVCaptureDevice.TorchMode.off
// device.unlockForConfiguration()
// torchButton?.isSelected = false
// }
// }
// self.navigationController?.popViewController(animated: true)
// }
//
// /**
// 闪光灯的打开/关闭
// */
// @objc func torchButtonAction() {
// guard let device = captureDevice else {
// return
// }
// if device.hasTorch {
// if device.isTorchActive {
// guard let _ = try? device.lockForConfiguration() else {
// return
// }
// device.torchMode = AVCaptureDevice.TorchMode.off
// device.unlockForConfiguration()
// torchButton?.isSelected = false
// } else {
// guard let _ = try? device.lockForConfiguration() else {
// return
// }
// device.torchMode = AVCaptureDevice.TorchMode.on
// device.unlockForConfiguration()
// torchButton?.isSelected = true
// }
// }
// }
//
// fileprivate func startScanAnimation() {
// stepAnimation()
// }
//
// fileprivate func stopScanAnimation() {
// isAnimationing = false
// }
//
// @objc func stepAnimation() {
// if !isAnimationing {
// return
// }
// var frame:CGRect = detectorFrame
// frame.size.height = 3
// lineImageView.frame = frame
// lineImageView.alpha = 1.0
// UIView.animate(withDuration: 2.0, animations: { () -> Void in
//
// self.lineImageView.alpha = 0.0
//
// frame.origin.y += self.detectorFrame.size.height
// self.lineImageView.frame = frame
//
// }, completion:{ (value: Bool) -> Void in
//
// self.perform(#selector(self.stepAnimation), with: nil, afterDelay: 0.3)
//
// })
// }
//}
//
//extension QRCodeScanViewController: AVCaptureMetadataOutputObString(describing: jectsDelegate {
//
// func metadataOutput(_ captureOutput: AVCaptureMetadataOutput, didOutput metadataObjects: [AVMetadataObject], from connection: AVCaptureConnection) {
// print("get QR: \(metadataObjects)")
// captureSession.stopRunning()
// stopScanAnimation()
// }
//}
//
//// Helper function inserted by Swift 4.2 migrator.
//fileprivate func convertFromAVMediaType(_ input: AVMediaType) -> String {
// return input.rawValue
//}
//
//// Helper function inserted by Swift 4.2 migrator.
//fileprivate func convertFromAVCaptureSessionPreset(_ input: AVCaptureSession.Preset) -> String {
// return input.rawValue
//}
//
//// Helper function inserted by Swift 4.2 migrator.
//fileprivate func convertFromAVMetadataObjectObjectType(_ input: AVMetadataObject.ObjectType) -> String {
// return input.rawValue
//}
| mit | 1e7636cd51f2b80f97232418615db151 | 36.592233 | 154 | 0.610666 | 4.179169 | false | false | false | false |
msdgwzhy6/SAHistoryNavigationViewController | SAHistoryNavigationViewControllerSample/SAHistoryNavigationViewControllerSample/CustomTransitioningController.swift | 1 | 8687 | //
// CustomTransitioningController.swift
// SAHistoryNavigationViewControllerSample
//
// Created by 鈴木 大貴 on 2015/08/05.
// Copyright (c) 2015年 鈴木大貴. All rights reserved.
//
import UIKit
class CustomTransitioningController: NSObject, UIViewControllerAnimatedTransitioning {
private(set) var navigationControllerOperation: UINavigationControllerOperation
private var currentTransitionContext: UIViewControllerContextTransitioning?
private var backgroundView: UIView?
private var alphaView: UIView?
private static let kDefaultScale: CGFloat = 0.8
private static let kDefaultDuration: NSTimeInterval = 0.3
required init(operation: UINavigationControllerOperation) {
navigationControllerOperation = operation
super.init()
}
func transitionDuration(transitionContext: UIViewControllerContextTransitioning) -> NSTimeInterval {
return CustomTransitioningController.kDefaultDuration
}
func animateTransition(transitionContext: UIViewControllerContextTransitioning) {
let toViewContoller = transitionContext.viewControllerForKey(UITransitionContextToViewControllerKey)
let fromViewContoller = transitionContext.viewControllerForKey(UITransitionContextFromViewControllerKey)
currentTransitionContext = transitionContext
let containerView = transitionContext.containerView()
if let fromView = fromViewContoller?.view, toView = toViewContoller?.view {
switch navigationControllerOperation {
case .Push:
pushAnimation(transitionContext, toView: toView, fromView: fromView, containerView: containerView)
case .Pop:
popAnimation(transitionContext, toView: toView, fromView: fromView, containerView: containerView)
case .None:
let cancelled = transitionContext.transitionWasCancelled()
transitionContext.completeTransition(!cancelled)
}
}
}
}
//MARK: - Internal Methods
extension CustomTransitioningController {
func forceFinish() {
let navigationControllerOperation = self.navigationControllerOperation
if let backgroundView = backgroundView, alphaView = alphaView {
let dispatchTime = dispatch_time(DISPATCH_TIME_NOW, Int64((CustomTransitioningController.kDefaultDuration + 0.1) * Double(NSEC_PER_SEC)))
dispatch_after(dispatchTime, dispatch_get_main_queue()) { [weak self] in
if let currentTransitionContext = self?.currentTransitionContext {
let toViewContoller = currentTransitionContext.viewControllerForKey(UITransitionContextToViewControllerKey)
let fromViewContoller = currentTransitionContext.viewControllerForKey(UITransitionContextFromViewControllerKey)
if let fromView = fromViewContoller?.view, toView = toViewContoller?.view {
switch navigationControllerOperation {
case .Push:
self?.pushAniamtionCompletion(currentTransitionContext, toView: toView, fromView: fromView, backgroundView: backgroundView, alphaView: alphaView)
case .Pop:
self?.popAniamtionCompletion(currentTransitionContext, toView: toView, fromView: fromView, backgroundView: backgroundView, alphaView: alphaView)
case .None:
let cancelled = currentTransitionContext.transitionWasCancelled()
currentTransitionContext.completeTransition(!cancelled)
}
self?.currentTransitionContext = nil
self?.backgroundView = nil
self?.alphaView = nil
}
}
}
}
}
}
//MARK: - Private Methods
extension CustomTransitioningController {
private func popAnimation(transitionContext: UIViewControllerContextTransitioning, toView: UIView, fromView: UIView, containerView: UIView) {
let backgroundView = UIView(frame: containerView.bounds)
backgroundView.backgroundColor = .blackColor()
containerView.addSubview(backgroundView)
self.backgroundView = backgroundView
toView.frame = containerView.bounds
containerView.addSubview(toView)
let alphaView = UIView(frame: containerView.bounds)
alphaView.backgroundColor = .blackColor()
containerView.addSubview(alphaView)
self.alphaView = alphaView
fromView.frame = containerView.bounds
containerView.addSubview(fromView)
let completion: (Bool) -> Void = { [weak self] finished in
if finished {
self?.popAniamtionCompletion(transitionContext, toView: toView, fromView: fromView, backgroundView: backgroundView, alphaView: alphaView)
}
}
let kDefaultScale = CustomTransitioningController.kDefaultScale
toView.transform = CGAffineTransformScale(CGAffineTransformIdentity, kDefaultScale, kDefaultScale)
alphaView.alpha = 0.7
UIView.animateWithDuration(transitionDuration(transitionContext), delay: 0.0, options: .CurveEaseOut, animations: {
toView.transform = CGAffineTransformIdentity
fromView.frame.origin.x = containerView.frame.size.width
alphaView.alpha = 0.0
}, completion: completion)
}
private func popAniamtionCompletion(transitionContext: UIViewControllerContextTransitioning, toView: UIView, fromView: UIView, backgroundView: UIView, alphaView: UIView) {
let cancelled = transitionContext.transitionWasCancelled()
if cancelled {
toView.transform = CGAffineTransformIdentity
toView.removeFromSuperview()
} else {
fromView.removeFromSuperview()
}
backgroundView.removeFromSuperview()
alphaView.removeFromSuperview()
transitionContext.completeTransition(!cancelled)
currentTransitionContext = nil
self.backgroundView = nil
self.alphaView = nil
}
private func pushAnimation(transitionContext: UIViewControllerContextTransitioning, toView: UIView, fromView: UIView, containerView: UIView) {
let backgroundView = UIView(frame: containerView.bounds)
backgroundView.backgroundColor = .blackColor()
containerView.addSubview(backgroundView)
self.backgroundView = backgroundView
fromView.frame = containerView.bounds
containerView.addSubview(fromView)
let alphaView = UIView(frame: containerView.bounds)
alphaView.backgroundColor = .blackColor()
alphaView.alpha = 0.0
containerView.addSubview(alphaView)
self.alphaView = alphaView
toView.frame = containerView.bounds
toView.frame.origin.x = containerView.frame.size.width
containerView.addSubview(toView)
let completion: (Bool) -> Void = { [weak self] finished in
if finished {
self?.pushAniamtionCompletion(transitionContext, toView: toView, fromView: fromView, backgroundView: backgroundView, alphaView: alphaView)
}
}
let kDefaultScale = CustomTransitioningController.kDefaultScale
UIView.animateWithDuration(transitionDuration(transitionContext), delay: 0.0, options: .CurveEaseOut, animations: {
fromView.transform = CGAffineTransformScale(CGAffineTransformIdentity, kDefaultScale, kDefaultScale)
toView.frame.origin.x = 0.0
alphaView.alpha = 0.7
}, completion: completion)
}
private func pushAniamtionCompletion(transitionContext: UIViewControllerContextTransitioning, toView: UIView, fromView: UIView, backgroundView: UIView, alphaView: UIView) {
let cancelled = transitionContext.transitionWasCancelled()
if cancelled {
toView.removeFromSuperview()
}
fromView.transform = CGAffineTransformIdentity
backgroundView.removeFromSuperview()
fromView.removeFromSuperview()
alphaView.removeFromSuperview()
transitionContext.completeTransition(!cancelled)
currentTransitionContext = nil
self.backgroundView = nil
self.alphaView = nil
}
}
| mit | 5464654b8f60c302137ec3812e6e1e9f | 43.270408 | 176 | 0.666475 | 6.264982 | false | false | false | false |
AngelLandoni/MVVM-R | MVVMR/Application/Settings/SettingsView.swift | 1 | 1864 | //
// SettingsView.swift
// MVVMR
//
// Created by Angel Landoni on 2/11/17.
// Copyright © 2017 Angel Landoni. All rights reserved.
//
import UIKit
class SettingsView: ALView {
private var controller: SettingsController = SettingsController()
private var tableViewAdapter: SettingsTableViewAdapter! = nil
// Components
private var settingsTableView: UITableView! = nil
override func viewDidLoad() {
super.viewDidLoad()
configureTableView()
}
func setRouter(router: SettingsRouter) {
controller.router = router
}
}
// MARK: - ALView virtual methods -
extension SettingsView {
override func configureObject() {
title = "Settings"
}
}
// MARK: - Private methods -
private extension SettingsView {
func configureTableView() {
settingsTableView = UITableView(frame: CGRectZero, style: .Grouped)
settingsTableView.translatesAutoresizingMaskIntoConstraints = false
settingsTableView.backgroundColor = TableViewTheme.Normal.backgroundColor
settingsTableView?.separatorColor = TableViewTheme.Normal.separator
settingsTableView.tableFooterView = UIView()
view.addSubview(settingsTableView)
// Setup constraints
NSLayoutConstraint.activateConstraints([
settingsTableView.leftAnchor.constraintEqualToAnchor(view.leftAnchor),
settingsTableView.rightAnchor.constraintEqualToAnchor(view.rightAnchor),
settingsTableView.topAnchor.constraintEqualToAnchor(view.topAnchor),
settingsTableView.bottomAnchor.constraintEqualToAnchor(view.bottomAnchor)
])
tableViewAdapter = SettingsTableViewAdapter(tableViewRef: settingsTableView)
// Reload all the sections.
settingsTableView.reloadData()
}
} | gpl-3.0 | ae1f3d4ab84b61388ed1efc1d6db99fa | 28.587302 | 85 | 0.694579 | 5.876972 | false | false | false | false |
noehou/myDouYuZB | DYZB/DYZB/Classes/Home/View/RecommendGameView.swift | 1 | 1859 | //
// RecommendGameView.swift
// DYZB
//
// Created by Tommaso on 2016/12/13.
// Copyright © 2016年 Tommaso. All rights reserved.
//
import UIKit
private let kGameCellID = "kGameCellID"
private let kEdgeInsetMargin : CGFloat = 10
class RecommendGameView: UIView {
//MARK:定义数据的属性
var groups : [BaseGameModel]? {
didSet {
//刷新表格
collectionView.reloadData()
}
}
//MARK:控件属性
@IBOutlet weak var collectionView: UICollectionView!
//MARK:-系统回调
override func awakeFromNib() {
super.awakeFromNib()
//设置该控件不随着父控件的拉伸而拉伸
autoresizingMask = UIViewAutoresizing()
//注册Cell
collectionView.register(UINib(nibName: "CollectionGameCell", bundle: nil), forCellWithReuseIdentifier: kGameCellID)
//给collectionView 添加内边距
collectionView.contentInset = UIEdgeInsets(top: 0, left: kEdgeInsetMargin, bottom: 0, right: kEdgeInsetMargin)
}
}
//MARK:-提供快速创建的类方法
extension RecommendGameView {
class func recommendGameView() -> RecommendGameView {
return Bundle.main.loadNibNamed("RecommendGameView", owner: nil, options: nil)?.first as! RecommendGameView
}
}
extension RecommendGameView : UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return groups?.count ?? 0
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: kGameCellID, for: indexPath) as! CollectionGameCell
cell.baseGame = groups![indexPath.item]
return cell
}
}
| mit | 9f0a572eb8140f725e73727386dcbea2 | 29.596491 | 126 | 0.685206 | 5.099415 | false | false | false | false |
haitran2011/Rocket.Chat.iOS | Rocket.Chat/Controllers/Chat/ChatDataController.swift | 1 | 4325 | //
// ChatDataController.swift
// Rocket.Chat
//
// Created by Rafael Kellermann Streit on 09/12/16.
// Copyright © 2016 Rocket.Chat. All rights reserved.
//
import Foundation
enum ChatDataType {
case daySeparator
case message
case sendingMessage
case loader
}
struct ChatData {
var identifier = String.random(10)
var type: ChatDataType = .message
var timestamp: Date
var indexPath: IndexPath!
// This is only used for messages
var message: Message?
// Initializers
init?(type: ChatDataType, timestamp: Date) {
self.type = type
self.timestamp = timestamp
}
}
final class ChatDataController {
var data: [ChatData] = []
func clear() -> [IndexPath] {
var indexPaths: [IndexPath] = []
for item in data {
indexPaths.append(item.indexPath)
}
data = []
return indexPaths
}
func itemAt(_ indexPath: IndexPath) -> ChatData? {
return data.filter { item in
return item.indexPath?.row == indexPath.row && item.indexPath?.section == indexPath.section
}.first
}
func indexPathOf(_ identifier: String) -> IndexPath? {
return data.filter { item in
return item.identifier == identifier
}.flatMap { item in
item.indexPath
}.first
}
// swiftlint:disable function_body_length cyclomatic_complexity
func insert(_ items: [ChatData]) -> [IndexPath] {
var indexPaths: [IndexPath] = []
var newItems: [ChatData] = []
var lastObj = data.last
var identifiers: [String] = items.map { $0.identifier }
func insertDaySeparator(from obj: ChatData) {
guard let calendar = NSCalendar(calendarIdentifier: .gregorian) else { return }
let date = obj.timestamp
let components = calendar.components([.day, .month, .year], from: date)
guard let newDate = calendar.date(from: components) else { return }
guard let separator = ChatData(type: .daySeparator, timestamp: newDate) else { return }
identifiers.append(separator.identifier)
newItems.append(separator)
}
for newObj in items {
if let lastObj = lastObj {
if lastObj.type == .message && (
lastObj.timestamp.day != newObj.timestamp.day ||
lastObj.timestamp.month != newObj.timestamp.month ||
lastObj.timestamp.year != newObj.timestamp.year) {
// Check if already contains some separator with this data
// swiftlint:disable for_where
var insert = true
for obj in data.filter({ $0.type == .daySeparator }) {
if lastObj.timestamp.day == obj.timestamp.day &&
lastObj.timestamp.month == obj.timestamp.month &&
lastObj.timestamp.year == obj.timestamp.year {
insert = false
}
}
if insert {
insertDaySeparator(from: newObj)
}
}
}
newItems.append(newObj)
lastObj = newObj
}
data.append(contentsOf: newItems)
data.sort(by: { $0.timestamp < $1.timestamp })
var normalizeds: [ChatData] = []
for (idx, item) in data.enumerated() {
var customItem = item
let indexPath = IndexPath(item: idx, section: 0)
customItem.indexPath = indexPath
normalizeds.append(customItem)
for identifier in identifiers {
// swiftlint: disable for_where
if identifier == item.identifier {
indexPaths.append(indexPath)
break
}
}
}
data = normalizeds
return indexPaths
}
func update(_ message: Message) -> Int {
for (index, _) in data.enumerated() {
var obj = data[index]
if obj.message?.identifier == message.identifier {
obj.message = message
return obj.indexPath.row
}
}
return -1
}
}
| mit | 33369a47440fce592ed1500595161197 | 29.237762 | 103 | 0.540703 | 4.858427 | false | false | false | false |
Samiabo/Weibo | Weibo/Weibo/Classes/Home/StatusViewModel.swift | 1 | 2127 | //
// StatusViewModel.swift
// Weibo
//
// Created by han xuelong on 2017/1/4.
// Copyright © 2017年 han xuelong. All rights reserved.
//
import UIKit
class StatusViewModel: NSObject {
var status: StatusModel?
var sourceText: String?
var createAtText: String?
var verifiedImage: UIImage?
var vipImage: UIImage?
var profileURL: NSURL?
var picURLs: [URL] = [URL]()
init(status: StatusModel) {
self.status = status
if let source = status.source, source != "" {
let startIndex = (source as NSString).range(of: ">").location + 1
let length = (source as NSString).range(of: "</").location - startIndex
sourceText = (source as NSString).substring(with: NSRange(location: startIndex, length: length))
}
if let create_at = status.created_at {
createAtText = NSDate.createDateStr(createAtStr: create_at)
}
let verified_type = status.user?.verified_type ?? -1
switch verified_type {
case 0:
verifiedImage = UIImage(named: "avatar_vip")
case 2, 3, 5:
verifiedImage = UIImage(named: "avatar_enterprise_vip")
case 220:
verifiedImage = UIImage(named: "avatar_grassroot")
default:
verifiedImage = nil
}
let mbrank = status.user?.mbrank ?? 0
if mbrank > 0 && mbrank <= 6 {
vipImage = UIImage(named: "common_icon_membership_level\(mbrank)")
}
let profileURLString = status.user?.profile_image_url ?? ""
profileURL = NSURL(string: profileURLString)
let picURLDicts = status.pic_urls!.count != 0 ? status.pic_urls : status.retweeted_status?.pic_urls
if let picURLDicts = picURLDicts {
for picURLDict in picURLDicts {
guard let picURLString = picURLDict["thumbnail_pic"] else {
continue
}
picURLs.append(URL(string: picURLString)!)
}
}
}
}
| mit | 7f76156956e2941ab21c1ee075c9e58c | 30.235294 | 108 | 0.558851 | 4.481013 | false | false | false | false |
lucasmedeirosleite/EasyMapping | Tests/EasyMappingTests/EKMappingBlocksTestCase.swift | 2 | 3047 | //
// EasyMapping
//
// Copyright (c) 2012-2017 Lucas Medeiros.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import XCTest
import EasyMapping
class EKMappingBlocksTestCase: XCTestCase {
func testBlockShouldConvertFromStringToURL() {
let string = "http://www.google.com"
let url = EKMappingBlocks.urlMappingBlock()("foo", string) as? URL
XCTAssertEqual(url?.absoluteString, string)
}
func testShouldReturnNilOnNonStringValue() {
let number = 6
let nilURL = EKMappingBlocks.urlMappingBlock()("foo", number)
XCTAssertNil(nilURL)
}
func testShouldReverseConvertURLToString() {
let url = URL(string: "http://www.google.com")
let string = EKMappingBlocks.urlReverseMappingBlock()(url) as? String
XCTAssertEqual(string, url?.absoluteString)
}
func testURLStringShouldBeNilIfURLIsNil() {
let url : URL? = nil
let string = EKMappingBlocks.urlReverseMappingBlock()(url)
XCTAssertNil(string)
}
func testCoreDataReverseMappingBlocks() {
ManagedCar.register(ManagedMappingProvider.carMapping())
ManagedPhone.register(ManagedMappingProvider.phoneMapping())
defer {
ManagedCar.register(nil)
ManagedPhone.register(nil)
}
let context = Storage.shared.context
let info = FixtureLoader.dictionary(fromFileNamed: "Person.json")
let mapping = ManagedMappingProvider.personWithReverseBlocksMapping()
let person = EKManagedObjectMapper.object(fromExternalRepresentation: info,
with: mapping,
in: context) as! ManagedPerson
let sut = EKSerializer.serializeObject(person, with: mapping, from: context)
XCTAssertEqual(person.gender, "husband")
XCTAssertEqual(sut["gender"] as? String, "male")
}
}
| mit | b8d0544c32476276d0ecdfeaacd74da3 | 37.56962 | 84 | 0.672137 | 4.828843 | false | true | false | false |
ZZZZZZZP/DouYuZB | DYZB/DYZB/Classes/Tools/Extension/UIView.swift | 1 | 1111 | //
// UIView.swift
// DYZB
//
// Created by 张鹏 on 16/10/1.
// Copyright © 2016年 张鹏. All rights reserved.
//
import UIKit
extension UIView{
var x: CGFloat{
get{
return frame.origin.x
}
set{
frame.origin.x = newValue
}
}
var y: CGFloat{
get{
return frame.origin.y
}
set{
frame.origin.y = newValue
}
}
var width: CGFloat{
get{
return frame.width
}
set{
frame.size.width = newValue
}
}
var height: CGFloat{
get{
return frame.height
}
set{
frame.size.height = newValue
}
}
var centerX: CGFloat{
get{
return center.x
}
set{
center.x = newValue
}
}
var centerY: CGFloat{
get{
return center.y
}
set{
center.y = newValue
}
}
}
| mit | cd00a91ec6fde0c8fea0cca8c3fe532f | 12.75 | 46 | 0.386364 | 4.545455 | false | false | false | false |
evgenyneu/walk-to-circle-ios | walk to circleTests/CongratsPhraseTests.swift | 1 | 3735 | import UIKit
import WalkToCircle
import XCTest
class CongratsPhraseTests: XCTestCase {
// oneRandomPhrase
// -----------------
func testGetRandom() {
walkCongratsPhrases[1] = ["Test one"]
walkCongratsPhrases[2] = ["Test two"]
walkCongratsPhrases[5] = ["Test five"]
walkCongratsPhrases[20] = ["Test Oh My Glob!"]
XCTAssertEqual("Test one", CongratsPhrase.oneRandomPhrase(1))
XCTAssertEqual("Test two", CongratsPhrase.oneRandomPhrase(2))
XCTAssertEqual("Test two", CongratsPhrase.oneRandomPhrase(3))
XCTAssertEqual("Test five", CongratsPhrase.oneRandomPhrase(5))
// Edge cases
XCTAssertEqual("Test Oh My Glob!", CongratsPhrase.oneRandomPhrase(1000))
XCTAssertEqual("Test one", CongratsPhrase.oneRandomPhrase(0))
}
func testGetRandom_returnsUnseenOne() {
walkCongratsPhrases[1] = ["a", "b", "c", "d"]
walkCongratsPhrasesSeenToday = ["a", "b", "d"]
XCTAssertEqual("c", CongratsPhrase.oneRandomPhrase(1))
}
func testGetRandom_remembersPhraseInTodaysList() {
walkCongratsPhrases[1] = ["Something to remember"]
walkCongratsPhrasesSeenToday = []
CongratsPhrase.oneRandomPhrase(1)
XCTAssertEqual(["Something to remember"], walkCongratsPhrasesSeenToday)
}
func testGetRandom_remembersPhraseOnlyOnce() {
walkCongratsPhrases[1] = ["Something to remember"]
walkCongratsPhrasesSeenToday = []
CongratsPhrase.oneRandomPhrase(1)
CongratsPhrase.oneRandomPhrase(1)
CongratsPhrase.oneRandomPhrase(1)
XCTAssertEqual(["Something to remember"], walkCongratsPhrasesSeenToday)
}
// oneRandomPhrase from array
// -----------------
func testPickRandomPhraseFomrArray() {
var result = CongratsPhrase.oneRandomPhrase(["a"])
XCTAssertEqual("a", result)
result = CongratsPhrase.oneRandomPhrase([])
XCTAssertEqual(walkCongratsNoPhraseFound, result)
}
// Get random phrases
// -----------------
func testGetPhrases() {
walkCongratsPhrases[1] = ["Test one"]
walkCongratsPhrases[2] = ["Test two"]
walkCongratsPhrases[5] = ["Test five"]
walkCongratsPhrases[8] = ["Test eight"]
walkCongratsPhrases[13] = ["Test 13"]
walkCongratsPhrases[20] = ["Test Oh My Glob!"]
var result = CongratsPhrase.getPhrases(1)
XCTAssertEqual(["Test one"], result)
result = CongratsPhrase.getPhrases(2)
XCTAssertEqual(["Test two"], result)
result = CongratsPhrase.getPhrases(3)
XCTAssertEqual(["Test two"], result)
result = CongratsPhrase.getPhrases(5)
XCTAssertEqual(["Test five"], result)
result = CongratsPhrase.getPhrases(12)
XCTAssertEqual(["Test eight"], result)
result = CongratsPhrase.getPhrases(21)
XCTAssertEqual(["Test Oh My Glob!"], result)
// Edge cases
result = CongratsPhrase.getPhrases(0)
XCTAssertEqual(["Test one"], result)
result = CongratsPhrase.getPhrases(123123)
XCTAssertEqual(["Test Oh My Glob!"], result)
result = CongratsPhrase.getPhrases(-123123)
XCTAssertEqual(["Test one"], result)
}
// Unseen phrases
// -----------------
func testUnseenPhrasesToday() {
let result = CongratsPhrase.unseenPhrasesToday(["a", "b", "c"], alreadySeenToday: ["a"])
XCTAssertEqual(["b", "c"], result)
}
func testUnseenPhrasesToday_withGlobalPhrases() {
walkCongratsPhrasesSeenToday = ["b"]
let result = CongratsPhrase.unseenPhrasesToday(["a", "b", "c"])
XCTAssertEqual(["a", "c"], result)
}
func testUnseenPhrasesToday_withGlobalPhrases_whenAllSeen() {
walkCongratsPhrasesSeenToday = ["b", "c", "a"]
let result = CongratsPhrase.unseenPhrasesToday(["a", "b", "c"])
XCTAssertEqual(["a", "b", "c"], result)
XCTAssertEqual([], walkCongratsPhrasesSeenToday)
}
} | mit | 4a96e40b5ca08b26db406f214574b88d | 28.888 | 92 | 0.683802 | 3.923319 | false | true | false | false |
benlangmuir/swift | test/IRGen/debug_poison.swift | 9 | 6618 | // RUN: %target-swift-frontend -primary-file %s -emit-ir -Onone -enable-copy-propagation -enable-lexical-borrow-scopes=false | %FileCheck %s -DINT=i%target-ptrsize
//
// This test is currently disabled because mandatory copy propagation
// is not part of the pipeline. It may be re-added to the pipeline,
// but it isn't clear if we'll still need to emit poison references by
// that time.
//
// REQUIRES: mandatory_copy_propagation
// Test debug_value [poison] emission
class K {
init() {}
}
protocol P : AnyObject {}
class D : P {}
protocol Q {}
class E : Q {}
func useInt(_ i: Int) {}
func useAny(_: Any) {}
func useOptionalAny(_: Any?) {}
func useNone() {}
func getK() -> K { return K() }
func getOptionalK() -> K? { return K() }
private func useK(_: K) -> Int {
return 2
}
private func useOptionalK(_: K?) -> Int {
return 2
}
// Hoist and poison 'b' above useInt(y).
//
// CHECK-LABEL: define {{.*}}swiftcc void @"$s12debug_poison13testPoisonRefyyF"
// CHECK: %b.debug = alloca %T12debug_poison1KC*
// CHECK: %y.debug = alloca [[INT]]
// CHECK: [[REF:%.*]] = call {{.*}} %T12debug_poison1KC* @"$s12debug_poison4getKAA1KCyF"()
// CHECK: store %T12debug_poison1KC* [[REF]], %T12debug_poison1KC** %b.debug
// CHECK: [[Y:%.*]] = call {{.*}} [[INT]] @"$s12debug_poison4use{{.*}}"(%T12debug_poison1KC* [[REF]])
// CHECK: call void {{.*}} @swift_release {{.*}} [[REF]]
// CHECK: store %T12debug_poison1KC* inttoptr ([[INT]] 1088 to %T12debug_poison1KC*), %T12debug_poison1KC** %b.debug
// CHECK: store [[INT]] [[Y]], [[INT]]* %y.debug
// CHECK: call {{.*}} void @"$s12debug_poison6useIntyySiF"([[INT]] [[Y]])
public func testPoisonRef() {
let b = getK()
let y = useK(b)
useInt(y)
}
// Hoist and poison 'b' above useInt(y).
//
// CHECK-LABEL: define {{.*}}swiftcc void @"$s12debug_poison21testPoisonOptionalRefyyF"
// CHECK: %b.debug = alloca [[INT]]
// CHECK: %y.debug = alloca [[INT]]
// CHECK: [[REF:%.*]] = call {{.*}} [[INT]] @"$s12debug_poison12getOptionalKAA1KCSgyF"()
// CHECK: store [[INT]] [[REF]], [[INT]]* %b.debug
// CHECK: [[Y:%.*]] = call {{.*}} [[INT]] @"$s12debug_poison12useOptionalK{{.*}}"([[INT]] [[REF]])
// CHECK: call void @swift_release
// CHECK: [[NIL:%.*]] = icmp eq [[INT]] [[REF]], 0
// CHECK: [[POISON:%.*]] = select i1 [[NIL]], [[INT]] [[REF]], [[INT]] 1088
// CHECK: store [[INT]] [[POISON]], [[INT]]* %b.debug
// CHECK: store [[INT]] [[Y]], [[INT]]* %y.debug
// CHECK: call {{.*}} void @"$s12debug_poison6useIntyySiF"([[INT]] [[Y]])
public func testPoisonOptionalRef() {
let b: K? = getOptionalK()
let y = useOptionalK(b)
useInt(y)
}
// Hoist and poison 'b' above useNone.
//
// CHECK-LABEL: define {{.*}}swiftcc void @"$s12debug_poison21testPoisonExistentialyyF"
// CHECK: %b.debug = alloca %T12debug_poison1PP
// CHECK: [[INIT:%.*]] = call {{.*}} %T12debug_poison1DC* @"$s12debug_poison1DCACycfC"(
// CHECK: [[REF:%.*]] = bitcast %T12debug_poison1DC* [[INIT]] to %[[REFTY:.*]]*
// CHECK: [[GEP0:%.*]] = getelementptr inbounds %T12debug_poison1PP, %T12debug_poison1PP* %b.debug, i32 0, i32 0
// CHECK: store %[[REFTY]]* [[REF]], %[[REFTY]]** [[GEP0]]
// CHECK: store i8** getelementptr inbounds ([1 x i8*], [1 x i8*]* @"$s12debug_poison1DCAA1PAAWP", i32 0, i32 0), i8***
// CHECK: call %[[REFTY]]* @swift_{{unknownObjectRetain|retain}}(%[[REFTY]]* returned [[REF]])
// CHECK: store %[[REFTY]]* [[REF]], %[[REFTY]]**
// CHECK: call {{.*}} void @"$s12debug_poison6useAnyyyypF"(
// CHECK: call void @swift_{{unknownObjectRelease|release}}(%[[REFTY]]* [[REF]])
// CHECK: [[GEP1:%.*]] = getelementptr inbounds %T12debug_poison1PP, %T12debug_poison1PP* %b.debug, i32 0, i32 0
// CHECK: store %[[REFTY]]* inttoptr ([[INT]] 1088 to %[[REFTY]]*), %[[REFTY]]** [[GEP1]]
// CHECK: call {{.*}} void @"$s12debug_poison7useNoneyyF"()
public func testPoisonExistential() {
let b: P = D()
useAny(b)
useNone()
}
// Hoist and poison 'b' above useNone.
//
// CHECK-LABEL: define {{.*}}swiftcc void @"$s12debug_poison19testPoisonCompositeyyF"()
// CHECK: %b.debug = alloca %T12debug_poison1Q_Xl
// CHECK: [[INIT:%.*]] = call {{.*}} %T12debug_poison1EC* @"$s12debug_poison1ECACycfC"(
// CHECK: [[REF:%.*]] = bitcast %T12debug_poison1EC* [[INIT]] to %[[REFTY]]*
// CHECK: [[GEP0:%.*]] = getelementptr inbounds %T12debug_poison1Q_Xl, %T12debug_poison1Q_Xl* %b.debug, i32 0, i32 0
// CHECK: store %[[REFTY]]* [[REF]], %[[REFTY]]** [[GEP0]]
// CHECK: store i8** getelementptr inbounds ([1 x i8*], [1 x i8*]* @"$s12debug_poison1ECAA1QAAWP", i32 0, i32 0), i8***
// CHECK: call %[[REFTY]]* @swift_{{unknownObjectRetain|retain}}(%[[REFTY]]* returned [[REF]])
// CHECK: store %[[REFTY]]* [[REF]], %[[REFTY]]**
// CHECK: call {{.*}} void @"$s12debug_poison6useAnyyyypF"(
// CHECK: call void @swift_{{unknownObjectRelease|release}}(%[[REFTY]]* [[REF]])
// CHECK: [[GEP1:%.*]] = getelementptr inbounds %T12debug_poison1Q_Xl, %T12debug_poison1Q_Xl* %b.debug, i32 0, i32 0
// CHECK: store %[[REFTY]]* inttoptr ([[INT]] 1088 to %[[REFTY]]*), %[[REFTY]]** [[GEP1]]
// CHECK: call {{.*}} void @"$s12debug_poison7useNoneyyF"()
public func testPoisonComposite() {
let b: Q & AnyObject = E()
useAny(b)
useNone()
}
// CopyPropagation hoists 'b' above useNone, but IRGen currently bails on emitting poison.
//
// CHECK-LABEL: define {{.*}}swiftcc void @"$s12debug_poison27testPoisonOptionalCompositeyyF"()
// CHECK: %b.debug = alloca %T12debug_poison1Q_XlSg
// CHECK: [[INIT:%.*]] = call {{.*}} %T12debug_poison1EC* @"$s12debug_poison1ECACycfC"(
// CHECK: [[REF0:%.*]] = bitcast %T12debug_poison1EC* [[INIT]] to %[[REFTY]]*
// CHECK: [[REFINT0:%.*]] = ptrtoint %[[REFTY]]* [[REF0]] to [[INT]]
// CHECK: [[SHADOW0:%.*]] = bitcast %T12debug_poison1Q_XlSg* %b.debug to { [[INT]], [[INT]] }*
// CHECK: [[GEP0:%.*]] = getelementptr inbounds {{.*}} [[SHADOW0]], i32 0, i32 0
// CHECK: store [[INT]] [[REFINT0]], [[INT]]* [[GEP0]]
// CHECK: store [[INT]] ptrtoint ([1 x i8*]* @"$s12debug_poison1ECAA1QAAWP" to [[INT]]),
// CHECK: [[REF1:%.*]] = inttoptr [[INT]] [[REFINT0]] to %[[REFTY]]*
// CHECK: call %[[REFTY]]* @swift_{{unknownObjectRetain|retain}}(%[[REFTY]]* returned [[REF1]])
// CHECK: icmp eq [[INT]] [[REFINT0]], 0
// CHECK: [[PHI:%.*]] = phi %[[REFTY]]*
// CHECK: call void @swift_{{unknownObjectRelease|release}}(%[[REFTY]]*
// CHECK: store %[[REFTY]]* [[PHI]], %[[REFTY]]**
// CHECK: call {{.*}} void @"$s12debug_poison14useOptionalAnyyyypSgF"(
//
// Currently no poison store here.
// CHECK-NOT: store
// CHECK: call {{.*}} void @"$s12debug_poison7useNoneyyF"()
public func testPoisonOptionalComposite() {
let b: Optional<Q & AnyObject> = E()
useOptionalAny(b)
useNone()
}
| apache-2.0 | c3bdab360efe310465f7baa0549b347e | 44.328767 | 163 | 0.618767 | 3.03022 | false | true | false | false |
walkingsmarts/ReactiveCocoa | ReactiveCocoa/NSObject+KeyValueObserving.swift | 4 | 12132 | import Foundation
import ReactiveSwift
import enum Result.NoError
extension Reactive where Base: NSObject {
/// Create a producer which sends the current value and all the subsequent
/// changes of the property specified by the key path.
///
/// The producer completes when the object deinitializes.
///
/// - parameters:
/// - keyPath: The key path of the property to be observed.
///
/// - returns: A producer emitting values of the property specified by the
/// key path.
public func producer(forKeyPath keyPath: String) -> SignalProducer<Any?, NoError> {
return SignalProducer { observer, lifetime in
let disposable = KeyValueObserver.observe(
self.base,
keyPath: keyPath,
options: [.initial, .new],
action: observer.send
)
lifetime.observeEnded(disposable.dispose)
if let lifetimeDisposable = self.lifetime.observeEnded(observer.sendCompleted) {
lifetime.observeEnded(lifetimeDisposable.dispose)
}
}
}
/// Create a signal all changes of the property specified by the key path.
///
/// The signal completes when the object deinitializes.
///
/// - note:
/// Does not send the initial value. See `producer(forKeyPath:)`.
///
/// - parameters:
/// - keyPath: The key path of the property to be observed.
///
/// - returns: A producer emitting values of the property specified by the
/// key path.
public func signal(forKeyPath keyPath: String) -> Signal<Any?, NoError> {
return Signal { observer in
let disposable = CompositeDisposable()
disposable += KeyValueObserver.observe(
self.base,
keyPath: keyPath,
options: [.new],
action: observer.send
)
disposable += self.lifetime.observeEnded(observer.sendCompleted)
return disposable
}
}
}
internal final class KeyValueObserver: NSObject {
typealias Action = (_ object: AnyObject?) -> Void
private static let context = UnsafeMutableRawPointer.allocate(bytes: 1, alignedTo: 0)
unowned(unsafe) let unsafeObject: NSObject
let key: String
let action: Action
fileprivate init(observing object: NSObject, key: String, options: NSKeyValueObservingOptions, action: @escaping Action) {
self.unsafeObject = object
self.key = key
self.action = action
super.init()
object.addObserver(
self,
forKeyPath: key,
options: options,
context: KeyValueObserver.context
)
}
func detach() {
unsafeObject.removeObserver(self, forKeyPath: key, context: KeyValueObserver.context)
}
override func observeValue(
forKeyPath keyPath: String?,
of object: Any?,
change: [NSKeyValueChangeKey : Any]?,
context: UnsafeMutableRawPointer?
) {
if context == KeyValueObserver.context {
action(object as! NSObject)
}
}
}
extension KeyValueObserver {
/// Establish an observation to the property specified by the key path
/// of `object`.
///
/// - warning: The observation would not be automatically removed when
/// `object` deinitializes. You must manually dispose of the
/// returned disposable before `object` completes its
/// deinitialization.
///
/// - parameters:
/// - object: The object to be observed.
/// - keyPath: The key path of the property to be observed.
/// - options: The desired configuration of the observation.
/// - action: The action to be invoked upon arrival of changes.
///
/// - returns: A disposable that would tear down the observation upon
/// disposal.
static func observe(
_ object: NSObject,
keyPath: String,
options: NSKeyValueObservingOptions,
action: @escaping (_ value: AnyObject?) -> Void
) -> AnyDisposable {
// Compute the key path head and tail.
let components = keyPath.components(separatedBy: ".")
precondition(!components.isEmpty, "Received an empty key path.")
let isNested = components.count > 1
let keyPathHead = components[0]
let keyPathTail = components[1 ..< components.endIndex].joined(separator: ".")
// The serial disposable for the head key.
//
// The inner disposable would be disposed of, and replaced with a new one
// when the value of the head key changes.
let headSerialDisposable = SerialDisposable()
// If the property of the head key isn't actually an object (or is a Class
// object), there is no point in observing the deallocation.
//
// If this property is not a weak reference to an object, we don't need to
// watch for it spontaneously being set to nil.
//
// Attempting to observe non-weak properties using dynamic getters will
// result in broken behavior, so don't even try.
let (shouldObserveDeinit, isWeak) = keyPathHead.withCString { cString -> (Bool, Bool) in
if let propertyPointer = class_getProperty(type(of: object), cString) {
let attributes = PropertyAttributes(property: propertyPointer)
return (attributes.isObject && attributes.objectClass != NSClassFromString("Protocol") && !attributes.isBlock, attributes.isWeak)
}
return (false, false)
}
// Establish the observation.
//
// The initial value is also handled by the closure below, if `Initial` has
// been specified in the observation options.
let observer: KeyValueObserver
if isNested {
observer = KeyValueObserver(observing: object, key: keyPathHead, options: options.union(.initial)) { object in
guard let value = object?.value(forKey: keyPathHead) as! NSObject? else {
action(nil)
return
}
let headDisposable = CompositeDisposable()
headSerialDisposable.inner = headDisposable
if shouldObserveDeinit {
let disposable = value.reactive.lifetime.observeEnded {
if isWeak {
action(nil)
}
// Detach the key path tail observers eagarly.
headSerialDisposable.inner = nil
}
headDisposable += disposable
}
// Recursively add observers along the key path tail.
let disposable = KeyValueObserver.observe(
value,
keyPath: keyPathTail,
options: options.subtracting(.initial),
action: action
)
headDisposable += disposable
// Send the latest value of the key path tail.
action(value.value(forKeyPath: keyPathTail) as AnyObject?)
}
} else {
observer = KeyValueObserver(observing: object, key: keyPathHead, options: options) { object in
guard let value = object?.value(forKey: keyPathHead) as AnyObject? else {
action(nil)
return
}
// For a direct key path, the deinitialization needs to be
// observed only if the key path is a weak property.
if shouldObserveDeinit && isWeak {
let disposable = lifetime(of: value).observeEnded {
action(nil)
}
headSerialDisposable.inner = disposable
}
// Send the latest value of the key.
action(value)
}
}
return AnyDisposable {
observer.detach()
headSerialDisposable.dispose()
}
}
}
/// A descriptor of the attributes and type information of a property in
/// Objective-C.
internal struct PropertyAttributes {
struct Code {
static let start = Int8(UInt8(ascii: "T"))
static let quote = Int8(UInt8(ascii: "\""))
static let nul = Int8(UInt8(ascii: "\0"))
static let comma = Int8(UInt8(ascii: ","))
struct ContainingType {
static let object = Int8(UInt8(ascii: "@"))
static let block = Int8(UInt8(ascii: "?"))
}
struct Attribute {
static let readonly = Int8(UInt8(ascii: "R"))
static let copy = Int8(UInt8(ascii: "C"))
static let retain = Int8(UInt8(ascii: "&"))
static let nonatomic = Int8(UInt8(ascii: "N"))
static let getter = Int8(UInt8(ascii: "G"))
static let setter = Int8(UInt8(ascii: "S"))
static let dynamic = Int8(UInt8(ascii: "D"))
static let ivar = Int8(UInt8(ascii: "V"))
static let weak = Int8(UInt8(ascii: "W"))
static let collectable = Int8(UInt8(ascii: "P"))
static let oldTypeEncoding = Int8(UInt8(ascii: "t"))
}
}
/// The class of the property.
let objectClass: AnyClass?
/// Indicate whether the property is a weak reference.
let isWeak: Bool
/// Indicate whether the property is an object.
let isObject: Bool
/// Indicate whether the property is a block.
let isBlock: Bool
init(property: objc_property_t) {
guard let attrString = property_getAttributes(property) else {
preconditionFailure("Could not get attribute string from property.")
}
precondition(attrString[0] == Code.start, "Expected attribute string to start with 'T'.")
let typeString = attrString + 1
let _next = NSGetSizeAndAlignment(typeString, nil, nil)
guard _next != typeString else {
let string = String(validatingUTF8: attrString)
preconditionFailure("Could not read past type in attribute string: \(String(describing: string)).")
}
var next = UnsafeMutablePointer<Int8>(mutating: _next)
let typeLength = typeString.distance(to: next)
precondition(typeLength > 0, "Invalid type in attribute string.")
var objectClass: AnyClass? = nil
// if this is an object type, and immediately followed by a quoted string...
if typeString[0] == Code.ContainingType.object && typeString[1] == Code.quote {
// we should be able to extract a class name
let className = typeString + 2;
// fast forward the `next` pointer.
guard let endQuote = strchr(className, Int32(Code.quote)) else {
preconditionFailure("Could not read class name in attribute string.")
}
next = endQuote
if className != UnsafePointer(next) {
let length = className.distance(to: next)
let name = UnsafeMutablePointer<Int8>.allocate(capacity: length + 1)
name.initialize(from: UnsafeMutablePointer<Int8>(mutating: className), count: length)
(name + length).initialize(to: Code.nul)
// attempt to look up the class in the runtime
objectClass = objc_getClass(name) as! AnyClass?
name.deinitialize(count: length + 1)
name.deallocate(capacity: length + 1)
}
}
if next.pointee != Code.nul {
// skip past any junk before the first flag
next = strchr(next, Int32(Code.comma))
}
let emptyString = UnsafeMutablePointer<Int8>.allocate(capacity: 1)
emptyString.initialize(to: Code.nul)
defer {
emptyString.deinitialize()
emptyString.deallocate(capacity: 1)
}
var isWeak = false
while next.pointee == Code.comma {
let flag = next[1]
next += 2
switch flag {
case Code.nul:
break;
case Code.Attribute.readonly:
break;
case Code.Attribute.copy:
break;
case Code.Attribute.retain:
break;
case Code.Attribute.nonatomic:
break;
case Code.Attribute.getter:
fallthrough
case Code.Attribute.setter:
next = strchr(next, Int32(Code.comma)) ?? emptyString
case Code.Attribute.dynamic:
break
case Code.Attribute.ivar:
// assume that the rest of the string (if present) is the ivar name
if next.pointee != Code.nul {
next = emptyString
}
case Code.Attribute.weak:
isWeak = true
case Code.Attribute.collectable:
break
case Code.Attribute.oldTypeEncoding:
let string = String(validatingUTF8: attrString)
assertionFailure("Old-style type encoding is unsupported in attribute string \"\(String(describing: string))\"")
// skip over this type encoding
while next.pointee != Code.comma && next.pointee != Code.nul {
next += 1
}
default:
let pointer = UnsafeMutablePointer<Int8>.allocate(capacity: 2)
pointer.initialize(to: flag)
(pointer + 1).initialize(to: Code.nul)
let flag = String(validatingUTF8: pointer)
let string = String(validatingUTF8: attrString)
preconditionFailure("ERROR: Unrecognized attribute string flag '\(String(describing: flag))' in attribute string \"\(String(describing: string))\".")
}
}
if next.pointee != Code.nul {
let unparsedData = String(validatingUTF8: next)
let string = String(validatingUTF8: attrString)
assertionFailure("Warning: Unparsed data \"\(String(describing: unparsedData))\" in attribute string \"\(String(describing: string))\".")
}
self.objectClass = objectClass
self.isWeak = isWeak
self.isObject = typeString[0] == Code.ContainingType.object
self.isBlock = isObject && typeString[1] == Code.ContainingType.block
}
}
| mit | 610873f28b9facb791cecad0b370638e | 29.713924 | 153 | 0.692878 | 3.863694 | false | false | false | false |
varkor/firefox-ios | Storage/SQL/BrowserDB.swift | 1 | 17605 | /* 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 XCGLogger
import Deferred
import Shared
import Deferred
public let NotificationDatabaseWasRecreated = "NotificationDatabaseWasRecreated"
private let log = Logger.syncLogger
public typealias Args = [AnyObject?]
protocol Changeable {
func run(sql: String, withArgs args: Args?) -> Success
func run(commands: [String]) -> Success
func run(commands: [(sql: String, args: Args?)]) -> Success
}
protocol Queryable {
func runQuery<T>(sql: String, args: Args?, factory: SDRow -> T) -> Deferred<Maybe<Cursor<T>>>
}
// Version 1 - Basic history table.
// Version 2 - Added a visits table, refactored the history table to be a GenericTable.
// Version 3 - Added a favicons table.
// Version 4 - Added a readinglist table.
// Version 5 - Added the clients and the tabs tables.
// Version 6 - Visit timestamps are now microseconds.
// Version 7 - Eliminate most tables. See BrowserTable instead.
public class BrowserDB {
private let db: SwiftData
// XXX: Increasing this should blow away old history, since we currently don't support any upgrades.
private let Version: Int = 7
private let files: FileAccessor
private let filename: String
private let secretKey: String?
private let schemaTable: SchemaTable
private var initialized = [String]()
// SQLITE_MAX_VARIABLE_NUMBER = 999 by default. This controls how many ?s can
// appear in a query string.
public static let MaxVariableNumber = 999
public init(filename: String, secretKey: String? = nil, files: FileAccessor) {
log.debug("Initializing BrowserDB: \(filename).")
self.files = files
self.filename = filename
self.schemaTable = SchemaTable()
self.secretKey = secretKey
let file = ((try! files.getAndEnsureDirectory()) as NSString).stringByAppendingPathComponent(filename)
self.db = SwiftData(filename: file, key: secretKey, prevKey: nil)
if AppConstants.BuildChannel == .Developer && secretKey != nil {
log.debug("Creating db: \(file) with secret = \(secretKey)")
}
// Create or update will also delete and create the database if our key was incorrect.
self.createOrUpdate(self.schemaTable)
}
// Creates a table and writes its table info into the table-table database.
private func createTable(conn: SQLiteDBConnection, table: SectionCreator) -> TableResult {
log.debug("Try create \(table.name) version \(table.version)")
if !table.create(conn) {
// If creating failed, we'll bail without storing the table info
log.debug("Creation failed.")
return .Failed
}
var err: NSError? = nil
return schemaTable.insert(conn, item: table, err: &err) > -1 ? .Created : .Failed
}
// Updates a table and writes its table into the table-table database.
// Exposed internally for testing.
func updateTable(conn: SQLiteDBConnection, table: SectionUpdater) -> TableResult {
log.debug("Trying update \(table.name) version \(table.version)")
var from = 0
// Try to find the stored version of the table
let cursor = schemaTable.query(conn, options: QueryOptions(filter: table.name))
if cursor.count > 0 {
if let info = cursor[0] as? TableInfoWrapper {
from = info.version
}
}
// If the versions match, no need to update
if from == table.version {
return .Exists
}
if !table.updateTable(conn, from: from) {
// If the update failed, we'll bail without writing the change to the table-table.
log.debug("Updating failed.")
return .Failed
}
var err: NSError? = nil
// Yes, we UPDATE OR INSERT… because we might be transferring ownership of a database table
// to a different Table. It'll trigger exists, and thus take the update path, but we won't
// necessarily have an existing schema entry -- i.e., we'll be updating from 0.
if schemaTable.update(conn, item: table, err: &err) > 0 ||
schemaTable.insert(conn, item: table, err: &err) > 0 {
return .Updated
}
return .Failed
}
// Utility for table classes. They should call this when they're initialized to force
// creation of the table in the database.
func createOrUpdate(tables: Table...) -> Bool {
var success = true
let doCreate = { (table: Table, connection: SQLiteDBConnection) -> () in
switch self.createTable(connection, table: table) {
case .Created:
success = true
return
case .Exists:
log.debug("Table already exists.")
success = true
return
default:
success = false
}
}
if let _ = self.db.transaction({ connection -> Bool in
let thread = NSThread.currentThread().description
// If the table doesn't exist, we'll create it.
for table in tables {
log.debug("Create or update \(table.name) version \(table.version) on \(thread).")
if !table.exists(connection) {
log.debug("Doesn't exist. Creating table \(table.name).")
doCreate(table, connection)
} else {
// Otherwise, we'll update it
switch self.updateTable(connection, table: table) {
case .Updated:
log.debug("Updated table \(table.name).")
success = true
break
case .Exists:
log.debug("Table \(table.name) already exists.")
success = true
break
default:
log.error("Update failed for \(table.name). Dropping and recreating.")
table.drop(connection)
var err: NSError? = nil
self.schemaTable.delete(connection, item: table, err: &err)
doCreate(table, connection)
}
}
if !success {
log.warning("Failed to configure multiple tables. Aborting.")
return false
}
}
return success
}) {
// Err getting a transaction
success = false
}
// If we failed, move the file and try again. This will probably break things that are already
// attached and expecting a working DB, but at least we should be able to restart.
var notify: NSNotification? = nil
if !success {
log.debug("Couldn't create or update \(tables.map { $0.name }).")
log.debug("Attempting to move \(self.filename) to another location.")
// Make sure that we don't still have open the files that we want to move!
// Note that we use sqlite3_close_v2, which might actually _not_ close the
// database file yet. For this reason we move the -shm and -wal files, too.
db.forceClose()
// Note that a backup file might already exist! We append a counter to avoid this.
var bakCounter = 0
var bak: String
repeat {
bakCounter += 1
bak = "\(self.filename).bak.\(bakCounter)"
} while self.files.exists(bak)
do {
try self.files.move(self.filename, toRelativePath: bak)
let shm = self.filename + "-shm"
let wal = self.filename + "-wal"
log.debug("Moving \(shm) and \(wal)…")
if self.files.exists(shm) {
log.debug("\(shm) exists.")
try self.files.move(shm, toRelativePath: bak + "-shm")
}
if self.files.exists(wal) {
log.debug("\(wal) exists.")
try self.files.move(wal, toRelativePath: bak + "-wal")
}
success = true
// Notify the world that we moved the database. This allows us to
// reset sync and start over in the case of corruption.
let notification = NotificationDatabaseWasRecreated
notify = NSNotification(name: notification, object: self.filename)
} catch _ {
success = false
}
assert(success)
// Do this after the relevant tables have been created.
defer {
if let notify = notify {
NSNotificationCenter.defaultCenter().postNotification(notify)
}
}
if let _ = db.transaction({ connection -> Bool in
for table in tables {
doCreate(table, connection)
if !success {
return false
}
}
return success
}) {
success = false
}
}
return success
}
typealias IntCallback = (connection: SQLiteDBConnection, inout err: NSError?) -> Int
func withConnection<T>(flags flags: SwiftData.Flags, inout err: NSError?, callback: (connection: SQLiteDBConnection, inout err: NSError?) -> T) -> T {
var res: T!
err = db.withConnection(flags) { connection in
// An error may occur if the internet connection is dropped.
var err: NSError? = nil
res = callback(connection: connection, err: &err)
return err
}
return res
}
func withWritableConnection<T>(inout err: NSError?, callback: (connection: SQLiteDBConnection, inout err: NSError?) -> T) -> T {
return withConnection(flags: SwiftData.Flags.ReadWrite, err: &err, callback: callback)
}
func withReadableConnection<T>(inout err: NSError?, callback: (connection: SQLiteDBConnection, inout err: NSError?) -> Cursor<T>) -> Cursor<T> {
return withConnection(flags: SwiftData.Flags.ReadOnly, err: &err, callback: callback)
}
func transaction(inout err: NSError?, callback: (connection: SQLiteDBConnection, inout err: NSError?) -> Bool) -> NSError? {
return self.transaction(synchronous: true, err: &err, callback: callback)
}
func transaction(synchronous synchronous: Bool=true, inout err: NSError?, callback: (connection: SQLiteDBConnection, inout err: NSError?) -> Bool) -> NSError? {
return db.transaction(synchronous: synchronous) { connection in
var err: NSError? = nil
return callback(connection: connection, err: &err)
}
}
}
extension BrowserDB {
func vacuum() {
log.debug("Vacuuming a BrowserDB.")
db.withConnection(SwiftData.Flags.ReadWriteCreate, synchronous: true) { connection in
return connection.vacuum()
}
}
func checkpoint() {
log.debug("Checkpointing a BrowserDB.")
db.transaction(synchronous: true) { connection in
connection.checkpoint()
return true
}
}
}
extension BrowserDB {
public class func varlist(count: Int) -> String {
return "(" + Array(count: count, repeatedValue: "?").joinWithSeparator(", ") + ")"
}
enum InsertOperation: String {
case Insert = "INSERT"
case Replace = "REPLACE"
case InsertOrIgnore = "INSERT OR IGNORE"
case InsertOrReplace = "INSERT OR REPLACE"
case InsertOrRollback = "INSERT OR ROLLBACK"
case InsertOrAbort = "INSERT OR ABORT"
case InsertOrFail = "INSERT OR FAIL"
}
/**
* Insert multiple sets of values into the given table.
*
* Assumptions:
* 1. The table exists and contains the provided columns.
* 2. Every item in `values` is the same length.
* 3. That length is the same as the length of `columns`.
* 4. Every value in each element of `values` is non-nil.
*
* If there are too many items to insert, multiple individual queries will run
* in sequence.
*
* A failure anywhere in the sequence will cause immediate return of failure, but
* will not roll back — use a transaction if you need one.
*/
func bulkInsert(table: String, op: InsertOperation, columns: [String], values: [Args]) -> Success {
// Note that there's a limit to how many ?s can be in a single query!
// So here we execute 999 / (columns * rows) insertions per query.
// Note that we can't use variables for the column names, so those don't affect the count.
if values.isEmpty {
log.debug("No values to insert.")
return succeed()
}
let variablesPerRow = columns.count
// Sanity check.
assert(values[0].count == variablesPerRow)
let cols = columns.joinWithSeparator(", ")
let queryStart = "\(op.rawValue) INTO \(table) (\(cols)) VALUES "
let varString = BrowserDB.varlist(variablesPerRow)
let insertChunk: [Args] -> Success = { vals -> Success in
let valuesString = Array(count: vals.count, repeatedValue: varString).joinWithSeparator(", ")
let args: Args = vals.flatMap { $0 }
return self.run(queryStart + valuesString, withArgs: args)
}
let rowCount = values.count
if (variablesPerRow * rowCount) < BrowserDB.MaxVariableNumber {
return insertChunk(values)
}
log.debug("Splitting bulk insert across multiple runs. I hope you started a transaction!")
let rowsPerInsert = (999 / variablesPerRow)
let chunks = chunk(values, by: rowsPerInsert)
log.debug("Inserting in \(chunks.count) chunks.")
// There's no real reason why we can't pass the ArraySlice here, except that I don't
// want to keep fighting Swift.
return walk(chunks, f: { insertChunk(Array($0)) })
}
func runWithConnection<T>(block: (connection: SQLiteDBConnection, inout err: NSError?) -> T) -> Deferred<Maybe<T>> {
return DeferredDBOperation(db: self.db, block: block).start()
}
func write(sql: String, withArgs args: Args? = nil) -> Deferred<Maybe<Int>> {
return self.runWithConnection() { (connection, err) -> Int in
err = connection.executeChange(sql, withArgs: args)
if err == nil {
let modified = connection.numberOfRowsModified
log.debug("Modified rows: \(modified).")
return modified
}
return 0
}
}
public func forceClose() {
db.forceClose()
}
}
extension BrowserDB: Changeable {
func run(sql: String, withArgs args: Args? = nil) -> Success {
return run([(sql, args)])
}
func run(commands: [String]) -> Success {
return self.run(commands.map { (sql: $0, args: nil) })
}
/**
* Runs an array of SQL commands. Note: These will all run in order in a transaction and will block
* the caller's thread until they've finished. If any of them fail the operation will abort (no more
* commands will be run) and the transaction will roll back, returning a DatabaseError.
*/
func run(commands: [(sql: String, args: Args?)]) -> Success {
if commands.isEmpty {
return succeed()
}
var err: NSError? = nil
let errorResult = self.transaction(&err) { (conn, err) -> Bool in
for (sql, args) in commands {
err = conn.executeChange(sql, withArgs: args)
if let err = err {
log.warning("SQL operation failed: \(err.localizedDescription)")
return false
}
}
return true
}
if let err = err ?? errorResult {
return deferMaybe(DatabaseError(err: err))
}
return succeed()
}
}
extension BrowserDB: Queryable {
func runQuery<T>(sql: String, args: Args?, factory: SDRow -> T) -> Deferred<Maybe<Cursor<T>>> {
return runWithConnection { (connection, err) -> Cursor<T> in
return connection.executeQuery(sql, factory: factory, withArgs: args)
}
}
func queryReturnsResults(sql: String, args: Args?=nil) -> Deferred<Maybe<Bool>> {
return self.runQuery(sql, args: args, factory: { row in true })
>>== { deferMaybe($0[0] ?? false) }
}
func queryReturnsNoResults(sql: String, args: Args?=nil) -> Deferred<Maybe<Bool>> {
return self.runQuery(sql, args: nil, factory: { row in false })
>>== { deferMaybe($0[0] ?? true) }
}
}
extension SQLiteDBConnection {
func tablesExist(names: [String]) -> Bool {
let count = names.count
let inClause = BrowserDB.varlist(names.count)
let tablesSQL = "SELECT name FROM sqlite_master WHERE type = 'table' AND name IN \(inClause)"
let res = self.executeQuery(tablesSQL, factory: StringFactory, withArgs: names.map { $0 as AnyObject })
log.debug("\(res.count) tables exist. Expected \(count)")
return res.count > 0
}
}
| mpl-2.0 | 704180a78ad065e88738d60a6a8d33e7 | 37.935841 | 164 | 0.585999 | 4.766793 | false | false | false | false |
audrl1010/EasyMakePhotoPicker | EasyMakePhotoPicker/Classes/PhotosViewConfigure.swift | 1 | 2746 | //
// PhotosViewConfigure.swift
// PhotoPicker
//
// Created by myung gi son on 2017. 6. 25..
// Copyright © 2017년 grutech. All rights reserved.
//
import UIKit
import Photos
import PhotosUI
import UIKit
public protocol PhotosViewConfigure {
var fetchOptions: PHFetchOptions { get }
var allowsMultipleSelection: Bool { get }
var allowsCameraSelection: Bool { get }
// .video, .livePhoto
var allowsPlayTypes: [AssetType] { get }
var messageWhenMaxCountSelectedPhotosIsExceeded: String { get }
var maxCountSelectedPhotos: Int { get }
// get item image from PHCachingImageManager
// based on the UICollectionViewFlowLayout`s itemSize,
// therefore must set well itemSize in UICollectionViewFlowLayout.
var layout: UICollectionViewFlowLayout { get }
var photoCellTypeConverter: PhotoCellTypeConverter { get }
var livePhotoCellTypeConverter: LivePhotoCellTypeConverter { get }
var videoCellTypeConverter: VideoCellTypeConverter { get }
var cameraCellTypeConverter: CameraCellTypeConverter { get }
}
public protocol CellTypeConverter {
associatedtype Cellable
var cellIdentifier: String { get }
var cellClass: AnyClass { get }
}
public struct PhotoCellTypeConverter: CellTypeConverter {
public typealias Cellable = PhotoCellable
public var cellIdentifier: String
public var cellClass: AnyClass
public init<C: UICollectionViewCell>(type: C.Type) where C: Cellable {
cellIdentifier = NSStringFromClass(type)
cellClass = type
}
}
public struct LivePhotoCellTypeConverter: CellTypeConverter {
public typealias Cellable = LivePhotoCellable
public var cellIdentifier: String
public var cellClass: AnyClass
public init<C: UICollectionViewCell>(type: C.Type) where C: Cellable {
cellIdentifier = NSStringFromClass(type)
cellClass = type
}
}
public struct VideoCellTypeConverter: CellTypeConverter {
public typealias Cellable = VideoCellable
public var cellIdentifier: String
public var cellClass: AnyClass
public init<C: UICollectionViewCell>(type: C.Type) where C: Cellable {
cellIdentifier = NSStringFromClass(type)
cellClass = type
}
}
public struct CameraCellTypeConverter: CellTypeConverter {
public typealias Cellable = CameraCellable
public var cellIdentifier: String
public var cellClass: AnyClass
public init<C: UICollectionViewCell>(type: C.Type) where C: Cellable {
cellIdentifier = NSStringFromClass(type)
cellClass = type
}
}
public protocol CameraCellable: class { }
public protocol PhotoCellable: class {
var viewModel: PhotoCellViewModel? { get set }
}
public protocol LivePhotoCellable: PhotoCellable { }
public protocol VideoCellable: PhotoCellable { }
| mit | 6d9d5e55f5cf635a1b2caebcf5f092f5 | 22.444444 | 72 | 0.753555 | 4.737478 | false | false | false | false |
ktmswzw/FeelingClientBySwift | Pods/ImagePickerSheetController/ImagePickerSheetController/ImagePickerSheetController/ImagePickerAction.swift | 5 | 2736 | //
// ImagePickerAction.swift
// ImagePickerSheet
//
// Created by Laurin Brandner on 24/05/15.
// Copyright (c) 2015 Laurin Brandner. All rights reserved.
//
import Foundation
public enum ImagePickerActionStyle {
case Default
case Cancel
}
public class ImagePickerAction {
public typealias Title = Int -> String
public typealias Handler = (ImagePickerAction) -> ()
public typealias SecondaryHandler = (ImagePickerAction, Int) -> ()
/// The title of the action's button.
public let title: String
/// The title of the action's button when more than one image is selected.
public let secondaryTitle: Title
/// The style of the action. This is used to call a cancel handler when dismissing the controller by tapping the background.
public let style: ImagePickerActionStyle
let handler: Handler
let secondaryHandler: SecondaryHandler
/// Initializes a new ImagePickerAction. The secondary title and handler are used when at least 1 image has been selected.
/// Secondary title defaults to title if not specified.
/// Secondary handler defaults to handler if not specified.
public convenience init(title: String, secondaryTitle: String? = nil, style: ImagePickerActionStyle = .Default, handler: Handler, secondaryHandler: SecondaryHandler? = nil) {
self.init(title: title, secondaryTitle: secondaryTitle.map { string in { _ in string }}, style: style, handler: handler, secondaryHandler: secondaryHandler)
}
/// Initializes a new ImagePickerAction. The secondary title and handler are used when at least 1 image has been selected.
/// Secondary title defaults to title if not specified. Use the closure to format a title according to the selection.
/// Secondary handler defaults to handler if not specified
public init(title: String, secondaryTitle: Title?, style: ImagePickerActionStyle = .Default, handler: Handler, var secondaryHandler: SecondaryHandler? = nil) {
if secondaryHandler == nil {
secondaryHandler = { action, _ in
handler(action)
}
}
self.title = title
self.secondaryTitle = secondaryTitle ?? { _ in title }
self.style = style
self.handler = handler
self.secondaryHandler = secondaryHandler!
}
func handle(numberOfImages: Int = 0) {
if numberOfImages > 0 {
secondaryHandler(self, numberOfImages)
}
else {
handler(self)
}
}
}
func ?? (left: ImagePickerAction.Title?, right: ImagePickerAction.Title) -> ImagePickerAction.Title {
if let left = left {
return left
}
return right
}
| mit | f7b999e15ba5cf148979ee50f98903b6 | 35.48 | 178 | 0.673611 | 4.842478 | false | false | false | false |
xivol/Swift-CS333 | playgrounds/extras/notification/local-notification/local-notification/LocalNotification.swift | 3 | 2195 | //
// LocalNotification.swift
// local-notification
//
// Created by Илья Лошкарёв on 21.04.17.
// Copyright © 2017 Илья Лошкарёв. All rights reserved.
//
import Foundation
import CoreLocation
import UserNotifications
import UserNotificationsUI
protocol LocalNotificationCenterDelegate: UNUserNotificationCenterDelegate {
func userNotificationCenter(_ center: UNUserNotificationCenter, failedToSheduleNotificationForIdentifier identifier: String, withError error: Error)
}
class LocalNotification {
let center: UNUserNotificationCenter
let identifier: String
var content = UNMutableNotificationContent()
private var trigger: UNNotificationTrigger?
init(withIdentifier identifier: String, deliverTo center: UNUserNotificationCenter = UNUserNotificationCenter.current()) {
self.identifier = identifier
self.center = center
}
func schedule(in timeInterval: TimeInterval, repeats: Bool) {
trigger = UNTimeIntervalNotificationTrigger(timeInterval: timeInterval, repeats: repeats)
send()
}
func schedule(forDateMatching date: DateComponents, repeats: Bool) {
trigger = UNCalendarNotificationTrigger(dateMatching: date, repeats: repeats)
send()
}
func schedule(forLocation location: CLLocation, inRadius radius: Double, repeats: Bool) {
let region = CLCircularRegion(center: location.coordinate, radius: radius, identifier: identifier + "TriggerLocation")
region.notifyOnEntry = true
region.notifyOnExit = false
trigger = UNLocationNotificationTrigger(region: region, repeats: repeats)
send()
}
private func send() {
let request = UNNotificationRequest(identifier:identifier, content: content, trigger: trigger)
center.add(request) {
error in
guard let error = error else {return}
if let delegate = self.center.delegate as? LocalNotificationCenterDelegate {
delegate.userNotificationCenter(self.center, failedToSheduleNotificationForIdentifier: self.identifier, withError: error)
}
}
}
}
| mit | 0043bd97582941e9d4b3ae61c78e2142 | 34 | 152 | 0.710599 | 5.479798 | false | false | false | false |
RMizin/PigeonMessenger-project | FalconMessenger/Supporting Files/UIComponents/INSPhotosGallery/INSScalingImageView.swift | 1 | 4316 | //
// INSScalingImageView.swift
// INSPhotoViewer
//
// Created by Michal Zaborowski on 28.02.2016.
// Copyright © 2016 Inspace Labs Sp z o. o. Spółka Komandytowa. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this library except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import UIKit
private func < <T : Comparable>(lhs: T?, rhs: T?) -> Bool {
switch (lhs, rhs) {
case let (l?, r?):
return l < r
case (nil, _?):
return true
default:
return false
}
}
class INSScalingImageView: UIScrollView {
lazy var imageView: UIImageView = {
let imageView = UIImageView(frame: self.bounds)
self.addSubview(imageView)
return imageView
}()
var image: UIImage? {
didSet {
updateImage(image)
}
}
override var frame: CGRect {
didSet {
updateZoomScale()
centerScrollViewContents()
}
}
override init(frame: CGRect) {
super.init(frame: frame)
setupImageScrollView()
updateZoomScale()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setupImageScrollView()
updateZoomScale()
}
override func didAddSubview(_ subview: UIView) {
super.didAddSubview(subview)
centerScrollViewContents()
}
private func setupImageScrollView() {
showsVerticalScrollIndicator = false
showsHorizontalScrollIndicator = false;
bouncesZoom = true;
decelerationRate = UIScrollView.DecelerationRate.fast;
}
func centerScrollViewContents() {
var horizontalInset: CGFloat = 0;
var verticalInset: CGFloat = 0;
if (contentSize.width < bounds.width) {
horizontalInset = (bounds.width - contentSize.width) * 0.5;
}
if (self.contentSize.height < bounds.height) {
verticalInset = (bounds.height - contentSize.height) * 0.5;
}
if (window?.screen.scale < 2.0) {
horizontalInset = floor(horizontalInset);
verticalInset = floor(verticalInset);
}
// Use `contentInset` to center the contents in the scroll view. Reasoning explained here: http://petersteinberger.com/blog/2013/how-to-center-uiscrollview/
self.contentInset = UIEdgeInsets(top: verticalInset, left: horizontalInset, bottom: verticalInset, right: horizontalInset);
}
private func updateImage(_ image: UIImage?) {
let size = image?.size ?? CGSize.zero
imageView.transform = CGAffineTransform.identity
imageView.image = image
imageView.frame = CGRect(origin: CGPoint.zero, size: size)
self.contentSize = size
updateZoomScale()
centerScrollViewContents()
}
private func updateZoomScale() {
if let image = imageView.image {
let scrollViewFrame = self.bounds
let scaleWidth = scrollViewFrame.size.width / image.size.width
let scaleHeight = scrollViewFrame.size.height / image.size.height
let minimumScale = min(scaleWidth, scaleHeight)
self.minimumZoomScale = minimumScale
self.maximumZoomScale = max(minimumScale, self.maximumZoomScale)
self.zoomScale = minimumZoomScale
// scrollView.panGestureRecognizer.enabled is on by default and enabled by
// viewWillLayoutSubviews in the container controller so disable it here
// to prevent an interference with the container controller's pan gesture.
//
// This is enabled in scrollViewWillBeginZooming so panning while zoomed-in
// is unaffected.
self.panGestureRecognizer.isEnabled = false
}
}
}
| gpl-3.0 | d7376f37af616255e9975a1f3760bda1 | 31.923664 | 164 | 0.631811 | 4.934783 | false | false | false | false |
Johnykutty/SwiftLint | Source/SwiftLintFramework/Rules/NumberSeparatorRuleExamples.swift | 2 | 2753 | //
// NumberSeparatorRuleExamples.swift
// SwiftLint
//
// Created by Marcelo Fabri on 12/29/16.
// Copyright © 2016 Realm. All rights reserved.
//
import Foundation
internal struct NumberSeparatorRuleExamples {
static let nonTriggeringExamples: [String] = {
return ["-", "+", ""].flatMap { (sign: String) -> [String] in
[
"let foo = \(sign)100",
"let foo = \(sign)1_000",
"let foo = \(sign)1_000_000",
"let foo = \(sign)1.000_1",
"let foo = \(sign)1_000_000.000_000_1",
"let binary = \(sign)0b10000",
"let binary = \(sign)0b1000_0001",
"let hex = \(sign)0xA",
"let hex = \(sign)0xAA_BB",
"let octal = \(sign)0o21",
"let octal = \(sign)0o21_1",
"let exp = \(sign)1_000_000.000_000e2"
]
}
}()
static let swift3TriggeringExamples = triggeringExamples(signs: ["↓-", "+↓", "↓"])
static let swift2TriggeringExamples = triggeringExamples(signs: ["-↓", "+↓", "↓"])
static let swift3Corrections = corrections(signs: [("↓-", "-"), ("+↓", "+"), ("↓", "")])
static let swift2Corrections = corrections(signs: [("-↓", "-"), ("+↓", "+"), ("↓", "")])
private static func triggeringExamples(signs: [String]) -> [String] {
return signs.flatMap { (sign: String) -> [String] in
[
"let foo = \(sign)10_0",
"let foo = \(sign)1000",
"let foo = \(sign)1000e2",
"let foo = \(sign)1000E2",
"let foo = \(sign)1__000",
"let foo = \(sign)1.0001",
"let foo = \(sign)1_000_000.000000_1",
"let foo = \(sign)1000000.000000_1"
]
}
}
private static func corrections(signs: [(String, String)]) -> [String: String] {
var result = [String: String]()
for (violation, sign) in signs {
result["let foo = \(violation)10_0"] = "let foo = \(sign)100"
result["let foo = \(violation)1000"] = "let foo = \(sign)1_000"
result["let foo = \(violation)1000e2"] = "let foo = \(sign)1_000e2"
result["let foo = \(violation)1000E2"] = "let foo = \(sign)1_000E2"
result["let foo = \(violation)1__000"] = "let foo = \(sign)1_000"
result["let foo = \(violation)1.0001"] = "let foo = \(sign)1.000_1"
result["let foo = \(violation)1_000_000.000000_1"] = "let foo = \(sign)1_000_000.000_000_1"
result["let foo = \(violation)1000000.000000_1"] = "let foo = \(sign)1_000_000.000_000_1"
}
return result
}
}
| mit | 6b69aa989444fab63c13a4bb4b188195 | 36.888889 | 103 | 0.48937 | 3.529107 | false | false | false | false |
mattrajca/swift-corelibs-foundation | Foundation/URLSession/BodySource.swift | 4 | 9335 | // Foundation/URLSession/BodySource.swift - URLSession & libcurl
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
// -----------------------------------------------------------------------------
///
/// These are libcurl helpers for the URLSession API code.
/// - SeeAlso: https://curl.haxx.se/libcurl/c/
/// - SeeAlso: URLSession.swift
///
// -----------------------------------------------------------------------------
import CoreFoundation
import Dispatch
/// Turn `Data` into `DispatchData`
internal func createDispatchData(_ data: Data) -> DispatchData {
//TODO: Avoid copying data
let buffer = UnsafeRawBufferPointer(start: data._backing.bytes,
count: data.count)
return DispatchData(bytes: buffer)
}
/// Copy data from `DispatchData` into memory pointed to by an `UnsafeMutableBufferPointer`.
internal func copyDispatchData<T>(_ data: DispatchData, infoBuffer buffer: UnsafeMutableBufferPointer<T>) {
precondition(data.count <= (buffer.count * MemoryLayout<T>.size))
_ = data.copyBytes(to: buffer)
}
/// Split `DispatchData` into `(head, tail)` pair.
internal func splitData(dispatchData data: DispatchData, atPosition position: Int) -> (DispatchData,DispatchData) {
return (data.subdata(in: 0..<position), data.subdata(in: position..<data.count))
}
/// A (non-blocking) source for body data.
internal protocol _BodySource: class {
/// Get the next chunck of data.
///
/// - Returns: `.data` until the source is exhausted, at which point it will
/// return `.done`. Since this is non-blocking, it will return `.retryLater`
/// if no data is available at this point, but will be available later.
func getNextChunk(withLength length: Int) -> _BodySourceDataChunk
}
internal enum _BodySourceDataChunk {
case data(DispatchData)
/// The source is depleted.
case done
/// Retry later to get more data.
case retryLater
case error
}
/// A body data source backed by `DispatchData`.
internal final class _BodyDataSource {
var data: DispatchData!
init(data: DispatchData) {
self.data = data
}
}
extension _BodyDataSource : _BodySource {
enum _Error : Error {
case unableToRewindData
}
func getNextChunk(withLength length: Int) -> _BodySourceDataChunk {
let remaining = data.count
if remaining == 0 {
return .done
} else if remaining <= length {
let r: DispatchData! = data
data = DispatchData.empty
return .data(r)
} else {
let (chunk, remainder) = splitData(dispatchData: data, atPosition: length)
data = remainder
return .data(chunk)
}
}
}
/// A HTTP body data source backed by a file.
///
/// This allows non-blocking streaming of file data to the remote server.
///
/// The source reads data using a `DispatchIO` channel, and hence reading
/// file data is non-blocking. It has a local buffer that it fills as calls
/// to `getNextChunk(withLength:)` drain it.
///
/// - Note: Calls to `getNextChunk(withLength:)` and callbacks from libdispatch
/// should all happen on the same (serial) queue, and hence this code doesn't
/// have to be thread safe.
internal final class _BodyFileSource {
fileprivate let fileURL: URL
fileprivate let channel: DispatchIO
fileprivate let workQueue: DispatchQueue
fileprivate let dataAvailableHandler: () -> Void
fileprivate var hasActiveReadHandler = false
fileprivate var availableChunk: _Chunk = .empty
/// Create a new data source backed by a file.
///
/// - Parameter fileURL: the file to read from
/// - Parameter workQueue: the queue that it's safe to call
/// `getNextChunk(withLength:)` on, and that the `dataAvailableHandler`
/// will be called on.
/// - Parameter dataAvailableHandler: Will be called when data becomes
/// available. Reading data is done in a non-blocking way, such that
/// no data may be available even if there's more data in the file.
/// if `getNextChunk(withLength:)` returns `.retryLater`, this handler
/// will be called once data becomes available.
init(fileURL: URL, workQueue: DispatchQueue, dataAvailableHandler: @escaping () -> Void) {
guard fileURL.isFileURL else { fatalError("The body data URL must be a file URL.") }
self.fileURL = fileURL
self.workQueue = workQueue
self.dataAvailableHandler = dataAvailableHandler
var fileSystemRepresentation: UnsafePointer<Int8>! = nil
fileURL.withUnsafeFileSystemRepresentation {
fileSystemRepresentation = $0
}
guard let channel = DispatchIO(type: .stream, path: fileSystemRepresentation,
oflag: O_RDONLY, mode: 0, queue: workQueue,
cleanupHandler: {_ in }) else {
fatalError("Cant create DispatchIO channel")
}
self.channel = channel
self.channel.setLimit(highWater: CFURLSessionMaxWriteSize)
}
fileprivate enum _Chunk {
/// Nothing has been read, yet
case empty
/// An error has occured while reading
case errorDetected(Int)
/// Data has been read
case data(DispatchData)
/// All data has been read from the file (EOF).
case done(DispatchData?)
}
}
fileprivate extension _BodyFileSource {
fileprivate var desiredBufferLength: Int { return 3 * CFURLSessionMaxWriteSize }
/// Enqueue a dispatch I/O read to fill the buffer.
///
/// - Note: This is a no-op if the buffer is full, or if a read operation
/// is already enqueued.
fileprivate func readNextChunk() {
// libcurl likes to use a buffer of size CFURLSessionMaxWriteSize, we'll
// try to keep 3 x of that around in the `chunk` buffer.
guard availableByteCount < desiredBufferLength else { return }
guard !hasActiveReadHandler else { return } // We're already reading
hasActiveReadHandler = true
let lengthToRead = desiredBufferLength - availableByteCount
channel.read(offset: 0, length: lengthToRead, queue: workQueue) { (done: Bool, data: DispatchData?, errno: Int32) in
let wasEmpty = self.availableByteCount == 0
self.hasActiveReadHandler = !done
switch (done, data, errno) {
case (true, _, errno) where errno != 0:
self.availableChunk = .errorDetected(Int(errno))
case (true, .some(let d), 0) where d.isEmpty:
self.append(data: d, endOfFile: true)
case (true, .some(let d), 0):
self.append(data: d, endOfFile: false)
case (false, .some(let d), 0):
self.append(data: d, endOfFile: false)
default:
fatalError("Invalid arguments to read(3) callback.")
}
if wasEmpty && (0 < self.availableByteCount) {
self.dataAvailableHandler()
}
}
}
fileprivate func append(data: DispatchData, endOfFile: Bool) {
switch availableChunk {
case .empty:
availableChunk = endOfFile ? .done(data) : .data(data)
case .errorDetected:
break
case .data(var oldData):
oldData.append(data)
availableChunk = endOfFile ? .done(oldData) : .data(oldData)
case .done:
fatalError("Trying to append data, but end-of-file was already detected.")
}
}
fileprivate var availableByteCount: Int {
switch availableChunk {
case .empty: return 0
case .errorDetected: return 0
case .data(let d): return d.count
case .done(.some(let d)): return d.count
case .done(.none): return 0
}
}
}
extension _BodyFileSource : _BodySource {
func getNextChunk(withLength length: Int) -> _BodySourceDataChunk {
switch availableChunk {
case .empty:
readNextChunk()
return .retryLater
case .errorDetected:
return .error
case .data(let data):
let l = min(length, data.count)
let (head, tail) = splitData(dispatchData: data, atPosition: l)
availableChunk = tail.isEmpty ? .empty : .data(tail)
readNextChunk()
if head.isEmpty {
return .retryLater
} else {
return .data(head)
}
case .done(.some(let data)):
let l = min(length, data.count)
let (head, tail) = splitData(dispatchData: data, atPosition: l)
availableChunk = tail.isEmpty ? .done(nil) : .done(tail)
if head.isEmpty {
return .done
} else {
return .data(head)
}
case .done(.none):
return .done
}
}
}
| apache-2.0 | 154c2e915de4390d6bf3de4f7b355540 | 37.258197 | 124 | 0.608034 | 4.621287 | false | false | false | false |
chuck1991/SpriteKitExample | SpriteKitExample/ArcheryScene.swift | 1 | 5888 | //
// ArcheryScene.swift
// SpriteKitExample
//
// Created by Chuck on 1/20/16.
// Copyright © 2016 kaichu. All rights reserved.
//
import UIKit
import Darwin
import SpriteKit
class ArcheryScene: SKScene, SKPhysicsContactDelegate {
private var ballCount = 20
private var score = 0
private struct CategoryMask{
static let Arrow: UInt32 = 0x1 << 0
static let Ball: UInt32 = 0x1 << 1
}
override func didMoveToView(view: SKView) {
self.physicsWorld.gravity = CGVectorMake(0.0, -1.0)
self.physicsWorld.contactDelegate = self
let releaseBall = SKAction.sequence([SKAction.runBlock{
let ballNode = self.createBallNode()
self.addChild(ballNode)},
SKAction.waitForDuration(1.0)]
)
let releaseAllBallsAction = SKAction.repeatAction(releaseBall, count: self.ballCount)
self.runAction(releaseAllBallsAction){
self.runAction(SKAction.sequence([
SKAction.waitForDuration(4.0),
SKAction.runBlock{
self.gameOver()
}
]))
}
}
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
if let archerNode = self.childNodeWithName("archerNode"){
if let animatorArchor = SKAction(named: "animatorArchor"){
let arrowNodeAction = SKAction.runBlock{
let arrowNode = self.createArrowNode()
self.addChild(arrowNode)
arrowNode.physicsBody?.applyImpulse(CGVectorMake(60.0, 0.0))
}
let archerActionSequence = SKAction.sequence([animatorArchor,arrowNodeAction])
archerNode.runAction(archerActionSequence)
}
}
}
private func createArrowNode() -> SKSpriteNode{
let archerNode = self.childNodeWithName("archerNode")
let archerNodePosition = archerNode?.position
let archerNodeWidth = archerNode?.frame.size.width
let arrowNode = SKSpriteNode(imageNamed: "ArrowTexture.jpg")
arrowNode.name = "arrowNode"
arrowNode.position = CGPointMake(archerNodePosition!.x + archerNodeWidth!, archerNodePosition!.y)
arrowNode.physicsBody = SKPhysicsBody(rectangleOfSize: arrowNode.frame.size)
arrowNode.physicsBody?.categoryBitMask = CategoryMask.Arrow
arrowNode.physicsBody?.contactTestBitMask = CategoryMask.Arrow | CategoryMask.Ball
arrowNode.physicsBody?.collisionBitMask = CategoryMask.Arrow | CategoryMask.Ball
arrowNode.physicsBody?.affectedByGravity = false
arrowNode.physicsBody?.usesPreciseCollisionDetection = true
return arrowNode
}
private func createBallNode() -> SKSpriteNode{
let ballNode = SKSpriteNode(imageNamed: "BallTexture.jpg")
ballNode.name = "ballNode"
ballNode.position = CGPointMake(randomRange(100.0, high: self.size.width/2), self.size.height-50)
ballNode.physicsBody = SKPhysicsBody(circleOfRadius: ballNode.size.width/2)
ballNode.physicsBody?.categoryBitMask = CategoryMask.Ball
ballNode.physicsBody?.usesPreciseCollisionDetection = true
return ballNode
}
private func createGameOverLabel() -> SKLabelNode{
let gameOverLabelNode = SKLabelNode(fontNamed: "Bradley Hand")
gameOverLabelNode.name = "gameOverLabelNode"
gameOverLabelNode.text = "Score: \(self.score)"
gameOverLabelNode.fontColor = UIColor.blueColor()
gameOverLabelNode.fontSize = 64
gameOverLabelNode.position = CGPointMake(CGRectGetMidX(self.frame),CGRectGetMidY(self.frame))
return gameOverLabelNode
}
func gameOver(){
let gameOverLabelNode = self.createGameOverLabel()
self.addChild(gameOverLabelNode)
let showLabelNodeAction = SKAction.sequence([SKAction.waitForDuration(3.0),SKAction.fadeOutWithDuration(1.0)])
let returnToWelcomeAction = SKAction.runBlock{
let welcomeScene = SKScene(fileNamed: "GameScene")
let revealWelcomeSceneTransition = SKTransition.revealWithDirection(.Down, duration: 1.0)
self.scene!.view?.presentScene(welcomeScene!, transition: revealWelcomeSceneTransition)
}
self.runAction(SKAction.sequence([showLabelNodeAction,returnToWelcomeAction]))
}
private func randomRange(low: CGFloat, high: CGFloat) -> CGFloat{
return CGFloat(arc4random_uniform(UInt32(high)-UInt32(low)) + UInt32(low))
}
}
extension ArcheryScene{
func didBeginContact(contact: SKPhysicsContact) {
let ballNode = contact.bodyB.node as! SKSpriteNode
if(contact.bodyA.categoryBitMask == CategoryMask.Arrow && contact.bodyB.categoryBitMask == CategoryMask.Ball){
let contactPoint = contact.contactPoint
let contactY = contactPoint.y
//let ballNodePositionX = ballNode.position.x
let ballNodePositionY = ballNode.position.y
let margin = ballNode.frame.height/2 - 5
if(contactY > (ballNodePositionY - margin)) && (contactY < (ballNodePositionY + margin)){
ballNode.removeFromParent()
if let burstBallParticlePath = NSBundle.mainBundle().pathForResource("BurstBallParticle", ofType: "sks"){
let burstBallParticle = NSKeyedUnarchiver.unarchiveObjectWithFile(burstBallParticlePath) as! SKEmitterNode
burstBallParticle.position = contactPoint
self.addChild(burstBallParticle)
let soundAction = SKAction(named: "burstBallAudio")
burstBallParticle.runAction(soundAction!)
}
self.score++
}
}
}
}
| mit | c9cb1565e7105008bdcbc6e8ab07c37e | 42.932836 | 126 | 0.652285 | 4.829368 | false | false | false | false |
practicalswift/swift | validation-test/Evolution/Inputs/global_change_size.swift | 40 | 1618 | #if BEFORE
var global: Int = 0
public struct ChangeEmptyToNonEmpty {
public init() {}
public var property: Int {
get { return global }
set { global = newValue }
}
}
#else
public struct ChangeEmptyToNonEmpty {
public init() {
property = 0
}
public var property: Int
}
#endif
#if BEFORE
public struct ChangeSize {
public init() {
count = 0
}
public var count: Int
public func validate() -> Bool {
return true
}
}
#else
public struct ChangeSize {
public init() {
_count = 0
_sign = 0
}
public var count: Int {
get { return _count * _sign }
set {
if newValue < 0 {
_count = -newValue
_sign = -1
} else {
_count = newValue
_sign = 1
}
}
}
private var _count: Int
private var _sign: Int
public func validate() -> Bool {
return (padding1 == 17 &&
padding2 == -12 &&
padding3 == 108 &&
padding4 == -7592)
}
// Some padding to grow the struct beyond what a fixed-size buffer
// can hold for a global. Use it as a canary to catch any memory
// corruption issues.
public var padding1: Int = 17
public var padding2: Int = -12
public var padding3: Int = 108
public var padding4: Int = -7592
}
#endif
// Test internal global variable hidden behind a public transparent
// interface
@usableFromInline var versionedGlobal: ChangeSize = ChangeSize()
@_transparent public func getVersionedGlobal() -> ChangeSize {
return versionedGlobal
}
@_transparent public func setVersionedGlobal(_ c: Int) {
versionedGlobal.count = c
}
| apache-2.0 | 362241a18f41811bc7e9f76b0c56801d | 16.212766 | 68 | 0.616811 | 3.816038 | false | false | false | false |
PezHead/tiny-tennis-scoreboard | Tiny Tennis/Game.swift | 1 | 4856 | //
// Game.swift
// Tiny Tennis
//
// Created by David Bireta on 10/15/16.
// Copyright © 2016 David Bireta. All rights reserved.
//
import TableTennisAPI
struct Game {
// MARK:- Properties
var redScore = 0
var blueScore = 0
var redPlayers = [Champion]()
var bluePlayers = [Champion]()
var currentServer: Champion {
var server = firstServer
var receiver = firstReceiver
for total in 0...(redScore+blueScore) {
if (total > 0 && total <= 20 && total % 2 == 0) || (total > 20) {
let oldServer = server
server = receiver
receiver = oldServer
if redPlayers.count == 2 {
// Swap
if receiver == redPlayers.first! {
receiver = redPlayers.last!
} else if receiver == redPlayers.last! {
receiver = redPlayers.first!
} else if receiver == bluePlayers.first {
receiver = bluePlayers.last!
} else if receiver == bluePlayers.last {
receiver = bluePlayers.first!
}
}
}
}
return server
}
var currentReceiver: Champion {
var server = firstServer
var receiver = firstReceiver
for total in 0...(redScore+blueScore) {
if (total > 0 && total <= 20 && total % 2 == 0) || (total > 20) {
let oldServer = server
server = receiver
receiver = oldServer
if redPlayers.count == 2 {
// Swap
if receiver == redPlayers.first! {
receiver = redPlayers.last!
} else if receiver == redPlayers.last! {
receiver = redPlayers.first!
} else if receiver == bluePlayers.first {
receiver = bluePlayers.last!
} else if receiver == bluePlayers.last {
receiver = bluePlayers.first!
}
}
}
}
return receiver
}
var winningTeam: Team? {
if redScore >= 11 && (redScore - blueScore) >= 2 {
return .red
} else if blueScore >= 11 && (blueScore - redScore) >= 2 {
return .blue
} else {
return nil
}
}
// MARK: - Private Properties
fileprivate var pointTracker = [Point]()
fileprivate let firstServer: Champion
fileprivate let firstReceiver: Champion
fileprivate var firstServingTeam: Team {
if redPlayers.contains(firstServer) {
return .red
} else {
return .blue
}
}
// MARK:- Public Methods
init(firstServer: Champion, firstReceiver: Champion, redPlayers: [Champion], bluePlayers: [Champion]) {
self.firstServer = firstServer
self.firstReceiver = firstReceiver
self.redPlayers = redPlayers
self.bluePlayers = bluePlayers
}
mutating func addPoint(_ team: Team) {
switch team {
case .red:
let pointWinner = redPlayers.contains(currentServer) ? currentServer : currentReceiver
pointTracker.append(Point(server: currentServer, receiver: currentReceiver, winner: pointWinner, order: pointTracker.count))
redScore += 1
case .blue:
let pointWinner = bluePlayers.contains(currentServer) ? currentServer : currentReceiver
pointTracker.append(Point(server: currentServer, receiver: currentReceiver, winner: pointWinner, order: pointTracker.count))
blueScore += 1
}
}
mutating func subtractPoint(_ team: Team) {
switch team {
case .red:
redScore -= 1
case .blue:
blueScore -= 1
}
pointTracker.removeLast()
}
mutating func undoPoint() {
if let team = pointTracker.popLast() {
if redPlayers.contains(team.winner) {
redScore -= 1
} else {
blueScore -= 1
}
}
}
func jsonData() -> [String:Any] {
let pointJSON = pointTracker.map { $0.jsonData() }
return [
"winner": redScore > blueScore ? redPlayers.first!.id : bluePlayers.first!.id,
"winningScore": redScore > blueScore ? redScore : blueScore,
"loser": redScore > blueScore ? bluePlayers.first!.id : redPlayers.first!.id,
"losingScore": redScore > blueScore ? blueScore : redScore,
"points": pointJSON
]
}
}
| mit | 8b8765424769b6173887bfe0d6768bd9 | 31.152318 | 136 | 0.508136 | 4.908999 | false | false | false | false |
yangchenghu/actor-platform | actor-apps/app-ios/ActorApp/Controllers/Discover/Cells/PublicCell.swift | 5 | 2703 | //
// Copyright (c) 2014-2015 Actor LLC. <https://actor.im>
//
import Foundation
class PublicCell: UITableViewCell {
let avatarView = AvatarView(frameSize: 48, type: .Rounded)
let title: UILabel = UILabel()
let desc: UILabel = UILabel()
let members: UILabel = UILabel()
let separatorView = TableViewSeparator(color: MainAppTheme.list.separatorColor)
var group: ACPublicGroup!
init() {
super.init(style: UITableViewCellStyle.Default, reuseIdentifier: "cell")
title.font = UIFont.mediumSystemFontOfSize(19)
title.textColor = MainAppTheme.list.dialogTitle
members.font = UIFont.mediumSystemFontOfSize(19)
members.textColor = MainAppTheme.list.dialogTitle
desc.font = UIFont.systemFontOfSize(16)
desc.textColor = MainAppTheme.list.dialogText
desc.lineBreakMode = NSLineBreakMode.ByWordWrapping
desc.numberOfLines = 2
contentView.addSubview(avatarView)
contentView.addSubview(title)
contentView.addSubview(members)
contentView.addSubview(desc)
contentView.addSubview(separatorView)
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func bind(group: ACPublicGroup, isLast: Bool) {
self.group = group
title.text = self.group.getTitle()
desc.text = self.group.getDescription()
members.text = "\(self.group.getMembers()) members"
if self.group.getFriends() > 0 {
members.text = members.text! + " and \(self.group.getFriends()) friends"
}
avatarView.bind(self.group.getTitle(), id: self.group.getId(), avatar: self.group.getAvatar())
separatorView.hidden = isLast
}
override func layoutSubviews() {
super.layoutSubviews()
let width = self.contentView.frame.width;
let leftPadding = CGFloat(76);
let padding = CGFloat(14);
avatarView.frame = CGRectMake(padding, 18, 48, 48);
title.frame = CGRectMake(leftPadding, 18, width - leftPadding - /*paddingRight*/padding, 20);
desc.frame = CGRectMake(leftPadding, 40, width - leftPadding - /*paddingRight*/padding, 60)
desc.sizeToFit()
members.frame = CGRectMake(leftPadding, 80, width - leftPadding - /*paddingRight*/padding, 20)
//members.sizeToFit()
// members.frame = CGRectMake(width - members.bounds.width - padding, 80, members.bounds.width, 20)
separatorView.frame = CGRectMake(leftPadding, 103.5, width, 0.5);
}
} | mit | 1d4693272ab6121f80f89118986dd143 | 33.666667 | 107 | 0.628931 | 4.709059 | false | false | false | false |
sadeslandes/SplitScreen | OSX/SplitScreen/SnapLayout.swift | 1 | 6777 | //
// SnapLayout.swift
// SplitScreen
//
// Created by Evan Thompson on 10/13/15.
// Copyright © 2015 SplitScreen. All rights reserved.
//
import Foundation
import AppKit
class SnapLayout {
var snap_points = [SnapPoint]()
/**
Creates `SnapPoint` objects and adds them to the SnapLayout in order to make it behave
according the standard layout
*/
func standard_layout(){
HEIGHT = Int((NSScreen.main()?.frame.height)!)
WIDTH = Int((NSScreen.main()?.frame.width)!)
// Hardcoded Windows 10 Aero Snap
let top_left: SnapPoint = SnapPoint.init(screen_dim: (WIDTH, HEIGHT),
snap_dim: (WIDTH/2, HEIGHT/2),
snap_loc: (0, 0))
top_left.add_snap_point(first: (0, HEIGHT), second: (0 ,HEIGHT))
snap_points.append(top_left)
let bot_left: SnapPoint = SnapPoint.init(screen_dim: (WIDTH, HEIGHT),
snap_dim: (WIDTH/2, HEIGHT/2),
snap_loc: (0, HEIGHT/2))
bot_left.add_snap_point(first: (0, 0), second: (0, 0))
snap_points.append(bot_left)
let left_side: SnapPoint = SnapPoint.init(screen_dim: (WIDTH, HEIGHT),
snap_dim: (WIDTH/2, HEIGHT),
snap_loc: (0, 0))
left_side.add_snap_point(first: (0, 1), second: (0, HEIGHT-1))
snap_points.append(left_side)
let top_right: SnapPoint = SnapPoint.init(screen_dim: (WIDTH, HEIGHT),
snap_dim: (WIDTH/2, HEIGHT/2),
snap_loc: (WIDTH/2, 0))
top_right.add_snap_point(first: (WIDTH, HEIGHT), second: (WIDTH, HEIGHT))
snap_points.append(top_right)
let bot_right: SnapPoint = SnapPoint.init(screen_dim: (WIDTH, HEIGHT),
snap_dim: (WIDTH/2, HEIGHT/2),
snap_loc: (WIDTH/2, HEIGHT/2))
bot_right.add_snap_point(first: (WIDTH, 0), second: (WIDTH, 0))
snap_points.append(bot_right)
let right_side: SnapPoint = SnapPoint.init(screen_dim: (WIDTH, HEIGHT),
snap_dim: (WIDTH/2, HEIGHT),
snap_loc: (WIDTH/2, 0))
right_side.add_snap_point(first: (WIDTH, 1), second: (WIDTH, HEIGHT-1))
snap_points.append(right_side)
let top: SnapPoint = SnapPoint.init(screen_dim: (WIDTH, HEIGHT),
snap_dim: (WIDTH, HEIGHT),
snap_loc: (0, 0))
top.add_snap_point(first: (1, HEIGHT), second: (WIDTH-1, HEIGHT))
snap_points.append(top)
}
/**
Creates `SnapPoint` objects and adds them to the SnapLayout in order to make it behave
according the horizontal layout
*/
func horizontal_layout(){
let left_upper: SnapPoint = SnapPoint.init(screen_dim: (WIDTH, HEIGHT),
snap_dim: (WIDTH, HEIGHT/2),
snap_loc: (0, 0))
left_upper.add_snap_point(first: (0, HEIGHT/2), second: (0, HEIGHT))
snap_points.append(left_upper)
let left_lower: SnapPoint = SnapPoint.init(screen_dim: (WIDTH, HEIGHT),
snap_dim: (WIDTH, HEIGHT/2),
snap_loc: (0, HEIGHT/2))
left_lower.add_snap_point(first: (0, 0), second: (0, HEIGHT/2))
snap_points.append(left_lower)
let right_upper: SnapPoint = SnapPoint.init(screen_dim: (WIDTH, HEIGHT),
snap_dim: (WIDTH, HEIGHT/2),
snap_loc: (0, 0))
right_upper.add_snap_point(first: (WIDTH, HEIGHT/2), second: (WIDTH, HEIGHT))
snap_points.append(right_upper)
let right_lower: SnapPoint = SnapPoint.init(screen_dim: (WIDTH, HEIGHT),
snap_dim: (WIDTH, HEIGHT/2),
snap_loc: (0, HEIGHT/2))
right_lower.add_snap_point(first: (WIDTH, 0), second: (WIDTH, HEIGHT/2))
snap_points.append(right_lower)
}
/**
Loads a file at `file_path` with preset hardpoints
- Parameter file_path: `NSString` that corresponds to a file with preset hardpoints
*/
func load(_ template_name: NSString) {
// Refreshes the snap points
snap_points.removeAll()
if(template_name == "standard") {
standard_layout()
} else if(template_name == "horizontal") {
horizontal_layout()
}
}
/**
Checks to see if the given `x` and `y` points are hardpoints
- Parameter x: Screen's x coordinate that will be compared
- Paramter y: Screen's y coordinate that will be compared
- Returns: `true` or `false` if `x` and `y` both compare to an existing hardpoint
*/
func is_hardpoint(_ x: CGFloat, y: CGFloat) -> Bool {
let xpos:Int = Int(x + 0.5)
let ypos:Int = Int(y + 0.5)
for i in 0 ..< snap_points.count {
if snap_points[i].check_point(x: xpos, y: ypos) {
return true
}
}
return false
}
/**
Get the new dimensions for a dragged window
- Parameter x: `CGFloat` that corresponds to screen x coordinate of mouse
- Parameter y: `CGFloat` that corresponds to screen y coordinate of mouse
- Returns: `tuple` of 4 `Ints` that correspond to the dragged windows four corners
*/
func get_snap_dimensions(_ x: CGFloat, y: CGFloat) ->(Int,Int,Int,Int) {
let x_i:Int = Int(x + 0.5)
let y_i:Int = Int(y + 0.5)
for i in 0 ..< snap_points.count {
if snap_points[i].check_point(x: x_i, y: y_i) {
let (x_snap, y_snap) = snap_points[i].get_snap_location()
let (x_dim, y_dim) = snap_points[i].get_snap_dimensions()
return (x_snap, y_snap, x_dim, y_dim)
}
}
// Should never reach this point
return (-1,-1,-1,-1)
}
/**
Creates and returns a string representation of the SnapLayout
- Returns: `String` which represents the SnapLayout
*/
func toString() -> String {
var retString: String = String()
for snap_point in snap_points {
retString = retString + snap_point.to_string()
}
return retString
}
let menu = NSApplication.shared().mainMenu
fileprivate var HEIGHT: Int = Int((NSScreen.main()?.frame.height)!)
fileprivate var WIDTH: Int = Int((NSScreen.main()?.frame.width)!)
}
| apache-2.0 | e83413728f9b3f3c9517705c7536e303 | 34.47644 | 88 | 0.530697 | 3.725124 | false | false | false | false |
gmission/gmission-ios | gmission/gmission/ImageHitVC.swift | 1 | 7724 | //
// CampaignList.swift
// gmission
//
// Created by CHEN Zhao on 4/12/2015.
// Copyright © 2015 CHEN Zhao. All rights reserved.
//
import UIKit
import SwiftyJSON
import WebImage
class ImageHitVM:HitVM{
}
class ImageAnswerCell:UITableViewCell{
@IBOutlet weak var answerImageView: UIImageView!
@IBOutlet weak var createdOnLabel: UILabel!
@IBOutlet weak var workerNameLabel: UILabel!
@IBOutlet weak var answerImageButton: UIButton!
weak var hitVC: HitVC!
internal var aspectConstraint : NSLayoutConstraint? {
didSet {
if oldValue != nil {
answerImageView.removeConstraint(oldValue!)
}
if aspectConstraint != nil {
answerImageView.addConstraint(aspectConstraint!)
}
}
}
override func prepareForReuse() {
super.prepareForReuse()
aspectConstraint = nil
}
@IBAction func fullScreenImage(sender: AnyObject) {
let oldImage = (self.answerImageButton.imageView?.image)!
let image = UIImage(CGImage: (oldImage.CGImage)!, scale: 1.0, orientation: oldImage.imageOrientation)
hitVC.showFullImageView(image)
}
}
class ImageHitVC: HitVC, UINavigationControllerDelegate, UIImagePickerControllerDelegate {
// @IBOutlet weak var textView: UITextView!
@IBOutlet weak var imageView: UIImageView!
var imageVM:ImageHitVM {return vm as! ImageHitVM}
@IBOutlet weak var viewForWorker: UIView!
@IBOutlet weak var answerTableView: UITableView!
@IBOutlet weak var requesterBar: UIToolbar!
// @IBOutlet weak var hitStatusLabel: UILabel!
// @IBOutlet weak var hitCreatedOn: UILabel!
@IBOutlet weak var closeBtn: UIBarButtonItem!
let binder:TableBinder<Answer> = TableBinder<Answer>()
override func viewDidLoad() {
super.viewDidLoad()
// answerTableView.rowHeight = UITableViewAutomaticDimension
let footerView = UIView(frame: CGRect(x: 0, y: 0, width: 100, height: 50))
footerView.backgroundColor = UIColor.clearColor()
answerTableView.tableFooterView = footerView
self.binder.bind(answerTableView, items: self.vm.answers, refreshFunc: vm.loadAnswers)
self.binder.cellFunc = { indexPath in
let answer = self.vm.answers[indexPath.row]
let cell = self.answerTableView.dequeueReusableCellWithIdentifier("imageAnswerCell", forIndexPath: indexPath) as! ImageAnswerCell
Attachment.getOne(answer.att_id, done: { (att:Attachment) -> Void in
cell.answerImageButton.simpleSetImage(att.imageURL)
})
cell.workerNameLabel.text = ""
cell.createdOnLabel.text = NSDateToLocalTimeString(HKTimeStringToNSDate(answer.created_on))
cell.hitVC = self
return cell
}
self.showHUD("Loading...")
binder.refreshThen { () -> Void in
self.hideHUD()
self.requesterBar.hidden = !self.vm.isRequester
if self.vm.hit.status == "closed"{
self.closeBtn.enabled = false
self.viewForWorker.hidden = true
self.answerTableView.hidden = false
self.navigationItem.rightBarButtonItem?.title = "Closed"
self.navigationItem.rightBarButtonItem?.enabled = false
}else if self.vm.hasAnswered{
print("answered")
self.viewForWorker.hidden = true
self.answerTableView.hidden = false
self.navigationItem.rightBarButtonItem?.title = "Answered"
self.navigationItem.rightBarButtonItem?.enabled = false
}else{
print("has not answered")
if self.vm.isRequester{
self.viewForWorker.hidden = true
self.answerTableView.hidden = false
self.navigationItem.rightBarButtonItem?.title = "Requested"
self.navigationItem.rightBarButtonItem?.enabled = false
}else{
self.viewForWorker.hidden = false
self.answerTableView.hidden = true
self.navigationItem.rightBarButtonItem?.title = "Submit"
self.navigationItem.rightBarButtonItem?.enabled = true
}
}
}
}
override func viewDidLayoutSubviews() {
// self.textView.contentOffset = CGPointZero;
}
var imagePicker: UIImagePickerController!
@IBAction func takePhotoClicked(sender: AnyObject) {
imagePicker = UIImagePickerController()
imagePicker.delegate = self
imagePicker.sourceType = .Camera
presentViewController(imagePicker, animated: true, completion: nil)
}
@IBAction func choosePhotoClicked(sender: AnyObject) {
imagePicker = UIImagePickerController()
imagePicker.delegate = self
imagePicker.sourceType = .PhotoLibrary
presentViewController(imagePicker, animated: true, completion: nil)
}
func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
imageView.image = image
imageView.contentMode = .ScaleAspectFit
dismissViewControllerAnimated(true, completion: nil)
}
func imagePickerControllerDidCancel(picker: UIImagePickerController) {
dismissViewControllerAnimated(true, completion: nil)
}
@IBAction override func closeHit(){
print("children close, image")
vm.hit.jsonDict["status"] = "closed"
Hit.postOne(vm.hit) { (hit:Hit) -> Void in
self.vm.hit = hit
self.navigationController?.popViewControllerAnimated(true)
}
}
override func submitAnswer(){
print("children submit answer, image")
if imageView.image == nil{
self.flashHUD("A photo is needed.", 1)
return
}
self.showHUD("Submitting ..")
let imageData = UIImageJPEGRepresentation(imageView.image!, 0.8)!
HTTP.uploadImage(imageData, fileName: "ios.jpg") { (nameFromServer, error) -> () in
if let e = error{
print("upload image error", e)
}else{
let attDict:[String:AnyObject] = ["type":"image", "value":nameFromServer!]
let att = Attachment(jsonDict: JSON(attDict))
Attachment.postOne(att) { (att:Attachment) -> Void in
print("attachment posted")
let answerDict:[String:AnyObject] = ["brief":"", "hit_id":self.vm.hit.id, "type":"image", "attachment_id":att.id,"worker_id":UserManager.currentUser.id]
self.vm.postAnswer(Answer(dict: answerDict)){
print("answer posted")
self.hideHUD()
self.flashHUD("Done!", 1)
self.viewDidLoad()
self.viewWillAppear(true)
}
}
}
}
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
print("segue of campaign")
if segue.identifier == "showHit"{
// let hitVC: HitVC = segue.destinationViewController as! HitVC
// hitVC.vm = HitVM(c: vm.hits[tableView.indexPathForSelectedRow!.row])
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| mit | 8f9271059970a765c6cc014d3301dd60 | 36.129808 | 172 | 0.607665 | 5.128154 | false | false | false | false |
anilkumarbp/swift-sdk-new | src/Subscription/crypt/Cipher.swift | 5 | 1964 | //
// Cipher.swift
// CryptoSwift
//
// Created by Marcin Krzyzanowski on 30/08/14.
// Copyright (c) 2014 Marcin Krzyzanowski. All rights reserved.
//
import Foundation
public enum Cipher {
/**
ChaCha20
:param: key Encryption key
:param: iv Initialization Vector
:returns: Value of Cipher
*/
case ChaCha20(key: [UInt8], iv: [UInt8])
/**
AES
:param: key Encryption key
:param: iv Initialization Vector
:param: blockMode Block mode (CBC by default)
:returns: Value of Cipher
*/
case AES(key: [UInt8], iv: [UInt8], blockMode: CipherBlockMode)
/**
Encrypt message
:param: message Plaintext message
:returns: encrypted message
*/
public func encrypt(bytes: [UInt8]) -> [UInt8]? {
switch (self) {
case .ChaCha20(let key, let iv):
var chacha = ChaCha20(key: key, iv: iv)
return chacha.encrypt(bytes)
case .AES(let key, let iv, let blockMode):
var aes = AES(key: key, iv: iv, blockMode: blockMode)
return aes.encrypt(bytes)
}
}
/**
Decrypt message
:param: message Message data
:returns: Plaintext message
*/
public func decrypt(bytes: [UInt8]) -> [UInt8]? {
switch (self) {
case .ChaCha20(let key, let iv):
var chacha = ChaCha20(key: key, iv: iv);
return chacha.decrypt(bytes)
case .AES(let key, let iv, let blockMode):
var aes = AES(key: key, iv: iv, blockMode: blockMode);
return aes.decrypt(bytes)
}
}
static public func randomIV(blockSize:Int) -> [UInt8] {
var randomIV:[UInt8] = [UInt8]();
for (var i = 0; i < blockSize; i++) {
randomIV.append(UInt8(truncatingBitPattern: arc4random_uniform(256)));
}
return randomIV
}
} | mit | 4fbfe20c6ae7ca9665bbe84932eace48 | 25.2 | 82 | 0.549898 | 4.1174 | false | false | false | false |
tominated/Quake3BSPParser | Sources/BinaryReader.swift | 1 | 2185 | //
// BinaryParser.swift
// Quake3BSPParser
//
// Created by Thomas Brunoli on 28/05/2017.
// Copyright © 2017 Quake3BSPParser. All rights reserved.
//
import Foundation
import simd
internal class BinaryReader {
let data: Data;
var position: Int = 0;
init(_ data: Data) {
self.data = data;
}
func reset() {
position = 0;
}
func jump(to addr: Int) {
position = addr;
}
func skip(length: Int) {
position += length;
}
func getNumber<T>() -> T {
let size = MemoryLayout<T>.size
let sub = data.subdata(in: position ..< (position + size))
let number = sub.withUnsafeBytes { (pointer: UnsafePointer<T>) -> T in
return pointer.pointee;
}
position += MemoryLayout<T>.size
return number;
}
func getInt2() -> int2 {
return int2(getNumber(), getNumber());
}
func getInt3() -> int3 {
return int3(getNumber(), getNumber(), getNumber());
}
func getFloat2() -> float2 {
return float2(getNumber(), getNumber());
}
func getFloat3() -> float3 {
return float3(getNumber(), getNumber(), getNumber());
}
func getIndexRange() -> CountableRange<Int32> {
let start: Int32 = getNumber();
let size: Int32 = getNumber();
return start ..< (start + size);
}
func getString(maxLength: Int) -> String? {
let string = data.withUnsafeBytes { (pointer: UnsafePointer<CChar>) -> String? in
var currentPointer = pointer.advanced(by: position);
for _ in 0 ..< maxLength {
guard currentPointer.pointee != CChar(0) else { break }
currentPointer = currentPointer.successor();
}
let endPosition = pointer.distance(to: currentPointer)
let stringData = data.subdata(in: position ..< endPosition);
return String(data: stringData, encoding: String.Encoding.ascii);
};
position += maxLength;
return string
}
func subdata(in range: Range<Int>) -> BinaryReader {
return BinaryReader(data.subdata(in: range));
}
}
| mit | cf5e283c50f59587879885af522f3947 | 23.818182 | 89 | 0.571429 | 4.341948 | false | false | false | false |
abertelrud/swift-package-manager | Tests/SourceControlTests/InMemoryGitRepositoryTests.swift | 2 | 5144 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift 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 http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import XCTest
import TSCBasic
import SourceControl
import SPMTestSupport
class InMemoryGitRepositoryTests: XCTestCase {
func testBasics() throws {
let fs = InMemoryFileSystem()
let repo = InMemoryGitRepository(path: .root, fs: fs)
try repo.createDirectory(AbsolutePath(path: "/new-dir/subdir"), recursive: true)
XCTAssertTrue(!repo.hasUncommittedChanges())
let filePath = AbsolutePath(path: "/new-dir/subdir").appending(component: "new-file.txt")
try repo.writeFileContents(filePath, bytes: "one")
XCTAssertEqual(try repo.readFileContents(filePath), "one")
XCTAssertTrue(repo.hasUncommittedChanges())
let firstCommit = try repo.commit()
XCTAssertTrue(!repo.hasUncommittedChanges())
XCTAssertEqual(try repo.readFileContents(filePath), "one")
XCTAssertEqual(try fs.readFileContents(filePath), "one")
try repo.writeFileContents(filePath, bytes: "two")
XCTAssertEqual(try repo.readFileContents(filePath), "two")
XCTAssertTrue(repo.hasUncommittedChanges())
let secondCommit = try repo.commit()
XCTAssertTrue(!repo.hasUncommittedChanges())
XCTAssertEqual(try repo.readFileContents(filePath), "two")
try repo.writeFileContents(filePath, bytes: "three")
XCTAssertTrue(repo.hasUncommittedChanges())
XCTAssertEqual(try repo.readFileContents(filePath), "three")
try repo.checkout(revision: firstCommit)
XCTAssertTrue(!repo.hasUncommittedChanges())
XCTAssertEqual(try repo.readFileContents(filePath), "one")
XCTAssertEqual(try fs.readFileContents(filePath), "one")
try repo.checkout(revision: secondCommit)
XCTAssertTrue(!repo.hasUncommittedChanges())
XCTAssertEqual(try repo.readFileContents(filePath), "two")
XCTAssert(try repo.getTags().isEmpty)
try repo.tag(name: "2.0.0")
XCTAssertEqual(try repo.getTags(), ["2.0.0"])
XCTAssertTrue(!repo.hasUncommittedChanges())
XCTAssertEqual(try repo.readFileContents(filePath), "two")
XCTAssertEqual(try fs.readFileContents(filePath), "two")
try repo.checkout(revision: firstCommit)
XCTAssertTrue(!repo.hasUncommittedChanges())
XCTAssertEqual(try repo.readFileContents(filePath), "one")
try repo.checkout(tag: "2.0.0")
XCTAssertTrue(!repo.hasUncommittedChanges())
XCTAssertEqual(try repo.readFileContents(filePath), "two")
}
func testProvider() throws {
let v1 = "1.0.0"
let v2 = "2.0.0"
let repo = InMemoryGitRepository(path: .root, fs: InMemoryFileSystem())
let specifier = RepositorySpecifier(path: .init(path: "/foo"))
try repo.createDirectory(AbsolutePath(path: "/new-dir/subdir"), recursive: true)
let filePath = AbsolutePath(path: "/new-dir/subdir").appending(component: "new-file.txt")
try repo.writeFileContents(filePath, bytes: "one")
try repo.commit()
try repo.tag(name: v1)
try repo.writeFileContents(filePath, bytes: "two")
try repo.commit()
try repo.tag(name: v2)
let provider = InMemoryGitRepositoryProvider()
provider.add(specifier: specifier, repository: repo)
let fooRepoPath = AbsolutePath(path: "/fooRepo")
try provider.fetch(repository: specifier, to: fooRepoPath)
let fooRepo = try provider.open(repository: specifier, at: fooRepoPath)
// Adding a new tag in original repo shouldn't show up in fetched repo.
try repo.tag(name: "random")
XCTAssertEqual(try fooRepo.getTags().sorted(), [v1, v2])
XCTAssert(fooRepo.exists(revision: try fooRepo.resolveRevision(tag: v1)))
let fooCheckoutPath = AbsolutePath(path: "/fooCheckout")
XCTAssertFalse(try provider.workingCopyExists(at: fooCheckoutPath))
_ = try provider.createWorkingCopy(repository: specifier, sourcePath: fooRepoPath, at: fooCheckoutPath, editable: false)
XCTAssertTrue(try provider.workingCopyExists(at: fooCheckoutPath))
let fooCheckout = try provider.openWorkingCopy(at: fooCheckoutPath)
XCTAssertEqual(try fooCheckout.getTags().sorted(), [v1, v2])
XCTAssert(fooCheckout.exists(revision: try fooCheckout.getCurrentRevision()))
let checkoutRepo = try provider.openRepo(at: fooCheckoutPath)
try fooCheckout.checkout(tag: v1)
XCTAssertEqual(try checkoutRepo.readFileContents(filePath), "one")
try fooCheckout.checkout(tag: v2)
XCTAssertEqual(try checkoutRepo.readFileContents(filePath), "two")
}
}
| apache-2.0 | 0d2c6de25e8cc9ce40199f346fae6a91 | 42.226891 | 128 | 0.670684 | 4.663645 | false | true | false | false |
wzboy049/ZMonthlyCalendar | ZMonthlyCalendar/sources/View/FSTopScrollView.swift | 1 | 10672 | //
// FSTopScrollView.swift
// ZBXMobile
//
// Created by wzboy on 17/3/20.
// Copyright © 2017年 zbx. All rights reserved.
//
import UIKit
typealias fscMonthClickBlock = (Int)->Void
typealias fscYearClickBlock = (Int)->Void
let kAnimateDuration = 0.25
let kLeftMargin : CGFloat = 13.0
let kNaviMaxY : CGFloat = 64.0
let kDefaultCellHeight : CGFloat = 44.0
let kScreenWidth : CGFloat = UIScreen.main.bounds.width
let kScreenHeight : CGFloat = UIScreen.main.bounds.height
let fcBtnWidth = kScreenWidth * 0.5
let fcCollectionHeight : CGFloat = 100
let fcCvCellHeight : CGFloat = 40
class FSTopScrollView: UIView ,UICollectionViewDelegate,UICollectionViewDataSource{
lazy var currentMonth : Int = {
let formate = DateFormatter()
formate.dateFormat = "MM"
let currentM = Int(formate.string(from: Date()))!
return currentM
}()
var yearBlock : fscYearClickBlock?
var monthBlock : fscMonthClickBlock?
var expandBlock : ( ()->() )?
var scorllBgView : UIView?
var collectionView : UICollectionView?
var collectionViewHeight : NSLayoutConstraint?
var clearCover : UIImageView?
lazy var scrollView: UIScrollView = {
let scrollView = UIScrollView(frame: CGRect(x: 0, y: 0, width: kScreenWidth, height: kDefaultCellHeight))
scrollView.showsHorizontalScrollIndicator = false;
scrollView.isPagingEnabled = false
self.addSubview(scrollView)
scrollView.alignInner_dd(type: .topLeft, referView: self, size: CGSize(kScreenWidth,fsvTopViewHeight))
return scrollView
}()
var modelArray : [[FSCellModel]] = [[FSCellModel]](){
didSet{
if modelArray.count > 0 {
fscSetupSubview()
}
}
}
var fscCurrentBtn : FSYearButton?
override init(frame: CGRect) {
super.init(frame: frame)
}
convenience init(modelArray:[[FSCellModel]]){
self.init()
self.modelArray = modelArray //set 里set subView //!!! convenience init 不走didSet!!!!
fscSetupSubview()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func fscSetupSubview(){
if scorllBgView != nil {
scorllBgView!.removeFromSuperview()
}
scorllBgView = UIView(frame: CGRect(x:0,y:0,width:kScreenWidth,height:fsvTopViewHeight))
scrollView.addSubview(scorllBgView!)
let formate = DateFormatter()
formate.dateFormat = "yyyy"
let currentYear = Int(formate.string(from: Date()))!
for (i, arr) in modelArray.enumerated() {
let btn = FSYearButton()
btn.setTitle("\(arr[0].year)年", for: .normal)
if arr[0].year == currentYear {
btn.isSelected = true
fscCurrentBtn = btn
}
btn.titleLabel?.font = UIFont.systemFont(ofSize: 16) //dFont16
btn.setTitleColor(UIColor.black, for: .normal)
btn.setTitleColor(UIColor.black, for: .selected)
btn.setImage(UIImage(named:"financialStatements_topArror_up"), for: .selected)
btn.setImage(UIImage(named:""), for: .normal)
btn.isSelected = arr[0].year == currentYear
btn.tag = i
btn.frame = CGRect(x: CGFloat(i) * fcBtnWidth, y: 0, width: fcBtnWidth, height: fsvTopViewHeight)
scorllBgView?.addSubview(btn)
// btn.backgroundColor = ddRandomColor_dd()
btn.addTarget(self, action: #selector(fscBtnClick(btn:)), for: .touchUpInside)
}
scrollView.contentInset = UIEdgeInsets(top: 0, left: fcBtnWidth * 0.5, bottom: 0, right: 0)
scorllBgView?.width = fcBtnWidth * CGFloat(modelArray.count)
scrollView.contentSize = scorllBgView!.size
scrollView.contentOffset = CGPoint(x: CGFloat(fscCurrentBtn!.tag) * fcBtnWidth - fcBtnWidth * 0.5, y: 0)
fscSetupCollectionView()
clearCover?.removeFromSuperview()
clearCover = UIImageView(image: UIImage(named:"financialStatements_topSlider_hud"))
// clearCover?.isUserInteractionEnabled = true
clearCover!.frame = CGRect(x: 0, y: 0, width: kScreenWidth, height: fsvTopViewHeight + 1) //+1 sb
addSubview(clearCover!)
}
func fscSetupCollectionView() {
///每行 2个cell
let cellNumPerRow : CGFloat = 6
let ueiCellWidth : CGFloat = fcCvCellHeight
// let ueiCellHeight : CGFloat = dheight(170)
let layout = UICollectionViewFlowLayout()
layout.itemSize = CGSize(width: ueiCellWidth, height: ueiCellWidth)
// layout.scrollDirection = .vertical
let margin = (kScreenWidth - ueiCellWidth * cellNumPerRow ) / (cellNumPerRow + 1)
layout.sectionInset = UIEdgeInsetsMake(5, margin, 5, margin);
collectionView = UICollectionView(frame: CGRect(x:0,y:fsvTopViewHeight,width:kScreenWidth,height:0), collectionViewLayout: layout)
addSubview(collectionView!)
let cCons = collectionView!.alignInner_dd(type: .topLeft, referView: self, size: CGSize(kScreenWidth,0),offset:CGPoint(0,fsvTopViewHeight))
collectionViewHeight = collectionView!.getConstraint_dd(constraintsList: cCons, attribute: .height)
collectionView?.register(FSTopCVCell.self, forCellWithReuseIdentifier: String(describing: FSTopCVCell.self))
collectionView?.bounces = false
collectionView?.backgroundColor = UIColor.lightGray
collectionView!.dataSource = self
collectionView!.delegate = self
// collectionView!.reloadData()
}
///年 按钮的点击事件
func fscBtnClick(btn:FSYearButton ){
let arr = modelArray[btn.tag]
if fscCurrentBtn!.isExpand {
collectionView?.reloadData() //刷新
}
//还是点击了当前 按钮 展开/收起collectionView
if fscCurrentBtn == btn {
let offset = CGPoint(x: fscCurrentBtn!.centerX - fcBtnWidth , y: 0)
scrollView.setContentOffset(offset, animated: true)
fscCurrentBtn!.isExpand = !(fscCurrentBtn!.isExpand)
if expandBlock != nil {
expandBlock!()
}
return
}
if yearBlock != nil {
yearBlock!(arr[0].year)
}
if fscCurrentBtn!.isExpand {
if expandBlock != nil {
expandBlock!()
}
fscCurrentBtn!.isExpand = !fscCurrentBtn!.isExpand
}
fscCurrentBtn?.isSelected = false
btn.isSelected = true
fscCurrentBtn = btn
let offset = CGPoint(x: fscCurrentBtn!.centerX - fcBtnWidth , y: 0)
scrollView.setContentOffset(offset, animated: true)
}
func showMonthView(){
collectionViewHeight?.constant = fcCollectionHeight
collectionView?.reloadData()
}
func hideMonthView(){
collectionViewHeight?.constant = 0
}
}
extension FSTopScrollView {
@objc(collectionView:cellForItemAtIndexPath:) func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: String(describing: FSTopCVCell.self), for: indexPath) as! FSTopCVCell
let model = modelArray[fscCurrentBtn!.tag][indexPath.item]
///下面这段是假数据
if model.month > currentMonth{
model.fileId = nil
}else if model.month == currentMonth {
model.fileId = "2"
}else {
model.fileId = "1"
}
cell.monthModel = model
// cell.btn.tag = indexPath.item
//
// cell.btn.addTarget(self, action: #selector(fscMonthBtnClick(btn:)), for: .touchUpInside)
return cell
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 12 //一年12月
}
@objc(collectionView:didSelectItemAtIndexPath:) func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
if monthBlock != nil && indexPath.item + 1 <= currentMonth {
monthBlock!(indexPath.item)
}
}
// func fscMonthBtnClick(btn:UIButton){
//
//
// }
}
class FSMonthBtn: UIButton {
var monthModle : FSCellModel?{
didSet{
if monthModle == nil {
return
}
}
}
override func layoutSubviews() {
super.layoutSubviews()
layer.cornerRadius = self.width * 0.5
layer.masksToBounds = true
}
}
class FSYearButton : UIButton {
var isExpand : Bool = false {
didSet{
if isExpand {
UIView.animate(withDuration: kAnimateDuration, animations: {
self.imageView?.transform = CGAffineTransform(rotationAngle: CGFloat.pi)
}, completion: { (flag) in
// self.imageView?.isHidden = true
})
}else {
UIView.animate(withDuration: kAnimateDuration, animations: {
self.imageView?.transform = CGAffineTransform.identity
}, completion: { (flag) in
})
}
}
}
override func layoutSubviews() {
super.layoutSubviews()
if titleLabel == nil || imageView == nil {
return
}
titleLabel?.sizeToFit()
if titleLabel != nil && !imageView!.isHidden {
titleLabel?.centerX = self.width * 0.45
titleLabel?.centerY = self.height * 0.5
imageView!.size = CGSize(width:13 ,height:13)
imageView!.centerY = titleLabel!.centerY
imageView!.x = titleLabel!.frame.maxX + 5
}else {
titleLabel?.centerX = self.width * 0.5
titleLabel?.centerY = self.height * 0.5
}
}
}
| mit | a8cb46b691edcb075c925beee82402d5 | 29.95614 | 167 | 0.579768 | 4.790498 | false | false | false | false |
gaelfoppolo/handicarparking | HandiParking/HandiParking/SwiftSpinner.swift | 1 | 12964 | //
// Copyright (c) 2015 Marin Todorov, Underplot ltd.
// This code is distributed under the terms and conditions of the MIT license.
//
// 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
// set up the SwiftSpinner protocol with a single option stop search function
@objc protocol SwiftSpinnerDelegate: NSObjectProtocol {
optional func didTapCloseButton()
}
public class SwiftSpinner: UIView {
// MARK: - Singleton
//
// Access the singleton instance
//
public class var sharedInstance: SwiftSpinner {
struct Singleton {
static let instance = SwiftSpinner(frame: CGRect.zeroRect)
}
return Singleton.instance
}
// MARK: - Init
//
// Custom init to build the spinner UI
//
public override init(frame: CGRect) {
super.init(frame: frame)
blurEffect = UIBlurEffect(style: blurEffectStyle)
blurView = UIVisualEffectView(effect: blurEffect)
addSubview(blurView)
vibrancyView = UIVisualEffectView(effect: UIVibrancyEffect(forBlurEffect: blurEffect))
addSubview(vibrancyView)
let titleScale: CGFloat = 0.85
titleLabel.frame.size = CGSize(width: frameSize.width * titleScale, height: frameSize.height * titleScale)
titleLabel.font = defaultTitleFont
titleLabel.numberOfLines = 0
titleLabel.textAlignment = .Center
titleLabel.lineBreakMode = .ByWordWrapping
titleLabel.adjustsFontSizeToFitWidth = true
vibrancyView.contentView.addSubview(titleLabel)
blurView.contentView.addSubview(vibrancyView)
outerCircleView.frame.size = frameSize
outerCircle.path = UIBezierPath(ovalInRect: CGRect(x: 0.0, y: 0.0, width: frameSize.width, height: frameSize.height)).CGPath
outerCircle.lineWidth = 8.0
outerCircle.strokeStart = 0.0
outerCircle.strokeEnd = 0.45
outerCircle.lineCap = kCALineCapRound
outerCircle.fillColor = UIColor.clearColor().CGColor
outerCircle.strokeColor = UIColor.whiteColor().CGColor
outerCircleView.layer.addSublayer(outerCircle)
outerCircle.strokeStart = 0.0
outerCircle.strokeEnd = 1.0
vibrancyView.contentView.addSubview(outerCircleView)
innerCircleView.frame.size = frameSize
let innerCirclePadding: CGFloat = 12
innerCircle.path = UIBezierPath(ovalInRect: CGRect(x: innerCirclePadding, y: innerCirclePadding, width: frameSize.width - 2*innerCirclePadding, height: frameSize.height - 2*innerCirclePadding)).CGPath
innerCircle.lineWidth = 4.0
innerCircle.strokeStart = 0.5
innerCircle.strokeEnd = 0.9
innerCircle.lineCap = kCALineCapRound
innerCircle.fillColor = UIColor.clearColor().CGColor
innerCircle.strokeColor = UIColor.grayColor().CGColor
innerCircleView.layer.addSublayer(innerCircle)
innerCircle.strokeStart = 0.0
innerCircle.strokeEnd = 1.0
vibrancyView.contentView.addSubview(innerCircleView)
closeButton = UIButton.buttonWithType(UIButtonType.System) as! UIButton
closeButton.addTarget(self, action: "closeButton:", forControlEvents: .TouchUpInside)
closeButton.setImage(UIImage(named: "close.png") as UIImage!, forState: .Normal)
closeButton.setTitleColor(UIColor.blackColor(), forState: .Normal)
closeButton.frame = CGRectMake(10, 25, 50, 50)
closeButton.tintColor = UIColor.whiteColor()
addSubview(closeButton)
}
// MARK: - Public interface
//
// Show the spinner activity on screen, if visible only update the title
//
public class func show(title: String, animated: Bool = true) {
let window = UIApplication.sharedApplication().windows.first as! UIWindow
let spinner = SwiftSpinner.sharedInstance
spinner.updateFrame()
if animated {
spinner.closeButton.enabled = true
} else {
spinner.closeButton.enabled = false
}
if spinner.superview == nil {
//show the spinner
spinner.alpha = 0.0
window.addSubview(spinner)
UIView.animateWithDuration(0.33, delay: 0.0, options: .CurveEaseOut, animations: {
spinner.alpha = 1.0
}, completion: nil)
}
spinner.title = title
spinner.animating = animated
}
//
// Show the spinner activity on screen with custom font, if visible only update the title
// Note that the custom font will be discarded when hiding the spinner
// To permanently change the title font, set the defaultTitleFont property
//
public class func show(title: String, withFont font: UIFont, animated: Bool = true) {
let spinner = SwiftSpinner.sharedInstance
spinner.titleLabel.font = font
show(title, animated: true)
}
//
// Tap close button of spinner
//
// Handle by the delegate method
//
func closeButton(sender: UIButton!) {
// test if delegate methode is implemented
/*if let delegateIsImplemented = delegate?.respondsToSelector(Selector("didTapCloseButton")) {
println("delegate ok")
if delegateIsImplemented {
println("method implemented")
} else {
println("method not implemented")
}
} else {
println("delegate not ok")
}*/
delegate?.didTapCloseButton?()
}
//
// Hide the spinner
//
public class func hide() {
let spinner = SwiftSpinner.sharedInstance
if spinner.superview == nil {
return
}
UIView.animateWithDuration(0.33, delay: 0.0, options: .CurveEaseOut, animations: {
spinner.alpha = 0.0
}, completion: {_ in
spinner.alpha = 1.0
spinner.removeFromSuperview()
spinner.titleLabel.font = spinner.defaultTitleFont
spinner.titleLabel.text = nil
})
spinner.animating = false
}
//
// Set the default title font
//
public class func setDefaultTitleFont(font: UIFont?) {
let spinner = SwiftSpinner.sharedInstance
spinner.defaultTitleFont = font!
spinner.titleLabel.font = font
}
//
// The spinner title
//
public var title: String = "" {
didSet {
let spinner = SwiftSpinner.sharedInstance
UIView.animateWithDuration(0.15, delay: 0.0, options: .CurveEaseOut, animations: {
spinner.titleLabel.transform = CGAffineTransformMakeScale(0.75, 0.75)
spinner.titleLabel.alpha = 0.2
}, completion: {_ in
spinner.titleLabel.text = self.title
UIView.animateWithDuration(0.35, delay: 0.0, usingSpringWithDamping: 0.35, initialSpringVelocity: 0.0, options: nil, animations: {
spinner.titleLabel.transform = CGAffineTransformIdentity
spinner.titleLabel.alpha = 1.0
}, completion: nil)
})
}
}
//
// observe the view frame and update the subviews layout
//
public override var frame: CGRect {
didSet {
if frame == CGRect.zeroRect {
return
}
blurView.frame = bounds
vibrancyView.frame = blurView.bounds
titleLabel.center = vibrancyView.center
outerCircleView.center = vibrancyView.center
innerCircleView.center = vibrancyView.center
}
}
//
// Start the spinning animation
//
public var animating: Bool = false {
willSet (shouldAnimate) {
if shouldAnimate && !animating {
spinInner()
spinOuter()
}
}
didSet {
// update UI
if animating {
self.outerCircle.strokeStart = 0.0
self.outerCircle.strokeEnd = 0.45
self.innerCircle.strokeStart = 0.5
self.innerCircle.strokeEnd = 0.9
} else {
self.outerCircle.strokeStart = 0.0
self.outerCircle.strokeEnd = 1.0
self.innerCircle.strokeStart = 0.0
self.innerCircle.strokeEnd = 1.0
}
}
}
// MARK: - Private interface
//
// layout elements
//
// this is where we declare our protocol
var delegate:SwiftSpinnerDelegate?
private var closeButton: UIButton!
private var blurEffectStyle: UIBlurEffectStyle = .Dark
private var blurEffect: UIBlurEffect!
private var blurView: UIVisualEffectView!
private var vibrancyView: UIVisualEffectView!
lazy var titleLabel = UILabel()
var defaultTitleFont = UIFont.systemFontOfSize(22)
let frameSize = CGSize(width: 200.0, height: 200.0)
private lazy var outerCircleView = UIView()
private lazy var innerCircleView = UIView()
private let outerCircle = CAShapeLayer()
private let innerCircle = CAShapeLayer()
required public init(coder aDecoder: NSCoder) {
fatalError("Not coder compliant")
}
private var currentOuterRotation: CGFloat = 0.0
private var currentInnerRotation: CGFloat = 0.1
private func spinOuter() {
if superview == nil {
return
}
let duration = Double(Float(arc4random()) / Float(UInt32.max)) * 2.0 + 1.5
let randomRotation = Double(Float(arc4random()) / Float(UInt32.max)) * M_PI_4 + M_PI_4
//outer circle
UIView.animateWithDuration(duration, delay: 0.0, usingSpringWithDamping: 0.4, initialSpringVelocity: 0.0, options: nil, animations: {
self.currentOuterRotation -= CGFloat(randomRotation)
self.outerCircleView.transform = CGAffineTransformMakeRotation(self.currentOuterRotation)
}, completion: {_ in
let waitDuration = Double(Float(arc4random()) / Float(UInt32.max)) * 1.0 + 1.0
self.delay(seconds: waitDuration, completion: {
if self.animating {
self.spinOuter()
}
})
})
}
private func spinInner() {
if superview == nil {
return
}
//inner circle
UIView.animateWithDuration(0.5, delay: 0.0, usingSpringWithDamping: 0.5, initialSpringVelocity: 0.0, options: nil, animations: {
self.currentInnerRotation += CGFloat(M_PI_4)
self.innerCircleView.transform = CGAffineTransformMakeRotation(self.currentInnerRotation)
}, completion: {_ in
self.delay(seconds: 0.5, completion: {
if self.animating {
self.spinInner()
}
})
})
}
private func updateFrame() {
let window = UIApplication.sharedApplication().windows.first as! UIWindow
SwiftSpinner.sharedInstance.frame = window.frame
}
// MARK: - Util methods
func delay(#seconds: Double, completion:()->()) {
let popTime = dispatch_time(DISPATCH_TIME_NOW, Int64( Double(NSEC_PER_SEC) * seconds ))
dispatch_after(popTime, dispatch_get_main_queue()) {
completion()
}
}
override public func layoutSubviews() {
super.layoutSubviews()
updateFrame()
}
}
| gpl-3.0 | f2ae50c6f8e01c6be919c2cecfb54728 | 34.911357 | 463 | 0.606449 | 5.317473 | false | false | false | false |
wbaumann/SmartReceiptsiOS | SmartReceipts/Modules/OCR Configuration/OCRConfigurationView.swift | 2 | 5773 | //
// OCRConfigurationView.swift
// SmartReceipts
//
// Created by Bogdan Evsenev on 25/10/2017.
//Copyright © 2017 Will Baumann. All rights reserved.
//
import UIKit
import Viperit
import RxSwift
import RxCocoa
//MARK: - Public Interface Protocol
protocol OCRConfigurationViewInterface {
var buy10ocr: Observable<Void> { get }
var buy50ocr: Observable<Void> { get }
var OCR10Price: AnyObserver<String> { get }
var OCR50Price: AnyObserver<String> { get }
func updateScansCount()
var logoutTap: Observable<Void> { get }
var successLogoutHandler: AnyObserver<Void> { get }
var errorHandler: AnyObserver<String> { get }
}
//MARK: OCRConfigurationView Class
final class OCRConfigurationView: UserInterface {
@IBOutlet private weak var descriptionLabel: UILabel!
@IBOutlet private weak var titleLabel: UILabel!
@IBOutlet private weak var autoScansLabel: UILabel!
@IBOutlet private weak var saveImagesLabel: UILabel!
@IBOutlet private weak var availablePurchases: UILabel!
@IBOutlet private weak var closeButton: UIBarButtonItem!
@IBOutlet fileprivate weak var scans10button: ScansPurchaseButton!
@IBOutlet fileprivate weak var scans50button: ScansPurchaseButton!
@IBOutlet fileprivate weak var autoScans: UISwitch!
@IBOutlet fileprivate weak var allowSaveImages: UISwitch!
@IBOutlet fileprivate weak var logoutButton: UIBarButtonItem!
private let bag = DisposeBag()
override func viewDidLoad() {
super.viewDidLoad()
localizeLabels()
scans10button.setScans(count: 10)
scans50button.setScans(count: 50)
autoScans.isOn = WBPreferences.automaticScansEnabled()
allowSaveImages.isOn = WBPreferences.allowSaveImageForAccuracy()
configureRx()
}
func updateScansCount() {
ScansPurchaseTracker.shared.fetchAndPersistAvailableRecognitions()
.map { String(format: LocalizedString("ocr_configuration_scans_remaining"), $0) }
.subscribe(onSuccess: { [weak self] in
self?.setTitle($0, subtitle: AuthService.shared.email)
}).disposed(by: bag)
}
private func configureRx() {
AuthService.shared.loggedInObservable
.subscribe(onNext: { [unowned self] loggedIn in
self.logoutButton.isEnabled = loggedIn
}).disposed(by: bag)
updateScansCount()
autoScans.rx.isOn
.subscribe(onNext:{ WBPreferences.setAutomaticScansEnabled($0) })
.disposed(by: bag)
allowSaveImages.rx.isOn
.subscribe(onNext:{ WBPreferences.setAllowSaveImageForAccuracy($0) })
.disposed(by: bag)
closeButton.rx.tap
.subscribe(onNext: { [unowned self] in
self.dismiss(animated: true, completion: nil)
}).disposed(by: bag)
}
private func localizeLabels() {
titleLabel.text = LocalizedString("ocr_configuration_welcome")
availablePurchases.text = LocalizedString("ocr_configuration_available_purchases")
autoScansLabel.text = LocalizedString("ocr_is_enabled")
saveImagesLabel.text = LocalizedString("ocr_save_scans_to_improve_results")
logoutButton.title = LocalizedString("logout_button_text")
// Note: Android split these strings across multiple files, so we combine them here
let localizedDescriptionFormat = "%@\n\n%@\n\n%@"
let localizedDescription = String(format: localizedDescriptionFormat,
LocalizedString("ocr_configuration_information"),
LocalizedString("ocr_configuration_information_line2"),
LocalizedString("ocr_configuration_information_line3"))
descriptionLabel.text = localizedDescription
}
}
//MARK: - Public interface
extension OCRConfigurationView: OCRConfigurationViewInterface {
var buy10ocr: Observable<Void> { return scans10button.rx.tap.asObservable() }
var buy50ocr: Observable<Void> { return scans50button.rx.tap.asObservable() }
var OCR10Price: AnyObserver<String> { return scans10button.rx.price }
var OCR50Price: AnyObserver<String> { return scans50button.rx.price }
var successLogoutHandler: AnyObserver<Void> {
return AnyObserver<Void>(eventHandler: { [weak self] event in
switch event {
case .next:
Logger.info("Successfully logged out")
self?.dismiss(animated: true, completion: nil)
default: break
}
})
}
var logoutTap: Observable<Void> {
return logoutButton.rx.tap.asObservable()
}
var errorHandler: AnyObserver<String> {
return AnyObserver<String>(eventHandler: { [weak self] event in
switch event {
case .next(let errorMessage):
let alert = UIAlertController(title: LocalizedString("generic_error_alert_title"), message: errorMessage, preferredStyle: .alert)
let action = UIAlertAction(title: LocalizedString("generic_button_title_ok"), style: .cancel, handler: nil)
alert.addAction(action)
self?.present(alert, animated: true, completion: nil)
default: break
}
})
}
}
// MARK: - VIPER COMPONENTS API (Auto-generated code)
private extension OCRConfigurationView {
var presenter: OCRConfigurationPresenter {
return _presenter as! OCRConfigurationPresenter
}
var displayData: OCRConfigurationDisplayData {
return _displayData as! OCRConfigurationDisplayData
}
}
| agpl-3.0 | a2f48bec5e9d26551bbbde68d13e6bd3 | 37.225166 | 145 | 0.654539 | 4.834171 | false | true | false | false |
vector-im/vector-ios | Riot/Modules/Room/DataSources/ThreadDataSource.swift | 1 | 1180 | //
// Copyright 2021 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
@objcMembers
public class ThreadDataSource: RoomDataSource {
public override func finalizeInitialization() {
super.finalizeInitialization()
showReadMarker = false
showBubbleReceipts = false
showTypingRow = false
}
public override var showReadMarker: Bool {
get {
return false
} set {
_ = newValue
}
}
public override var showBubbleReceipts: Bool {
get {
return false
} set {
_ = newValue
}
}
}
| apache-2.0 | df456921f2cdf295e6f00982de874d16 | 25.222222 | 75 | 0.644068 | 4.68254 | false | false | false | false |
erikdoe/swift-circle | SwiftCircle/SwiftCircleView.swift | 1 | 3002 | /*
* Copyright 2015 Erik Doernenburg
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use these files 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.
*/
// http://www.raywenderlich.com/74438/swift-tutorial-a-quick-start
// http://stackoverflow.com/questions/27852616/do-swift-screensavers-work-in-mac-os-x-before-yosemite
import ScreenSaver
public class SwiftCircleView : ScreenSaverView {
var defaultsManager: DefaultsManager = DefaultsManager()
lazy var sheetController: ConfigureSheetController = ConfigureSheetController()
var circleSize: Float = 100
var amplitude: Float = 0.5
var canvasColor: NSColor?
var circleColor: NSColor?
var frameCount = 0
override init?(frame: NSRect, isPreview: Bool) {
super.init(frame: frame, isPreview: isPreview)
animationTimeInterval = 1.0 / 60.0
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override public var hasConfigureSheet: Bool {
return true
}
override public var configureSheet: NSWindow? {
return sheetController.window
}
override public func startAnimation() {
super.startAnimation()
cacheColors()
needsDisplay = true
}
override public func stopAnimation() {
super.stopAnimation()
}
override public func draw(_ rect: NSRect) {
super.draw(rect)
cacheColors()
drawBackground()
drawCircle(canvasColor!, diameter: CGFloat(circleSize+amplitude))
let r = CGFloat(sin(Float(frameCount) / 40) * amplitude + circleSize)
drawCircle(circleColor!, diameter: r)
frameCount += 1
}
override public func animateOneFrame() {
needsDisplay = true
}
func cacheColors() {
circleSize = Float(bounds.size.height) / 4 * defaultsManager.size
amplitude = circleSize * defaultsManager.amplitude * 0.75
canvasColor = defaultsManager.canvasColor
circleColor = defaultsManager.circleColor
}
func drawBackground() {
let bPath:NSBezierPath = NSBezierPath(rect: bounds)
canvasColor!.set()
bPath.fill()
}
func drawCircle(_ color: NSColor, diameter: CGFloat) {
let circleRect = NSMakeRect(bounds.size.width/2 - diameter/2, bounds.size.height/2 - diameter/2, diameter, diameter)
let cPath: NSBezierPath = NSBezierPath(ovalIn: circleRect)
color.set()
cPath.fill()
}
}
| apache-2.0 | 6d03340ecf3d7830edb90b04db2022e0 | 28.145631 | 124 | 0.658228 | 4.541604 | false | false | false | false |
carabina/Brief | Brief/Brief.swift | 1 | 9577 | //
// Brief.swift
//
// Created by kakajika on 2015/06/03.
// Copyright (c) 2015 INFOCITY, Inc. All rights reserved.
//
import UIKit
extension UIView {
// Frame
public var frameOrigin: CGPoint {
get { return self.frame.origin }
set(frameOrigin) { self.frame = CGRect(origin: frameOrigin, size: frameSize) }
}
public var frameSize: CGSize {
get { return self.frame.size }
set(frameSize) { self.frame = CGRect(origin: frameOrigin, size: frameSize) }
}
// Frame Origin
public var x: CGFloat {
get { return self.frame.minX }
set(x) { self.frame = CGRectMake(x, y, width, height) }
}
public var y: CGFloat {
get { return self.frame.minY }
set(y) { self.frame = CGRectMake(x, y, width, height) }
}
// Frame Size
public var width: CGFloat {
get { return self.frame.width }
set(width) { self.frame = CGRectMake(x, y, width, height) }
}
public var height: CGFloat {
get { return self.frame.height }
set(height) { self.frame = CGRectMake(x, y, width, height) }
}
// Frame Borders
public var left: CGFloat {
get { return self.frame.minX }
set(left) { self.frame = CGRectMake(left, top, width, height) }
}
public var top: CGFloat {
get { return self.frame.minY }
set(top) { self.frame = CGRectMake(left, top, width, height) }
}
public var right: CGFloat {
get { return self.frame.maxX }
set(right) { self.frame = CGRectMake(right-width, top, width, height) }
}
public var bottom: CGFloat {
get { return self.frame.maxY }
set(bottom) { self.frame = CGRectMake(left, bottom-height, width, height) }
}
// Bounds
public var boundsOrigin: CGPoint {
get { return self.bounds.origin }
set(boundsOrigin) { self.bounds = CGRect(origin: boundsOrigin, size: boundsSize) }
}
public var boundsSize: CGSize {
get { return self.bounds.size }
set(boundsSize) { self.bounds = CGRect(origin: boundsOrigin, size: boundsSize) }
}
public var boundsWidth: CGFloat {
get { return self.bounds.width }
set(boundsWidth) { self.bounds = CGRectMake(boundsLeft, boundsTop, boundsWidth, boundsHeight) }
}
public var boundsHeight: CGFloat {
get { return self.bounds.height }
set(boundsHeight) { self.bounds = CGRectMake(boundsLeft, boundsTop, boundsWidth, boundsHeight) }
}
public var boundsLeft: CGFloat {
get { return self.bounds.minX }
set(boundsLeft) { self.bounds = CGRectMake(boundsLeft, boundsTop, boundsWidth, boundsHeight) }
}
public var boundsTop: CGFloat {
get { return self.bounds.minY }
set(boundsTop) { self.bounds = CGRectMake(boundsLeft, boundsTop, boundsWidth, boundsHeight) }
}
public var boundsRight: CGFloat {
get { return self.bounds.maxX }
set(boundsRight) { self.bounds = CGRectMake(boundsRight-boundsWidth, boundsTop, boundsWidth, boundsHeight) }
}
public var boundsBottom: CGFloat {
get { return self.bounds.maxY }
set(boundsBottom) { self.bounds = CGRectMake(boundsLeft, boundsBottom-boundsHeight, boundsWidth, boundsHeight) }
}
// Center Point
public var centerX: CGFloat {
get { return self.center.x }
set(centerX) { self.center = CGPointMake(centerX, centerY) }
}
public var centerY: CGFloat {
get { return self.center.y }
set(centerY) { self.center = CGPointMake(centerX, centerY) }
}
// Middle Point
public var middlePoint: CGPoint {
get { return CGPointMake(middleX, middleY) }
}
public var middleX: CGFloat {
get { return width * 0.5 }
}
public var middleY: CGFloat {
get { return height * 0.5 }
}
}
extension UIScrollView {
// Content Offset
public var contentOffsetX: CGFloat {
get { return self.contentOffset.x }
set(contentOffsetX) { self.contentOffset = CGPointMake(contentOffsetX, contentOffsetY) }
}
public var contentOffsetY: CGFloat {
get { return self.contentOffset.y }
set(contentOffsetY) { self.contentOffset = CGPointMake(contentOffsetX, contentOffsetY) }
}
// Content Size
public var contentSizeWidth: CGFloat {
get { return self.contentSize.width }
set(contentSizeWidth) { self.contentSize = CGSizeMake(contentSizeWidth, contentSizeHeight) }
}
public var contentSizeHeight: CGFloat {
get { return self.contentSize.height }
set(contentSizeHeight) { self.contentSize = CGSizeMake(contentSizeWidth, contentSizeHeight) }
}
// Content Inset
public var contentInsetTop: CGFloat {
get { return self.contentInset.top }
set(contentInsetTop) { self.contentInset = UIEdgeInsetsMake(contentInsetTop, contentInsetLeft, contentInsetBottom, contentInsetRight) }
}
public var contentInsetLeft: CGFloat {
get { return self.contentInset.left }
set(contentInsetLeft) { self.contentInset = UIEdgeInsetsMake(contentInsetTop, contentInsetLeft, contentInsetBottom, contentInsetRight) }
}
public var contentInsetBottom: CGFloat {
get { return self.contentInset.bottom }
set(contentInsetBottom) { self.contentInset = UIEdgeInsetsMake(contentInsetTop, contentInsetLeft, contentInsetBottom, contentInsetRight) }
}
public var contentInsetRight: CGFloat {
get { return self.contentInset.right }
set(contentInsetRight) { self.contentInset = UIEdgeInsetsMake(contentInsetTop, contentInsetLeft, contentInsetBottom, contentInsetRight) }
}
}
extension CALayer {
// Frame
public var frameOrigin: CGPoint {
get { return self.frame.origin }
set(frameOrigin) { self.frame = CGRect(origin: frameOrigin, size: frameSize) }
}
public var frameSize: CGSize {
get { return self.frame.size }
set(frameSize) { self.frame = CGRect(origin: frameOrigin, size: frameSize) }
}
// Frame Origin
public var x: CGFloat {
get { return self.frame.minX }
set(x) { self.frame = CGRectMake(x, y, width, height) }
}
public var y: CGFloat {
get { return self.frame.minY }
set(y) { self.frame = CGRectMake(x, y, width, height) }
}
// Frame Size
public var width: CGFloat {
get { return self.frame.width }
set(width) { self.frame = CGRectMake(x, y, width, height) }
}
public var height: CGFloat {
get { return self.frame.height }
set(height) { self.frame = CGRectMake(x, y, width, height) }
}
// Frame Borders
public var left: CGFloat {
get { return self.frame.minX }
set(left) { self.frame = CGRectMake(left, top, width, height) }
}
public var top: CGFloat {
get { return self.frame.minY }
set(top) { self.frame = CGRectMake(left, top, width, height) }
}
public var right: CGFloat {
get { return self.frame.maxX }
set(right) { self.frame = CGRectMake(right-width, top, width, height) }
}
public var bottom: CGFloat {
get { return self.frame.maxY }
set(bottom) { self.frame = CGRectMake(left, bottom-height, width, height) }
}
// Bounds
public var boundsOrigin: CGPoint {
get { return self.bounds.origin }
set(boundsOrigin) { self.bounds = CGRect(origin: boundsOrigin, size: boundsSize) }
}
public var boundsSize: CGSize {
get { return self.bounds.size }
set(boundsSize) { self.bounds = CGRect(origin: boundsOrigin, size: boundsSize) }
}
public var boundsWidth: CGFloat {
get { return self.bounds.width }
set(boundsWidth) { self.bounds = CGRectMake(boundsLeft, boundsTop, boundsWidth, boundsHeight) }
}
public var boundsHeight: CGFloat {
get { return self.bounds.height }
set(boundsHeight) { self.bounds = CGRectMake(boundsLeft, boundsTop, boundsWidth, boundsHeight) }
}
public var boundsLeft: CGFloat {
get { return self.bounds.minX }
set(boundsLeft) { self.bounds = CGRectMake(boundsLeft, boundsTop, boundsWidth, boundsHeight) }
}
public var boundsTop: CGFloat {
get { return self.bounds.minY }
set(boundsTop) { self.bounds = CGRectMake(boundsLeft, boundsTop, boundsWidth, boundsHeight) }
}
public var boundsRight: CGFloat {
get { return self.bounds.maxX }
set(boundsRight) { self.bounds = CGRectMake(boundsRight-boundsWidth, boundsTop, boundsWidth, boundsHeight) }
}
public var boundsBottom: CGFloat {
get { return self.bounds.maxY }
set(boundsBottom) { self.bounds = CGRectMake(boundsLeft, boundsBottom-boundsHeight, boundsWidth, boundsHeight) }
}
// Anchor Point
public var anchorX: CGFloat {
get { return self.anchorPoint.x }
set(anchorX) { self.anchorPoint = CGPointMake(anchorX, anchorY) }
}
public var anchorY: CGFloat {
get { return self.anchorPoint.y }
set(anchorY) { self.anchorPoint = CGPointMake(anchorX, anchorY) }
}
// Position
public var positionX: CGFloat {
get { return self.position.x }
set(positionX) { self.position = CGPointMake(positionX, positionY) }
}
public var positionY: CGFloat {
get { return self.position.y }
set(positionY) { self.position = CGPointMake(positionX, positionY) }
}
} | apache-2.0 | 7177197c076e0860fe6b3b4b19691840 | 35.418251 | 146 | 0.635481 | 4.14948 | false | false | false | false |
uasys/swift | test/attr/accessibility_print.swift | 5 | 11790 | // RUN: %empty-directory(%t)
// RUN: %target-swift-ide-test -skip-deinit=false -print-ast-typechecked -print-access -source-filename=%s | %FileCheck %s -check-prefix=CHECK -check-prefix=CHECK-SRC
// RUN: %target-swift-frontend -emit-module-path %t/accessibility_print.swiftmodule %s
// RUN: %target-swift-ide-test -skip-deinit=false -print-module -print-access -module-to-print=accessibility_print -I %t -source-filename=%s | %FileCheck %s
// This file uses alphabetic prefixes on its declarations because swift-ide-test
// sorts decls in a module before printing them.
// CHECK-LABEL: internal var AA_defaultGlobal
var AA_defaultGlobal = 0
// CHECK: {{^}}private{{(\*/)?}} var AB_privateGlobal
// CHECK: {{^}}internal{{(\*/)?}} var AC_internalGlobal
// CHECK: {{^}}public{{(\*/)?}} var AD_publicGlobal
// CHECK: {{^}}fileprivate{{(\*/)?}} var AE_fileprivateGlobal
private var AB_privateGlobal = 0
internal var AC_internalGlobal = 0
public var AD_publicGlobal = 0
fileprivate var AE_fileprivateGlobal = 0
// CHECK-LABEL: internal struct BA_DefaultStruct {
struct BA_DefaultStruct {
// CHECK: internal let x
let x = 0
} // CHECK: {{^[}]}}
// CHECK-LABEL: private{{(\*/)?}} struct BB_PrivateStruct {
private struct BB_PrivateStruct {
// CHECK: internal var x
var x = 0
// CHECK: internal init(x: Int)
// CHECK: internal init()
} // CHECK: {{^[}]}}
// CHECK-LABEL: internal{{(\*/)?}} struct BC_InternalStruct {
internal struct BC_InternalStruct {
// CHECK: internal let x
let x = 0
// CHECK: internal init()
} // CHECK: {{^[}]}}
// CHECK-LABEL: public{{(\*/)?}} struct BD_PublicStruct {
public struct BD_PublicStruct {
// CHECK: internal var x
var x = 0
// CHECK: internal init(x: Int)
// CHECK: internal init()
} // CHECK: {{^[}]}}
// CHECK-LABEL: public{{(\*/)?}} struct BE_PublicStructPrivateMembers {
public struct BE_PublicStructPrivateMembers {
// CHECK: private{{(\*/)?}} var x
private var x = 0
// CHECK: private init(x: Int)
// CHECK: internal init()
} // CHECK: {{^[}]}}
// CHECK-LABEL: {{^}}fileprivate{{(\*/)?}} struct BF_FilePrivateStruct {
fileprivate struct BF_FilePrivateStruct {
// CHECK: {{^}} internal var x
var x = 0
// CHECK: {{^}} internal init(x: Int)
// CHECK: {{^}} internal init()
} // CHECK: {{^[}]}}
// CHECK-LABEL: private{{(\*/)?}} class CA_PrivateClass
private class CA_PrivateClass {
// CHECK: {{^}} deinit
deinit {}
// CHECK: internal init()
} // CHECK: {{^[}]}}
// CHECK-LABEL: internal{{(\*/)?}} class CB_InternalClass
internal class CB_InternalClass {
// CHECK: {{^}} deinit
deinit {}
// CHECK: internal init()
} // CHECK: {{^[}]}}
// CHECK-LABEL: public{{(\*/)?}} class CC_PublicClass
public class CC_PublicClass {
// CHECK: {{^}} deinit
deinit {}
// CHECK: internal init()
} // CHECK: {{^[}]}}
// CHECK-LABEL: private{{(\*/)?}} enum DA_PrivateEnum {
private enum DA_PrivateEnum {
// CHECK: {{^}} case Foo
// CHECK: Bar
case Foo, Bar
// CHECK: internal init()
init() { self = .Foo }
// CHECK: private var hashValue
} // CHECK: {{^[}]}}
// CHECK-LABEL: internal{{(\*/)?}} enum DB_InternalEnum {
internal enum DB_InternalEnum {
// CHECK: {{^}} case Foo
// CHECK: Bar
case Foo, Bar
// CHECK: internal init()
init() { self = .Foo }
// CHECK: internal var hashValue
} // CHECK: {{^[}]}}
// CHECK-LABEL: public{{(\*/)?}} enum DC_PublicEnum {
public enum DC_PublicEnum {
// CHECK: {{^}} case Foo
// CHECK: Bar
case Foo, Bar
// CHECK: internal init()
init() { self = .Foo }
// CHECK: public var hashValue
} // CHECK: {{^[}]}}
// CHECK-LABEL: private{{(\*/)?}} protocol EA_PrivateProtocol {
private protocol EA_PrivateProtocol {
// CHECK: {{^}} associatedtype Foo
associatedtype Foo
// CHECK: fileprivate var Bar
var Bar: Int { get }
// CHECK: fileprivate func baz()
func baz()
} // CHECK: {{^[}]}}
// CHECK-LABEL: public{{(\*/)?}} protocol EB_PublicProtocol {
public protocol EB_PublicProtocol {
// CHECK: {{^}} associatedtype Foo
associatedtype Foo
// CHECK: public var Bar
var Bar: Int { get }
// CHECK: public func baz()
func baz()
} // CHECK: {{^[}]}}
private class FA_PrivateClass {}
internal class FB_InternalClass {}
public class FC_PublicClass {}
// CHECK-SRC: {{^}}ex
// CHECK-LABEL: tension FA_PrivateClass {
extension FA_PrivateClass {
// CHECK: internal func a()
func a() {}
} // CHECK: {{^[}]}}
// CHECK-LABEL: extension FB_InternalClass {
extension FB_InternalClass {
// CHECK: internal func a()
func a() {}
} // CHECK: {{^[}]}}
// CHECK-LABEL: extension FC_PublicClass {
extension FC_PublicClass {
// CHECK: internal func a()
func a() {}
} // CHECK: {{^[}]}}
private class FD_PrivateClass {}
// CHECK-SRC: private
// CHECK-LABEL: extension FD_PrivateClass {
private extension FD_PrivateClass {
// CHECK: private func explicitPrivateExt()
func explicitPrivateExt() {}
} // CHECK: {{^[}]}}
public class FE_PublicClass {}
// CHECK-SRC: private
// CHECK-LABEL: extension FE_PublicClass {
private extension FE_PublicClass {
// CHECK: private func explicitPrivateExt()
func explicitPrivateExt() {}
// CHECK: private struct PrivateNested {
struct PrivateNested {
// CHECK: internal var x
var x: Int
} // CHECK: }
} // CHECK: {{^[}]}}
// CHECK-SRC: internal
// CHECK-LABEL: extension FE_PublicClass {
internal extension FE_PublicClass {
// CHECK: internal func explicitInternalExt()
func explicitInternalExt() {}
// CHECK: internal struct InternalNested {
struct InternalNested {
// CHECK: internal var x
var x: Int
} // CHECK: }
} // CHECK: {{^[}]}}
// CHECK-SRC: public
// CHECK-LABEL: extension FE_PublicClass {
public extension FE_PublicClass {
// CHECK: public func explicitPublicExt()
func explicitPublicExt() {}
// CHECK: public struct PublicNested {
struct PublicNested {
// CHECK: internal var x
var x: Int
} // CHECK: }
} // CHECK: {{^[}]}}
// CHECK-LABEL: internal func GA_localTypes()
func GA_localTypes() {
// CHECK-SRC: private struct Local {
struct Local {
// CHECK-SRC: internal let x
let x = 0
}
_ = Local()
// CHECK-SRC: private enum LocalEnum {
enum LocalEnum {
// CHECK-SRC: {{^}} case A
case A, B
}
let enumVal = LocalEnum.A
_ = (enumVal == .B)
} // CHECK-SRC: {{^[}]}}
// CHECK-LABEL: public{{(\*/)?}} struct GB_NestedOuter {
public struct GB_NestedOuter {
// CHECK: internal struct Inner {
struct Inner {
// CHECK: private{{(\*/)?}} let x
private let x = 0
// CHECK: internal let y
let y = 0
}
} // CHECK: {{^[}]}}
// CHECK-LABEL: private{{(\*/)?}} struct GC_NestedOuterPrivate {
private struct GC_NestedOuterPrivate {
// CHECK: internal struct Inner {
struct Inner {
// CHECK: private{{(\*/)?}} let x
private let x = 0
// CHECK: internal let y
let y = 0
}
} // CHECK: {{^[}]}}
public protocol HA_PublicProtocol {
associatedtype Assoc
}
internal protocol HB_InternalProtocol {
associatedtype Assoc
}
private protocol HC_PrivateProtocol {
associatedtype Assoc
}
public struct HA_PublicStruct {}
internal struct HB_InternalStruct {}
private struct HC_PrivateStruct {}
// CHECK-LABEL: extension HA_PublicProtocol {
extension HA_PublicProtocol {
// CHECK: internal func unconstrained()
func unconstrained() {}
} // CHECK: {{^[}]}}
// CHECK-LABEL: extension HA_PublicProtocol where Self.Assoc == HA_PublicStruct {
extension HA_PublicProtocol where Assoc == HA_PublicStruct {
// CHECK: internal func constrained()
func constrained() {}
} // CHECK: {{^[}]}}
// CHECK-LABEL: extension HA_PublicProtocol where Self.Assoc == HB_InternalStruct {
extension HA_PublicProtocol where Assoc == HB_InternalStruct {
// CHECK: internal func constrained()
func constrained() {}
} // CHECK: {{^[}]}}
// CHECK-LABEL: extension HA_PublicProtocol where Self.Assoc == HC_PrivateStruct {
extension HA_PublicProtocol where Assoc == HC_PrivateStruct {
// CHECK: private func constrained()
func constrained() {}
} // CHECK: {{^[}]}}
// CHECK-LABEL: extension HB_InternalProtocol {
extension HB_InternalProtocol {
// CHECK: internal func unconstrained()
func unconstrained() {}
} // CHECK: {{^[}]}}
// CHECK-LABEL: extension HB_InternalProtocol where Self.Assoc == HA_PublicStruct {
extension HB_InternalProtocol where Assoc == HA_PublicStruct {
// CHECK: internal func constrained()
func constrained() {}
} // CHECK: {{^[}]}}
// CHECK-LABEL: extension HB_InternalProtocol where Self.Assoc == HB_InternalStruct {
extension HB_InternalProtocol where Assoc == HB_InternalStruct {
// CHECK: internal func constrained()
func constrained() {}
} // CHECK: {{^[}]}}
// CHECK-LABEL: extension HB_InternalProtocol where Self.Assoc == HC_PrivateStruct {
extension HB_InternalProtocol where Assoc == HC_PrivateStruct {
// CHECK: private func constrained()
func constrained() {}
} // CHECK: {{^[}]}}
// CHECK-LABEL: extension HC_PrivateProtocol {
extension HC_PrivateProtocol {
// CHECK: internal func unconstrained()
func unconstrained() {}
} // CHECK: {{^[}]}}
// CHECK-LABEL: extension HC_PrivateProtocol where Self.Assoc == HA_PublicStruct {
extension HC_PrivateProtocol where Assoc == HA_PublicStruct {
// CHECK: private func constrained()
func constrained() {}
} // CHECK: {{^[}]}}
// CHECK-LABEL: extension HC_PrivateProtocol where Self.Assoc == HB_InternalStruct {
extension HC_PrivateProtocol where Assoc == HB_InternalStruct {
// CHECK: private func constrained()
func constrained() {}
} // CHECK: {{^[}]}}
// CHECK-LABEL: extension HC_PrivateProtocol where Self.Assoc == HC_PrivateStruct {
extension HC_PrivateProtocol where Assoc == HC_PrivateStruct {
// CHECK: private func constrained()
func constrained() {}
} // CHECK: {{^[}]}}
public protocol IA_PublicAssocTypeProto {
associatedtype PublicValue
var publicValue: PublicValue { get }
}
fileprivate protocol IB_FilePrivateAssocTypeProto {
associatedtype FilePrivateValue
var filePrivateValue: FilePrivateValue { get }
}
// CHECK-LABEL: public{{(\*/)?}} class IC_PublicAssocTypeImpl : IA_PublicAssocTypeProto, IB_FilePrivateAssocTypeProto {
public class IC_PublicAssocTypeImpl: IA_PublicAssocTypeProto, IB_FilePrivateAssocTypeProto {
public var publicValue: Int = 0
public var filePrivateValue: Int = 0
// CHECK-DAG: {{^}} public typealias PublicValue
// CHECK-DAG: {{^}} public typealias FilePrivateValue
} // CHECK: {{^[}]}}
// CHECK-LABEL: private{{(\*/)?}} class ID_PrivateAssocTypeImpl : IA_PublicAssocTypeProto, IB_FilePrivateAssocTypeProto {
private class ID_PrivateAssocTypeImpl: IA_PublicAssocTypeProto, IB_FilePrivateAssocTypeProto {
public var publicValue: Int = 0
public var filePrivateValue: Int = 0
// CHECK-DAG: {{^}} internal typealias PublicValue
// CHECK-DAG: {{^}} internal typealias FilePrivateValue
} // CHECK: {{^[}]}}
// CHECK-LABEL: class MultipleAttributes {
class MultipleAttributes {
// CHECK: {{^}} final {{(/\*)?private(\*/)?}} func foo()
final private func foo() {}
} // CHECK: {{^[}]}}
// CHECK-LABEL: public{{(\*/)?}} class PublicInitBase {
public class PublicInitBase {
// CHECK: {{^}} {{(/\*)?public(\*/)?}} init()
public init() {}
// CHECK: {{^}} {{(/\*)?fileprivate(\*/)?}} init(other: PublicInitBase)
fileprivate init(other: PublicInitBase) {}
} // CHECK: {{^[}]}}
// CHECK-LABEL: public{{(\*/)?}} class PublicInitInheritor : PublicInitBase {
public class PublicInitInheritor : PublicInitBase {
// CHECK: {{^}} public init()
// CHECK: {{^}} fileprivate init(other: PublicInitBase)
} // CHECK: {{^[}]}}
// CHECK-LABEL: {{(/\*)?private(\*/)?}} class PublicInitPrivateInheritor : PublicInitBase {
private class PublicInitPrivateInheritor : PublicInitBase {
// CHECK: {{^}} internal init()
// CHECK: {{^}} fileprivate init(other: PublicInitBase)
} // CHECK: {{^[}]}}
| apache-2.0 | cffbab9b1dd64c1c042ba578c9d11157 | 30.356383 | 166 | 0.657252 | 3.816769 | false | false | false | false |
lanjing99/RxSwiftDemo | 23-mvvm-with-rxswift/starter/Tweetie/TweetieTests/TestData.swift | 3 | 2108 | /*
* Copyright (c) 2016-2017 Razeware LLC
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
import Foundation
import Accounts
import Unbox
@testable import Tweetie
class TestData {
static let account = ACAccount()
static let listId: ListIdentifier = (username:"user" , slug: "slug")
static let personJSON: [String: Any] = [
"id": 1,
"name": "Name",
"screen_name": "ScreeName",
"description": "Description",
"url": "url",
"profile_image_url_https": "profile_image_url_https",
]
static var personUserObject: User {
return (try! unbox(dictionary: personJSON))
}
static let tweetJSON: [String: Any] = [
"id": 1,
"text": "Text",
"user": [
"name": "Name",
"profile_image_url_https": "Url"
],
"created": "2011-11-11T20:00:00GMT"
]
static var tweetsJSON: [[String: Any]] {
return (1...3).map {
var dict = tweetJSON
dict["id"] = $0
return dict
}
}
static var tweets: [Tweet] {
return try! unbox(dictionaries: tweetsJSON, allowInvalidElements: true) as [Tweet]
}
}
| mit | 906a99a4d614a67d6756d16c58fb5441 | 30.939394 | 86 | 0.687856 | 3.954972 | false | false | false | false |
Rhumbix/SwiftyPaperTrail | SwiftyPaperTrailTests/BufferingService.swift | 1 | 1535 | //
// BufferingService.swift
// SwiftyPaperTrail
//
// Created by Mark Eschbach on 12/12/16.
// Copyright © 2016 Rhumbix, Inc. All rights reserved.
//
import CocoaAsyncSocket
class BufferingService : NSObject, GCDAsyncSocketDelegate {
var serviceSocket : GCDAsyncSocket!
var buffers = [BufferingClient]()
var disconnectionSignal : (( Data ) -> Void)?
func awaitData() -> UInt16 {
serviceSocket = GCDAsyncSocket(delegate: self, delegateQueue: DispatchQueue.init(label: "com.rhumbix.test"), socketQueue:DispatchQueue.init(label: "com.rhumbix.test.socket") )
try! serviceSocket.accept(onPort: 0)
return serviceSocket.localPort
}
func socket(_ sock: GCDAsyncSocket, didAcceptNewSocket newSocket: GCDAsyncSocket) {
let target = Data()
let client = BufferingClient(clientSocket: newSocket, target: target)
buffers.append(client)
}
}
class BufferingClient : NSObject, GCDAsyncSocketDelegate {
var socket : GCDAsyncSocket
var buffer : Data
init( clientSocket : GCDAsyncSocket, target : Data ){
socket = clientSocket
buffer = target
super.init()
socket.delegate = self
socket.readData(withTimeout: -1, tag: 0)
}
func socket(_ sock: GCDAsyncSocket, didRead data: Data, withTag tag: Int) {
buffer.append(data)
sock.readData(withTimeout: -1, tag: 0)
}
func socketDidDisconnect(_ sock: GCDAsyncSocket, withError err: Error?) {
print("Socket closed: \(err)")
}
}
| mit | 783a1eb0d0f42d71064f998c0e2b008d | 29.68 | 183 | 0.671447 | 4.345609 | false | false | false | false |
Legoless/iOS-Course | 2015-1/Lesson3/Gamebox/Gamebox/ViewController.swift | 1 | 1774 | //
// ViewController.swift
// Gamebox
//
// Created by Dal Rupnik on 21/10/15.
// Copyright © 2015 Unified Sense. All rights reserved.
//
import UIKit
class ViewController: UIViewController, UITextFieldDelegate {
let manager = GameManager()
@IBOutlet weak var resultLabel: UILabel!
@IBOutlet weak var nameTextField: UITextField!
@IBOutlet weak var priorityTextField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
resultLabel.text = "Click to add game!"
nameTextField.delegate = self
priorityTextField.delegate = self
if let gameName = NSUserDefaults.standardUserDefaults().objectForKey("GameName") as? String {
nameTextField.text = gameName
}
}
func textFieldDidEndEditing(textField: UITextField) {
print("ENDED EDITING")
if (textField == self.nameTextField)
{
print ("NAME ENDED")
}
}
@IBAction func addGameButtonTap(sender: UIButton) {
if let name = nameTextField.text, priority = UInt(priorityTextField.text!) where name.characters.count > 0 {
let game = Game(name: name, priority: priority)
manager.games.append(game)
resultLabel.text = "Added! There are \(manager.games.count) games in database!"
resultLabel.textColor = UIColor.blackColor()
NSUserDefaults.standardUserDefaults().setObject(name, forKey: "GameName")
NSUserDefaults.standardUserDefaults().synchronize()
}
else {
resultLabel.text = "Verify your data!"
resultLabel.textColor = UIColor.redColor()
}
}
}
| mit | a2138af149fa199ca5bd91c0bc078803 | 27.596774 | 116 | 0.606881 | 5.261128 | false | false | false | false |
nathawes/swift | test/Generics/existential_restrictions.swift | 5 | 3977 | // RUN: %target-typecheck-verify-swift -enable-objc-interop
protocol P { }
@objc protocol OP { }
protocol CP : class { }
@objc protocol SP : OP {
static func createNewOne() -> SP
}
func fP<T : P>(_ t: T) { }
// expected-note@-1 {{required by global function 'fP' where 'T' = 'P'}}
// expected-note@-2 {{required by global function 'fP' where 'T' = 'OP & P'}}
func fOP<T : OP>(_ t: T) { }
// expected-note@-1 {{required by global function 'fOP' where 'T' = 'OP & P'}}
func fOPE(_ t: OP) { }
func fSP<T : SP>(_ t: T) { }
func fAO<T : AnyObject>(_ t: T) { }
// expected-note@-1 {{where 'T' = 'P'}}
// expected-note@-2 {{where 'T' = 'CP'}}
// expected-note@-3 {{where 'T' = 'OP & P'}}
func fAOE(_ t: AnyObject) { }
func fT<T>(_ t: T) { }
func testPassExistential(_ p: P, op: OP, opp: OP & P, cp: CP, sp: SP, any: Any, ao: AnyObject) {
fP(p) // expected-error{{protocol 'P' as a type cannot conform to the protocol itself; only concrete types such as structs, enums and classes can conform to protocols}}
fAO(p) // expected-error{{global function 'fAO' requires that 'P' be a class type}}
fAOE(p) // expected-error{{argument type 'P' expected to be an instance of a class or class-constrained type}}
fT(p)
fOP(op)
fAO(op)
fAOE(op)
fT(op)
fAO(cp) // expected-error{{global function 'fAO' requires that 'CP' be a class type}}
fAOE(cp)
fT(cp)
fP(opp) // expected-error{{protocol 'OP & P' as a type cannot conform to 'P'; only concrete types such as structs, enums and classes can conform to protocols}}
fOP(opp) // expected-error{{protocol 'OP & P' as a type cannot conform to 'OP'; only concrete types such as structs, enums and classes can conform to protocols}}
fAO(opp) // expected-error{{global function 'fAO' requires that 'OP & P' be a class type}}
fAOE(opp)
fT(opp)
fOP(sp)
fSP(sp) // expected-error{{'SP' cannot be used as a type conforming to protocol 'SP' because 'SP' has static requirements}}
fAO(sp)
fAOE(sp)
fT(sp)
fT(any)
fAO(ao)
fAOE(ao)
}
class GP<T : P> {}
class GOP<T : OP> {}
class GCP<T : CP> {}
class GSP<T : SP> {}
class GAO<T : AnyObject> {} // expected-note 2{{requirement specified as 'T' : 'AnyObject'}}
func blackHole(_ t: Any) {}
func testBindExistential() {
blackHole(GP<P>()) // expected-error{{protocol 'P' as a type cannot conform to the protocol itself; only concrete types such as structs, enums and classes can conform to protocols}}
blackHole(GOP<OP>())
blackHole(GCP<CP>()) // expected-error{{protocol 'CP' as a type cannot conform to the protocol itself; only concrete types such as structs, enums and classes can conform to protocols}}
blackHole(GAO<P>()) // expected-error{{'GAO' requires that 'P' be a class type}}
blackHole(GAO<OP>())
blackHole(GAO<CP>()) // expected-error{{'GAO' requires that 'CP' be a class type}}
blackHole(GSP<SP>()) // expected-error{{'SP' cannot be used as a type conforming to protocol 'SP' because 'SP' has static requirements}}
blackHole(GAO<AnyObject>())
}
// rdar://problem/21087341
protocol Mine {}
class M1: Mine {}
class M2: Mine {}
extension Collection where Iterator.Element : Mine {
// expected-note@-1 {{required by referencing instance method 'takeAll()' on 'Collection'}}
func takeAll() {}
}
func foo() {
let allMine: [Mine] = [M1(), M2(), M1()]
// FIXME: we used to have a better diagnostic here -- the type checker
// would admit the conformance Mine : Mine, and later when computing
// substitutions, a specific diagnostic was generated. Now the
// conformance is rejected because Mine is not @objc, and we hit the
// generic no overloads error path. The error should actually talk
// about the return type, and this can happen in other contexts as well;
// <rdar://problem/21900971> tracks improving QoI here.
allMine.takeAll() // expected-error{{protocol 'Mine' as a type cannot conform to the protocol itself; only concrete types such as structs, enums and classes can conform to protocols}}
}
| apache-2.0 | ad1f5dbac42db1845fc4d2239ac4780b | 40.427083 | 186 | 0.672115 | 3.297678 | false | false | false | false |
blstream/StudyBox_iOS | StudyBox_iOS/TestViewController.swift | 1 | 18227 | import UIKit
import SVProgressHUD
enum TestModeTipOrQuestion {
case Tip, Question
}
class TestViewController: StudyBoxViewController {
@IBOutlet var testView: UIView!
@IBOutlet weak var questionView: UIView!
@IBOutlet weak var questionLabel: UILabel!
@IBOutlet weak var tipButton: UIButton!
@IBOutlet weak var answerView: UIView!
@IBOutlet weak var answerLabel: UILabel!
@IBOutlet weak var correctButton: UIButton!
@IBOutlet weak var incorrectButton: UIButton!
@IBOutlet weak var editFlashcardBarButton: UIBarButtonItem!
@IBOutlet weak var previousTipButton: UIButton!
@IBOutlet weak var nextTipButton: UIButton!
@IBOutlet weak var scoreLabel: UILabel!
@IBOutlet weak var currentQuestionNumber: UILabel!
@IBOutlet weak var answerLeading: NSLayoutConstraint!
@IBOutlet var answerTrailing: NSLayoutConstraint!
var testLogicSource: Test?
private lazy var dataManager: DataManager = UIApplication.appDelegate().dataManager
var tipsForFlashcard = [Tip]()
var currentTipNumber = 0
var tipOrQuestionMode = TestModeTipOrQuestion.Question
override func viewDidLoad() {
super.viewDidLoad()
/*
Because one Gesture Rec. can be added only to one view, we have to make a second one.
There are seperate GR's to avoid situation when user presses the button and
moves out of the button upwards because he changes his mind as to answering correct/incorrect or showing the tip.
*/
let swipeLeftForAnswer = UISwipeGestureRecognizer()
swipeLeftForAnswer.direction = .Left
swipeLeftForAnswer.delegate = self
swipeLeftForAnswer.addTarget(self, action: #selector(TestViewController.swipedLeft))
questionView.userInteractionEnabled = true
questionView.addGestureRecognizer(swipeLeftForAnswer)
let swipeUpQuestionLabel = UISwipeGestureRecognizer()
swipeUpQuestionLabel.direction = .Up
swipeUpQuestionLabel.delegate = self
swipeUpQuestionLabel.addTarget(self, action: #selector(TestViewController.swipedUp))
questionLabel.userInteractionEnabled = true
questionLabel.addGestureRecognizer(swipeUpQuestionLabel)
let swipeUpAnswerLabel = UISwipeGestureRecognizer()
swipeUpAnswerLabel.direction = .Up
swipeUpAnswerLabel.addTarget(self, action: #selector(TestViewController.swipedUp))
answerLabel.userInteractionEnabled = true
answerLabel.addGestureRecognizer(swipeUpAnswerLabel)
//Set the navigation bar title to current deck name
if let test = testLogicSource {
self.title = test.deck.name
//If user is logged in and emails match, we're the author so we can edit flashcards
if let email = dataManager.remoteDataManager.user?.email {
editFlashcardBarButton.enabled = test.deck.owner == email
} else { //user is not logged in
editFlashcardBarButton.enabled = false
}
if test.allFlashcardsHidden {
//Alert if passed deck have all flashcards hidden
self.presentAlertController(withTitle: "Uwaga!", message: "Wszystkie fiszki w tali są ukryte", buttonText: "OK", actionCompletion: {
DrawerViewController.sharedSbDrawerViewControllerChooseMenuOption(atIndex: 0)
})
}
if test.passedDeckWasEmpty {
//Alert if passed deck was empty.
self.presentAlertController(withTitle: "Uwaga!", message: "Talia jest pusta.", buttonText: "OK")
}
}
tipButton.backgroundColor = UIColor.sb_Grey()
correctButton.backgroundColor = UIColor.sb_Grey()
incorrectButton.backgroundColor = UIColor.sb_Grey()
questionLabel.backgroundColor = UIColor.sb_Grey()
answerLabel.backgroundColor = UIColor.sb_Grey()
correctButton.imageView?.contentMode = .ScaleAspectFit
incorrectButton.imageView?.contentMode = .ScaleAspectFit
previousTipButton.imageView?.contentMode = .ScaleAspectFit
nextTipButton.imageView?.contentMode = .ScaleAspectFit
previousTipButton.hidden = true
nextTipButton.hidden = true
tipOrQuestionMode = .Question
tipButton.titleLabel?.font = UIFont.sbFont(size: sbFontSizeLarge, bold: false)
correctButton.titleLabel?.font = UIFont.sbFont(size: sbFontSizeLarge, bold: false)
incorrectButton.titleLabel?.font = UIFont.sbFont(size: sbFontSizeLarge, bold: false)
questionLabel.font = UIFont.sbFont(size: sbFontSizeLarge, bold: false)
answerLabel.font = UIFont.sbFont(size: sbFontSizeLarge, bold: false)
scoreLabel.font = UIFont.sbFont(size: sbFontSizeMedium, bold: false)
currentQuestionNumber.font = UIFont.sbFont(size: sbFontSizeMedium, bold: false)
currentQuestionNumber.text = "#1"
updateQuestionUiForCurrentCard()
updateAnswerUiForCurrentCard()
answerTrailing.active = false
answerLeading.constant = view.frame.width
}
override func shouldPerformSegueWithIdentifier(identifier: String, sender: AnyObject?) -> Bool {
if let testLogic = testLogicSource {
if identifier == "ScoreSegue" {
switch testLogic.testType {
case .Learn:
let controller = UIAlertController(title: "Koniec", message: "To już wszystkie fiszki, czy chcesz rozpocząć naukę od nowa?",
preferredStyle: .Alert)
controller.addAction(
UIAlertAction(title: "Tak", style: .Default,
handler: { _ in
if let repeatDeck = testLogic.repeatDeck {
self.testLogicSource = Test(flashcards: repeatDeck, testType: .Learn, deck: testLogic.deck)
self.answeredQuestionTransition()
}
})
)
controller.addAction(
UIAlertAction(title: "Nie", style: .Default,
handler: { _ in
// TODOs: refactor, make enums for DrawerViewControllers menu options
DrawerViewController.sharedSbDrawerViewControllerChooseMenuOption(atIndex: 0)
})
)
presentViewController(controller, animated: true, completion: nil)
return false
default:
return true
}
}
}
return true
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if let nextViewController = segue.destinationViewController as? ScoreViewController {
nextViewController.testLogicSource = testLogicSource
}
}
func swipedLeft(){
view.layoutIfNeeded()
self.answerLeading.constant = 0
UIView.animateWithDuration(0.5, delay: 0, options: [.CurveEaseOut], animations: {
self.answerTrailing.active = true
self.view.layoutIfNeeded()
self.questionView.center.x = self.testView.center.x - self.testView.frame.size.width
}, completion: nil)
}
func swipedUp(){
UIView.animateWithDuration(0.5, delay: 0, options: [.CurveEaseOut], animations: {
//move views up
self.questionView.center.y = self.questionView.center.y - self.testView.frame.size.height
self.answerView.center.y = self.answerView.center.y - self.testView.frame.size.height
//set alpha to 0 to prepare for next animation +fade-out effect
self.questionView.alpha = 0
self.answerView.alpha = 0
}, completion: { _ in
if let testLogic = self.testLogicSource {
testLogic.skipCard()
}
self.updateQuestionUiForCurrentCard()
self.updateAnswerUiForCurrentCard()
//set views to show questionView after animation
self.questionView.center.x = self.testView.center.x
self.answerTrailing.active = false
self.answerLeading.constant = self.view.frame.width
//move views back to their correct Y position
self.questionView.center.y = self.questionView.center.y + self.testView.frame.size.height
self.answerView.center.y = self.answerView.center.y + self.testView.frame.size.height
//animate alpha back to 1
UIView.animateWithDuration(0.5, delay: 0, options: [.CurveEaseOut], animations: {
self.questionView.alpha = 1
self.answerView.alpha = 1
}, completion: nil)
})
}
@IBAction func showTip(sender: AnyObject) {
switch tipOrQuestionMode {
case .Question: //If current is Question, we're switching to Tip mode
if let currentCard = testLogicSource?.currentCard {
dataManager.allTipsForFlashcard(currentCard.deckId, flashcardID: currentCard.serverID, completion: { response in
switch response {
case .Success(let tipsFromManager):
guard !tipsFromManager.isEmpty else {
SVProgressHUD.showInfoWithStatus("Fiszka nie ma podpowiedzi")
return
}
self.tipsForFlashcard = tipsFromManager.sort {
return $0.difficulty < $1.difficulty
}
self.previousTipButton.tintColor = UIColor.sb_Grey()
self.previousTipButton.userInteractionEnabled = false
self.nextTipButton.userInteractionEnabled = true
self.nextTipButton.tintColor = UIColor.sb_Graphite()
self.tipOrQuestionMode = .Tip
self.currentTipNumber = 0
self.tipButton.setTitle("Pytanie", forState: .Normal)
self.updateUIForTipMode(.Tip)
case .Error(let err):
print(err)
SVProgressHUD.showErrorWithStatus("Nie można pobrać podpowiedzi dla fiszki.")
}
})
}
case .Tip: //If current is Tip, we're switching to Question mode
updateUIForTipMode(.Question)
currentTipNumber = 0
tipOrQuestionMode = .Question
}
}
@IBAction func nextTipAction(sender: AnyObject) {
currentTipNumber += 1
if currentTipNumber == tipsForFlashcard.count-1 { //last tip
UIView.animateWithDuration(0.25) {
self.previousTipButton.tintColor = UIColor.sb_Graphite()
self.nextTipButton.tintColor = UIColor.sb_Grey()
}
self.nextTipButton.userInteractionEnabled = false
}
if currentTipNumber == 1 {
self.previousTipButton.userInteractionEnabled = true
UIView.animateWithDuration(0.25) {
self.previousTipButton.tintColor = UIColor.sb_Graphite()
}
}
self.questionLabel.text = tipsForFlashcard[currentTipNumber].content
}
@IBAction func previousTipAction(sender: AnyObject) {
currentTipNumber -= 1
if currentTipNumber == 0 { //first tip
UIView.animateWithDuration(0.25) {
self.previousTipButton.tintColor = UIColor.sb_Grey()
self.nextTipButton.tintColor = UIColor.sb_Graphite()
}
self.previousTipButton.userInteractionEnabled = false
}
if currentTipNumber == tipsForFlashcard.count-2 {
UIView.animateWithDuration(0.25) {
self.nextTipButton.tintColor = UIColor.sb_Graphite()
}
self.nextTipButton.userInteractionEnabled = true
}
self.questionLabel.text = tipsForFlashcard[currentTipNumber].content
}
func updateUIForTipMode(mode: TestModeTipOrQuestion) {
switch mode {
case .Question:
previousTipButton.hidden = true
nextTipButton.hidden = true
tipButton.setTitle("Podpowiedź", forState: .Normal)
questionLabel.text = testLogicSource?.currentCard?.question
case .Tip:
if self.tipsForFlashcard.count > 1 {
self.previousTipButton.hidden = false
self.nextTipButton.hidden = false
}
tipButton.setTitle("Pytanie", forState: .Normal)
questionLabel.text = tipsForFlashcard[currentTipNumber].content
}
}
func updateQuestionUiForCurrentCard() {
if let testLogic = testLogicSource {
let points = testLogic.cardsAnsweredAndPossible()
scoreLabel.text = "\(points.0) / \(points.1)"
}
updateUIForTipMode(.Question)
}
func updateAnswerUiForCurrentCard() {
if let test = testLogicSource, card = test.currentCard {
answerLabel.text = card.answer
currentQuestionNumber.text = "#\(test.index)"
}
}
func updateForAnswer(correct: Bool) {
if let testLogic = testLogicSource {
if (correct ? testLogic.correctAnswer() : testLogic.incorrectAnswer()) != nil {
answeredQuestionTransition()
} else {
if shouldPerformSegueWithIdentifier("ScoreSegue", sender: self) {
performSegueWithIdentifier("ScoreSegue", sender: self)
}
}
}
}
@IBAction func correctAnswer(sender: AnyObject) { updateForAnswer(true) }
@IBAction func incorrectAnswer(sender: AnyObject) { updateForAnswer(false) }
///Global time setting for button scale animations
let buttonsAnimationTime: NSTimeInterval = 0.1
///Global scale setting for button scale animations
let buttonsScaleWhenPressed = CGAffineTransformMakeScale(0.85, 0.85)
@IBAction func correctButtonTouchDown(sender: AnyObject) {
UIView.animateWithDuration(buttonsAnimationTime, delay: 0, options: .CurveEaseOut, animations: {
self.correctButton.transform = self.buttonsScaleWhenPressed }, completion:nil )
}
@IBAction func correctTouchDragExit(sender: AnyObject) {
UIView.animateWithDuration(buttonsAnimationTime, delay: 0, options: .CurveEaseOut, animations: {
self.correctButton.transform = CGAffineTransformIdentity }, completion:nil )
}
@IBAction func correctTouchCancel(sender: AnyObject) {
UIView.animateWithDuration(buttonsAnimationTime, delay: 0, options: .CurveEaseOut, animations: {
self.correctButton.transform = CGAffineTransformIdentity }, completion:nil )
}
@IBAction func incorrectButtonTouchDown(sender: AnyObject) {
UIView.animateWithDuration(buttonsAnimationTime, delay:0, options: .CurveEaseOut, animations: {
self.incorrectButton.transform = self.buttonsScaleWhenPressed }, completion:nil )
}
@IBAction func incorrectTouchDragExit(sender: AnyObject) {
UIView.animateWithDuration(buttonsAnimationTime, delay: 0, options: .CurveEaseOut, animations: {
self.incorrectButton.transform = CGAffineTransformIdentity }, completion:nil )
}
@IBAction func incorrectTouchCancel(sender: AnyObject) {
UIView.animateWithDuration(buttonsAnimationTime, delay: 0, options: .CurveEaseOut, animations: {
self.incorrectButton.transform = CGAffineTransformIdentity }, completion:nil )
}
///Animation sequence to go back to starting point and display `questionView`
func answeredQuestionTransition(){
questionView.alpha = 0
questionView.center.x = testView.center.x
updateQuestionUiForCurrentCard()
//move answerView outside of the screen
answerTrailing.active = false
answerLeading.constant = view.frame.width
//animate dissolving of views
UIView.animateWithDuration(0.5, delay: 0, options: [.CurveEaseInOut],
animations: {
self.answerView.alpha = 0
self.questionView.alpha = 1
},
completion: { _ in
self.answerView.alpha = 1
})
//set buttons size back to normal
incorrectButton.transform = CGAffineTransformIdentity
correctButton.transform = CGAffineTransformIdentity
tipOrQuestionMode = .Question
updateAnswerUiForCurrentCard()
}
@IBAction func editCurrentFlashcard(sender: UIBarButtonItem) {
if let testLogicSource = testLogicSource, card = testLogicSource.currentCard,
editFlashcardNavigation = storyboard?.instantiateViewControllerWithIdentifier(Utils.UIIds.EditFlashcardViewControllerID),
editFlashcardViewController = editFlashcardNavigation.childViewControllers[0] as? EditFlashcardViewController {
editFlashcardViewController.mode = EditFlashcardViewControllerMode.Modify(flashcard: card, updateCallback: {[weak self] ( _ ) in
self?.updateQuestionUiForCurrentCard()
self?.updateAnswerUiForCurrentCard()
})
presentViewController(editFlashcardNavigation, animated: true, completion: nil)
}
}
}
extension TestViewController: UIGestureRecognizerDelegate {
func gestureRecognizer(gestureRecognizer: UIGestureRecognizer,
shouldRecognizeSimultaneouslyWithGestureRecognizer otherGestureRecognizer: UIGestureRecognizer) -> Bool {
return true
}
}
| apache-2.0 | 768c01971ea6283a0b05f075c068ec0a | 45.358779 | 148 | 0.623799 | 5.25346 | false | true | false | false |
xedin/swift | test/TBD/specialization.swift | 3 | 2052 | // Validate the the specializations actually exist (if they don't then we're not
// validating that they end up with the correct linkages):
// RUN: %target-swift-frontend -emit-sil -o- -O -validate-tbd-against-ir=none %s | %FileCheck %s
// RUN: %target-swift-frontend -emit-ir -o/dev/null -O -validate-tbd-against-ir=all %s
// RUN: %target-swift-frontend -emit-ir -o/dev/null -O -validate-tbd-against-ir=all -enable-library-evolution %s
// With -enable-testing:
// RUN: %target-swift-frontend -emit-ir -o/dev/null -O -validate-tbd-against-ir=all -enable-testing %s
// RUN: %target-swift-frontend -emit-ir -o/dev/null -O -validate-tbd-against-ir=all -enable-library-evolution -enable-testing %s
// RUN: %empty-directory(%t)
// RUN: %target-swift-frontend -typecheck -parse-as-library -module-name test %s -emit-tbd -emit-tbd-path %t/typecheck.tbd
// RUN: %target-swift-frontend -emit-ir -parse-as-library -module-name test %s -emit-tbd -emit-tbd-path %t/emit-ir.tbd
// RUN: diff -u %t/typecheck.tbd %t/emit-ir.tbd
// rdar://problem/40738913
open class Foo {
@inline(never)
fileprivate func foo<T>(_: T.Type) {}
}
open class Bar<T> {
public init() {
bar()
}
@inline(never)
fileprivate func bar() {}
}
public func f() {
Foo().foo(Int.self)
Bar<Int>().bar()
}
// Generic specialization, from the foo call in f
// CHECK-LABEL: // specialized Foo.foo<A>(_:)
// CHECK-NEXT: sil private [noinline] @$s14specialization3FooC3foo33_A6E3E43DB6679655BDF5A878ABC489A0LLyyxmlFSi_Tg5Tf4dd_n : $@convention(thin) () -> ()
// Function signature specialization, from the bar call in Bar.init
// CHECK-LABEL: // specialized Bar.bar()
// CHECK-NEXT: sil private [noinline] @$s14specialization3BarC3bar33_A6E3E43DB6679655BDF5A878ABC489A0LLyyFTf4d_n : $@convention(thin) () -> () {
// Generic specialization, from the bar call in f
// CHECK-LABEL: // specialized Bar.bar()
// CHECK-NEXT: sil private [noinline] @$s14specialization3BarC3bar33_A6E3E43DB6679655BDF5A878ABC489A0LLyyFSi_Tg5Tf4d_n : $@convention(thin) () -> ()
| apache-2.0 | dfe37a29d9d0b2438d0d39b5e28389ef | 40.04 | 152 | 0.703216 | 2.931429 | false | true | false | false |
JohnSansoucie/MyProject2 | BlueCap/Profiles/ServiceProfilesViewController.swift | 1 | 1831 | //
// ServiceProfilesViewController.swift
// BlueCapUI
//
// Created by Troy Stribling on 6/5/14.
// Copyright (c) 2014 gnos.us. All rights reserved.
//
import UIKit
import BlueCapKit
class ServiceProfilesViewController : ServiceProfilesTableViewController {
struct MainStoryboard {
static let serviceProfileCell = "ServiceProfileCell"
static let serviceCharacteristicProfilesSegue = "ServiceCharacteristicProfiles"
}
override var serviceProfileCell : String {
return MainStoryboard.serviceProfileCell
}
required init(coder aDecoder:NSCoder) {
super.init(coder:aDecoder)
}
override func viewDidLoad() {
super.viewDidLoad()
self.styleNavigationBar()
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
self.navigationItem.title = "Service Profiles"
}
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
self.navigationItem.title = ""
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
override func prepareForSegue(segue:UIStoryboardSegue, sender:AnyObject!) {
if segue.identifier == MainStoryboard.serviceCharacteristicProfilesSegue {
if let selectedIndex = self.tableView.indexPathForCell(sender as UITableViewCell) {
let tag = self.serviceProfiles.keys.array
if let profiles = self.serviceProfiles[tag[selectedIndex.section]] {
let viewController = segue.destinationViewController as ServiceCharacteristicProfilesViewController
viewController.serviceProfile = profiles[selectedIndex.row]
}
}
}
}
}
| mit | 632a87afce507e996d70001037de0aad | 31.122807 | 119 | 0.666303 | 5.498498 | false | false | false | false |
fahidattique55/FAPanels | FAPanels/CenterVC.swift | 1 | 7492 | //
// CenterVC.swift
// FAPanels
//
// Created by Fahid Attique on 17/06/2017.
// Copyright © 2017 Fahid Attique. All rights reserved.
//
import UIKit
class CenterVC: UIViewController {
// MARK:- IBOutlets
@IBOutlet var centerPanelOnlyAnimOpts: UITextField!
@IBOutlet var centerPanelOnlyAnimDuration: UILabel!
@IBOutlet var pickerView: UIPickerView!
@IBOutlet var leftAllowableEdge: UILabel!
@IBOutlet var rightAllowableEdge: UILabel!
@IBOutlet var sidePanelsOpenAnimDuration: UILabel!
@IBOutlet var leftPanelPositionSwitch: UISwitch!
@IBOutlet var rightPanelPositionSwitch: UISwitch!
// MARK:- Class Properties
fileprivate let mainStoryboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
var pickerDataSource: [String] = ["flipFromLeft", "flipFromRight", "flipFromTop", "flipFromBottom", "curlUp", "curlDown", "crossDissolve", "moveRight", "moveLeft", "moveUp", "moveDown", "splitHorizotally", "splitVertically", "dumpFall", "boxFade"]
// MARK:- Life Cycle
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
viewConfigurations()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Functions
func viewConfigurations() {
pickerView.delegate = self
pickerView.dataSource = self
centerPanelOnlyAnimOpts.delegate = self
centerPanelOnlyAnimOpts.inputView = pickerView
leftPanelPositionSwitch.setOn(panel!.isLeftPanelOnFront, animated: false)
rightPanelPositionSwitch.setOn(panel!.isRightPanelOnFront, animated: false)
// Resetting the Panel Configs...
panel!.configs = FAPanelConfigurations()
panel!.configs.rightPanelWidth = 80
panel!.configs.bounceOnRightPanelOpen = false
panel!.delegate = self
}
func setCenterPanelAnimType( _ selectedRow: Int) {
var animOptions: FAPanelTransitionType = .crossDissolve
switch selectedRow {
case 0:
animOptions = .flipFromLeft
case 1:
animOptions = .flipFromRight
case 2:
animOptions = .flipFromTop
case 3:
animOptions = .flipFromBottom
case 4:
animOptions = .curlUp
case 5:
animOptions = .curlDown
case 6:
animOptions = .crossDissolve
case 7:
animOptions = .moveRight
case 8:
animOptions = .moveLeft
case 9:
animOptions = .moveUp
case 10:
animOptions = .moveDown
case 11:
animOptions = .splitHorizontally
case 12:
animOptions = .splitVertically
case 13:
animOptions = .dumpFall
case 14:
animOptions = .boxFade
default:
animOptions = .crossDissolve
}
panel!.configs.centerPanelTransitionType = animOptions
}
// MARK: - IBActions
@IBAction func showRightVC(_ sender: Any) {
panel?.openRight(animated: true)
}
@IBAction func showLeftVC(_ sender: Any) {
panel?.openLeft(animated: true)
}
@IBAction func updateRightPanelPosition(_ sender: UISwitch) {
panel?.rightPanelPosition = sender.isOn ? .front : .back
}
@IBAction func updateLeftPanelPosition(_ sender: UISwitch) {
panel?.leftPanelPosition = sender.isOn ? .front : .back
}
@IBAction func changeCenterVC(_ sender: UIButton) {
var identifier = ""
if sender.isSelected {
identifier = "CenterVC1"
}
else{
identifier = "CenterVC2"
}
let centerVC: UIViewController = mainStoryboard.instantiateViewController(withIdentifier: identifier)
let centerNavVC = UINavigationController(rootViewController: centerVC)
_ = panel!.center(centerNavVC)
sender.isSelected = !sender.isSelected
}
@IBAction func updateAnimDuration(_ sender: UIStepper) {
let valueAsText = String(format: "%.2f", sender.value/100)
centerPanelOnlyAnimDuration.text = valueAsText
panel!.configs.centerPanelTransitionDuration = TimeInterval(Double(valueAsText)!)
}
@IBAction func updatePanFromEdge(_ sender: UISwitch) {
panel!.configs.panFromEdge = sender.isOn
}
@IBAction func updateLeftEdgeValue(_ sender: UIStepper) {
let sliderValueAsText = String(format: "%.0f", sender.value)
leftAllowableEdge.text = sliderValueAsText
panel!.configs.minEdgeForLeftPanel = CGFloat(Double(sliderValueAsText)!)
}
@IBAction func updateRightEdgeValue(_ sender: UIStepper) {
let sliderValueAsText = String(format: "%.0f", sender.value)
rightAllowableEdge.text = sliderValueAsText
panel!.configs.minEdgeForRightPanel = CGFloat(Double(sliderValueAsText)!)
}
@IBAction func updateSidePanelsOpenAnimDuration(_ sender: UIStepper) {
let sliderValueAsText = String(format: "%.2f", sender.value/100)
sidePanelsOpenAnimDuration.text = sliderValueAsText
panel!.configs.maxAnimDuration = CGFloat(Double(sliderValueAsText)!)
}
}
extension CenterVC: UITextFieldDelegate {
func textFieldDidBeginEditing(_ textField: UITextField) {
if textField === centerPanelOnlyAnimOpts {
}
}
func textFieldDidEndEditing(_ textField: UITextField) {
if textField === centerPanelOnlyAnimOpts {
let selectedRow = pickerView.selectedRow(inComponent: 0)
textField.text = pickerDataSource[selectedRow]
setCenterPanelAnimType(selectedRow)
}
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
}
extension CenterVC: UIPickerViewDelegate, UIPickerViewDataSource {
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return pickerDataSource.count
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
return pickerDataSource[row]
}
}
extension CenterVC: FAPanelStateDelegate {
func centerPanelWillBecomeActive() {
print("centerPanelWillBecomeActive called")
}
func centerPanelDidBecomeActive() {
print("centerPanelDidBecomeActive called")
}
func leftPanelWillBecomeActive() {
print("leftPanelWillBecomeActive called")
}
func leftPanelDidBecomeActive() {
print("leftPanelDidBecomeActive called")
}
func rightPanelWillBecomeActive() {
print("rightPanelWillBecomeActive called")
}
func rightPanelDidBecomeActive() {
print("rightPanelDidBecomeActive called")
}
}
| apache-2.0 | 970ca16a53fba960cdbe74cb61fda259 | 23.400651 | 251 | 0.617007 | 5.169772 | false | false | false | false |
shridharmalimca/iOSDev | iOS/Swift 3.0/LocationTracking/LocationTracking/LocationManagerHelper.swift | 2 | 8998 | import UIKit
import CoreLocation
class LocationManagerHelper: NSObject {
let locationManager = CLLocationManager()
static let sharedInstance = LocationManagerHelper()
var latitude = Double()
var longitude = Double()
var userLocation = CLLocation()
var speedInKmPerHour: Double = 0.0
var previousSpeedInKmPerHour: Double = 0.0
var timer = Timer()
var isTimerSetForSpeed: Bool = false
var isSpeedChanged: Bool = false
var currentTimeInterval: Int = 0
var nextTimeInterval:Int = 0
public func updateUserLocation() {
locationManager.requestWhenInUseAuthorization()
locationManager.requestAlwaysAuthorization()
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.startUpdatingLocation()
}
public func stopLocationUpdate() {
locationManager.stopUpdatingLocation()
}
public func getLocation(latitude: Double, longitude: Double) -> CLLocation {
return CLLocation(latitude: latitude, longitude: longitude)
}
public func locationUpdatesAsPerCalculatedSpeedOfVehicle() {
// Manual testing for speed using Textfield on the home view controller
/* if speedInKmPerHour != previousSpeedInKmPerHour && previousSpeedInKmPerHour > 0.0 {
isSpeedChanged = true
} else {
isSpeedChanged = false
}*/
if isSpeedChanged {
if (speedInKmPerHour > 0 || speedInKmPerHour < 30) && previousSpeedInKmPerHour < 30 {
if speedInKmPerHour > 30 {
isTimerSetForSpeed = false
} else {
isTimerSetForSpeed = true
}
} else if (speedInKmPerHour > 30 || speedInKmPerHour < 60) && previousSpeedInKmPerHour < 60 {
if speedInKmPerHour > 60 {
isTimerSetForSpeed = false
} else {
isTimerSetForSpeed = true
}
} else if (speedInKmPerHour > 60 || speedInKmPerHour < 60) && previousSpeedInKmPerHour < 80 {
if speedInKmPerHour > 80 {
isTimerSetForSpeed = false
} else {
isTimerSetForSpeed = true
}
} else if previousSpeedInKmPerHour >= 80 || previousSpeedInKmPerHour >= 60 && speedInKmPerHour < 30 {
isTimerSetForSpeed = false
} else if (speedInKmPerHour > 80 || speedInKmPerHour < 80) && previousSpeedInKmPerHour < 500 {
if speedInKmPerHour > 80 {
isTimerSetForSpeed = false
} else {
isTimerSetForSpeed = true
}
} else {
isTimerSetForSpeed = false
}
}
switch speedInKmPerHour {
case 0..<30:
// capture location after 5 mins
print("0..<30 KM/h")
if (!isTimerSetForSpeed) {
stopTimer()
setTimer(timeInterval: 300) // 60 * 5
previousSpeedInKmPerHour = speedInKmPerHour
currentTimeInterval = 300
nextTimeInterval = 120
}
case 30..<60:
// capture location after 2 mins
print("30..<60 KM/h")
if !isTimerSetForSpeed {
stopTimer()
setTimer(timeInterval: 120) // 60 * 2
previousSpeedInKmPerHour = speedInKmPerHour
currentTimeInterval = 120
nextTimeInterval = 60
} else {
}
case 60..<80:
// capture location after 1 mins
print("60..<80 KM/h")
if !isTimerSetForSpeed {
stopTimer()
setTimer(timeInterval: 60)
previousSpeedInKmPerHour = speedInKmPerHour
currentTimeInterval = 60
nextTimeInterval = 30
}
case 80..<500:
// capture location after 30 secs
print("80..<500 KM/h")
if !isTimerSetForSpeed {
stopTimer()
setTimer(timeInterval: 30) // 30 sec
previousSpeedInKmPerHour = speedInKmPerHour
currentTimeInterval = 30
nextTimeInterval = 60
}
default:
print("Device is at ideal position or invalid speed found")
}
}
func setTimer(timeInterval: TimeInterval) {
isTimerSetForSpeed = true
timer = Timer.scheduledTimer(timeInterval: timeInterval, target: self, selector: #selector(captureLocation), userInfo: nil, repeats: true)
}
func stopTimer() {
timer.invalidate()
isTimerSetForSpeed = false
}
func captureLocation() {
saveUserLocationInFile()
// Save user location in DB
saveUserLocationInDB()
}
//MARK:- Save User Location In File
func saveUserLocationInFile() {
let fileManager = FileManager.default
let dir: URL = fileManager.urls(for: .documentDirectory, in: .userDomainMask).last!
let fileurl = dir.appendingPathComponent("locations.txt")
let headingText = "\t\t Time \t\t\t\t Latitude \t\t\t Longitude \t\t\t Current time interval \t\t Next time interval \n"
let separator = "--------------------------------------------------------------------------------------------------------------------------------"
let contentToWrite = " \(headingText) \(Date().addingTimeInterval(0)) \t \(latitude) \t\t\t \(longitude) \t\t\t\t\t \(currentTimeInterval) \t\t\t\t\t\t \(nextTimeInterval) \n \(separator) \n"
let data = contentToWrite.data(using: .utf8, allowLossyConversion: false)!
if fileManager.fileExists(atPath: fileurl.path) {
do {
let fileHandle = try FileHandle(forWritingTo: fileurl)
fileHandle.seekToEndOfFile()
fileHandle.write(data)
fileHandle.closeFile()
} catch let error {
print("file handle failed \(error.localizedDescription)")
}
} else {
do {
_ = try data.write(to: fileurl, options: .atomic)
} catch let error {
print("cant write \(error.localizedDescription)")
}
}
readFile()
}
func readFile() {
let path = NSSearchPathForDirectoriesInDomains(.documentDirectory,.userDomainMask , true)
let docDir = path[0]
let sampleFilePath = docDir.appendingFormat("/locations.txt")
do {
let contentOfFile = try String(contentsOfFile: sampleFilePath, encoding: .utf8)
print("file content is: \(contentOfFile)")
} catch {
print("Error while read file")
}
}
// MARK:- Save User Location In DB
func saveUserLocationInDB() {
print("saveUserLocationInDB")
let objDBHelper = DBHelper.instance
objDBHelper.saveLocationUpdatedDataInLocalDB(time: userLocation.timestamp, latitude: userLocation.coordinate.latitude, longitude: userLocation.coordinate.longitude, currentTimeInterval: currentTimeInterval, nextTimeInterval: nextTimeInterval, speed: speedInKmPerHour)
}
}
// MARK:- CLLocationManagerDelegate
extension LocationManagerHelper: CLLocationManagerDelegate {
public func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
if let currentLocation = manager.location {
latitude = (manager.location?.coordinate.latitude)!
longitude = (manager.location?.coordinate.longitude)!
print("latitude :\(latitude)")
print("longitude :\(longitude)")
print("time stamp: \(String(describing: currentLocation.timestamp))")
// location Manager return speed in mps(meter per second)
let speedInMeterPerSecond = currentLocation.speed
// formula for calculate meter per second to km/h.
// km/h = mps * 3.6
// 5m/sec = (5 * 3.6) = 18 km/h
speedInKmPerHour = (speedInMeterPerSecond * 3.6)
// print("speed \(speedInKmPerHour) Km/h")
if speedInKmPerHour != previousSpeedInKmPerHour && previousSpeedInKmPerHour > 0.0 {
isSpeedChanged = true
} else {
isSpeedChanged = false
}
locationUpdatesAsPerCalculatedSpeedOfVehicle()
}
// Create a location
userLocation = CLLocation(latitude: latitude, longitude: longitude)
// print("User location is \(userLocation)")
}
public func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
print("Failed to get the current location of user \(error.localizedDescription)")
}
}
| apache-2.0 | 0adf39e3e8d43a53264787256a81dc03 | 40.275229 | 275 | 0.577351 | 5.129989 | false | false | false | false |
BjornRuud/HTTPSession | Pods/Swifter/Sources/String+BASE64.swift | 4 | 1528 | //
// String+BASE64.swift
// Swifter
//
// Copyright © 2016 Damian Kołakowski. All rights reserved.
//
import Foundation
extension String {
private static let CODES = [UInt8]("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".utf8)
public static func toBase64(_ data: [UInt8]) -> String {
// Based on: https://en.wikipedia.org/wiki/Base64#Sample_Implementation_in_Java
var result = [UInt8]()
var tmp: UInt8
for index in stride(from: 0, to: data.count, by: 3) {
let byte = data[index]
tmp = (byte & 0xFC) >> 2;
result.append(CODES[Int(tmp)])
tmp = (byte & 0x03) << 4;
if index + 1 < data.count {
tmp |= (data[index + 1] & 0xF0) >> 4;
result.append(CODES[Int(tmp)]);
tmp = (data[index + 1] & 0x0F) << 2;
if (index + 2 < data.count) {
tmp |= (data[index + 2] & 0xC0) >> 6;
result.append(CODES[Int(tmp)]);
tmp = data[index + 2] & 0x3F;
result.append(CODES[Int(tmp)]);
} else {
result.append(CODES[Int(tmp)]);
result.append(contentsOf: [UInt8]("=".utf8));
}
} else {
result.append(CODES[Int(tmp)]);
result.append(contentsOf: [UInt8]("==".utf8));
}
}
return String.fromUInt8(result)
}
}
| mit | f16f74f5e874d19789aa1ef0648d0c7f | 32.173913 | 112 | 0.480996 | 3.815 | false | false | false | false |
WSDOT/wsdot-ios-app | wsdot/FavoritesSettingsViewController.swift | 2 | 7593 | //
// FavoritesSettingsViewController.swift
// WSDOT
//
// Copyright (c) 2017 Washington State Department of Transportation
//
// 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 FavoritesSettingsViewController: UIViewController {
let sectionCellIdentifier = "SectionCell"
let textCellIdentifier = "TextCell"
let numFavoriteSections = 8
var sectionTypesOrderRawArray = UserDefaults.standard.array(forKey: UserDefaultsKeys.favoritesOrder) as? [Int] ?? [Int]()
@IBOutlet weak var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
tableView.isEditing = true
tableView.allowsSelectionDuringEditing = true
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
MyAnalytics.screenView(screenName: "Settings")
}
func clearFavorites(){
MyAnalytics.event(category: "Favorites", action: "UIAction", label: "Cleared Favorites")
for camera in CamerasStore.getFavoriteCameras() {
CamerasStore.updateFavorite(camera, newValue: false)
}
for time in TravelTimesStore.findFavoriteTimes() {
TravelTimesStore.updateFavorite(time, newValue: false)
}
for schedule in FerryRealmStore.findFavoriteSchedules() {
FerryRealmStore.updateFavorite(schedule, newValue: false)
}
for pass in MountainPassStore.findFavoritePasses() {
MountainPassStore.updateFavorite(pass, newValue: false)
}
for location in FavoriteLocationStore.getFavorites() {
FavoriteLocationStore.deleteFavorite(location)
}
for route in MyRouteStore.getSelectedRoutes() {
_ = MyRouteStore.updateSelected(route, newValue: false)
}
for toll in TollRateSignsStore.findFavoriteTollSigns() {
TollRateSignsStore.updateFavorite(toll, newValue: false)
}
for wait in BorderWaitStore.getFavoriteWaits() {
BorderWaitStore.updateFavorite(wait, newValue: false)
}
}
}
// MARK: - TableView
extension FavoritesSettingsViewController: UITableViewDataSource, UITableViewDelegate {
func numberOfSections(in tableView: UITableView) -> Int {
return 2
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return UITableView.automaticDimension
}
func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
return UITableView.automaticDimension
}
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
switch section {
case 0:
return "Organize Favorites"
case 1:
return ""
default:
return ""
}
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
switch section {
case 0:
return numFavoriteSections
case 1:
return 1
default:
return 0
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
switch indexPath.section {
case 0:
let sectionCell = tableView.dequeueReusableCell(withIdentifier: sectionCellIdentifier, for: indexPath)
sectionCell.textLabel?.text = MyRouteStore.sectionTitles[sectionTypesOrderRawArray[indexPath.row]]
return sectionCell
case 1:
let deleteCell = tableView.dequeueReusableCell(withIdentifier: textCellIdentifier, for: indexPath)
deleteCell.textLabel?.text = "Clear Favorites"
deleteCell.textLabel?.textColor = UIColor(red: 1, green: 0, blue: 0, alpha: 1.0)
deleteCell.textLabel?.textAlignment = .center
return deleteCell
default:
return tableView.dequeueReusableCell(withIdentifier: "", for: indexPath)
}
}
// MARK: - Navigation
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
switch indexPath.section{
case 1: // Delete
let alertController = UIAlertController(title: "Clear Favorites?", message:"This cannot be undone. Any saved map locations will be deleted. Recorded routes will be kept.", preferredStyle: .alert)
// Setting tintColor on iOS < 9 leades to strange display behavior.
if #available(iOS 9.0, *) {
alertController.view.tintColor = Colors.tintColor
}
let confirmDeleteAction = UIAlertAction(title: "Clear", style: .destructive) { (_) -> Void in
self.clearFavorites()
}
let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)
alertController.addAction(cancelAction)
alertController.addAction(confirmDeleteAction)
present(alertController, animated: false, completion: nil)
tableView.deselectRow(at: indexPath, animated: true)
break
default:
break
}
}
// MARK: - Edit
// Keep movable cells in their section
func tableView(_ tableView: UITableView, targetIndexPathForMoveFromRowAt sourceIndexPath: IndexPath, toProposedIndexPath proposedDestinationIndexPath: IndexPath) -> IndexPath {
if sourceIndexPath.section != proposedDestinationIndexPath.section {
var row = 0
if sourceIndexPath.section < proposedDestinationIndexPath.section {
row = self.tableView(tableView, numberOfRowsInSection: sourceIndexPath.section) - 1
}
return IndexPath(row: row, section: sourceIndexPath.section)
}
return proposedDestinationIndexPath
}
func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
return indexPath.section == 0
}
func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
return indexPath.section == 0
}
func tableView(_ tableView: UITableView, shouldIndentWhileEditingRowAt indexPath: IndexPath) -> Bool {
return false
}
func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCell.EditingStyle {
return UITableViewCell.EditingStyle.none
}
func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to toIndexPath: IndexPath) {
// Update title array
let sectionMoved = sectionTypesOrderRawArray.remove(at: fromIndexPath.row)
sectionTypesOrderRawArray.insert(sectionMoved, at: toIndexPath.row)
UserDefaults.standard.set(sectionTypesOrderRawArray, forKey: UserDefaultsKeys.favoritesOrder)
}
}
| gpl-3.0 | 4c4402fd47354d87c322c2432112e2be | 37.348485 | 207 | 0.660608 | 5.388928 | false | false | false | false |
wei18810109052/CWWeChat | CWWeChat/MainClass/MomentModule/Layout/CWMomentDataService.swift | 2 | 3164 | //
// CWMomentDataService.swift
// CWWeChat
//
// Created by chenwei on 2017/4/11.
// Copyright © 2017年 cwcoder. All rights reserved.
//
import UIKit
import SwiftyJSON
class CWMomentDataService: NSObject {
func parseCommentData(_ dict: [String: Any]) {
let json = JSON(dict)
guard json["result"].string == "success",
let resultArray = json["text"].arrayObject,
let _ = resultArray as? [[String: String]] else {
return
}
}
func parseMomentData() -> [CWMomentLayout] {
var momentLayouts = [CWMomentLayout]()
guard let path = Bundle.main.path(forResource: "moments", ofType: "json"),
let momentData = try? Data(contentsOf: URL(fileURLWithPath: path)) else {
return momentLayouts
}
guard let momentList = JSON(data: momentData).dictionary?["data"]?.array else {
return momentLayouts
}
for moment in momentList {
let momentId = moment["momentId"].stringValue
let username = moment["username"].stringValue
let userId = moment["userId"].stringValue
let date = moment["date"].doubleValue
let type = CWMomentType(rawValue: moment["type"].intValue) ?? .normal
let content = moment["content"].string
let share_Date = Date(timeIntervalSince1970: date/1000)
let momentModel = CWMoment(momentId: momentId,
username: username,
userId: userId,
date: share_Date)
momentModel.content = content
momentModel.type = type
let items = moment["images"].arrayValue
for item in items {
let url1 = URL(string: item["largetURL"].stringValue)!
let url2 = URL(string: item["thumbnailURL"].stringValue)!
let size = CGSize(width: item["width"].intValue, height: item["height"].intValue)
let imageModel = CWMomentPhoto(thumbnailURL: url2, largetURL: url1, size: size)
momentModel.imageArray.append(imageModel)
}
if let news = moment["news"].dictionary {
let url = news["url"]?.stringValue
let imageUrl = news["imageurl"]?.stringValue
let title = news["title"]?.stringValue
let source = news["source"]?.stringValue
let newsurl = URL(string: url!)!
let newsImageUrl = URL(string: imageUrl!)!
let urlModel = CWMultimedia(url: newsurl,
imageURL: newsImageUrl,
title: title!, source: source)
momentModel.multimedia = urlModel
}
let layout = CWMomentLayout(moment: momentModel)
momentLayouts.append(layout)
}
return momentLayouts
}
}
| mit | 64e555d81e61b0554eebe20e3438750c | 34.516854 | 97 | 0.520405 | 5.330523 | false | false | false | false |
noppefoxwolf/ZappingKit | ZappingKit/Classes/Extensions.swift | 1 | 1166 | //
// Extensions.swift
// Pods
//
// Created by Tomoya Hirano on 2016/10/11.
//
//
import UIKit
internal struct FillConstraintsPair {
fileprivate var v: [NSLayoutConstraint]
fileprivate var h: [NSLayoutConstraint]
internal init(of view: UIView, name: String? = nil) {
let viewName = name ?? view.className
let views = [viewName: view]
let vConstraints = NSLayoutConstraint.constraints(withVisualFormat: "V:|[\(viewName)]|",
options: .alignAllLeft,
metrics: nil,
views: views)
let hConstraints = NSLayoutConstraint.constraints(withVisualFormat: "H:|[\(viewName)]|",
options: .alignAllLeft,
metrics: nil,
views: views)
v = vConstraints
h = hConstraints
}
}
fileprivate extension NSObject {
fileprivate static var className: String {
return NSStringFromClass(self).components(separatedBy: ".").last!
}
fileprivate var className: String {
return type(of: self).className
}
}
internal extension UIView {
internal func addConstraints(_ fillConstraintsPair: FillConstraintsPair) {
addConstraints(fillConstraintsPair.v)
addConstraints(fillConstraintsPair.h)
}
}
| mit | 65a1abeccdee0c71f23f2061239568b8 | 24.347826 | 92 | 0.69554 | 4.350746 | false | false | false | false |
rhysd/mal | swift/readline.swift | 24 | 1132 | //******************************************************************************
// MAL - readline
//******************************************************************************
import Foundation
private let HISTORY_FILE = "~/.mal-history"
func with_history_file(do_to_history_file:(UnsafePointer<Int8>) -> ()) {
HISTORY_FILE.withCString {
(c_str) -> () in
let abs_path = tilde_expand(UnsafeMutablePointer<Int8>(c_str))
if abs_path != nil {
do_to_history_file(abs_path)
free(abs_path)
}
}
}
func load_history_file() {
using_history()
with_history_file {
let _ = read_history($0)
}
}
func save_history_file() {
// Do this? stifle_history(1000)
with_history_file {
let _ = write_history($0)
}
}
func _readline(prompt: String) -> String? {
let line = prompt.withCString {
(c_str) -> UnsafeMutablePointer<Int8> in
return readline(c_str)
}
if line != nil {
if let result = String(UTF8String: line) {
add_history(line)
return result
}
}
return nil
}
| mpl-2.0 | 175d863d88d49bdc4e5a425a78e1cae4 | 23.608696 | 80 | 0.478799 | 3.863481 | false | false | false | false |
andrewBatutin/SwiftYamp | SwiftYampTests/Models/UserMessageBodyFrameTest.swift | 1 | 1378 | //
// UserMessageBodyFrameTest.swift
// SwiftYamp
//
// Created by Andrey Batutin on 6/13/17.
// Copyright © 2017 Andrey Batutin. All rights reserved.
//
import XCTest
@testable import SwiftYamp
class UserMessageBodyFrameTest: XCTestCase {
func testUserMessageBodySerializationSuccsefull(){
let expectedData = Data(bytes: [0x00, 0x00, 0x00, 0x04, 0x01, 0x02, 0x03, 0x04])
let subject = UserMessageBodyFrame(size: 4, body: [0x01, 0x02, 0x03, 0x04])
let realData = try! subject.toData()
XCTAssertEqual(realData, expectedData)
}
func testUserMessageBodyDeSerializationThrowsWithShortData(){
let inputData = Data(bytes: [0x00, 0x00, 0x00, 0x04, 0x01, 0x02, 0x03])
XCTAssertThrowsError(try UserMessageBodyFrame(data: inputData))
}
func testUserMessageBodyDeSerializationThrowsWithSizeOverflow(){
let inputData = Data(bytes: [0x04, 0x00, 0x00, 0x00, 0x01, 0x02, 0x03])
XCTAssertThrowsError(try UserMessageBodyFrame(data: inputData))
}
func testUserMessageBodyDeSerializationSuccsefull(){
let inputData = Data(bytes: [0x00, 0x00, 0x00, 0x04, 0x01, 0x02, 0x03, 0x04])
let subject = try! UserMessageBodyFrame(data: inputData)
XCTAssertEqual(subject.size, 0x04)
XCTAssertEqual(subject.body!, [0x01, 0x02, 0x03, 0x04])
}
}
| mit | 0422d26c2e7abcaad042d52f4594db30 | 33.425 | 88 | 0.687001 | 3.468514 | false | true | false | false |
inamiy/SwiftElm | SwiftElmPlayground.playground/Pages/Simple Counter.xcplaygroundpage/Contents.swift | 1 | 2565 | import UIKit
import PlaygroundSupport
import VTree
import SwiftElm
struct Model
{
let rootSize = CGSize(width: 320, height: 480)
let count: Int
}
func update(_ model: Model, _ msg: Msg) -> Model?
{
switch msg {
case .increment:
return Model(count: model.count + 1)
case .decrement:
return Model(count: model.count - 1)
}
}
func view(model: Model) -> VView<Msg>
{
let rootWidth = model.rootSize.width
let rootHeight = model.rootSize.height
let space: CGFloat = 20
let buttonWidth = (rootWidth - space*3)/2
func rootView(_ children: [AnyVTree<Msg>] = []) -> VView<Msg>
{
return VView(
styles: .init {
$0.frame = CGRect(x: 0, y: 0, width: rootWidth, height: rootHeight)
$0.backgroundColor = .white
},
children: children
)
}
func label(_ count: Int) -> VLabel<Msg>
{
return VLabel(
text: .text("\(count)"),
styles: .init {
$0.frame = CGRect(x: 0, y: 40, width: rootWidth, height: 80)
$0.backgroundColor = .clear
$0.textAlignment = .center
$0.font = .systemFont(ofSize: 48)
}
)
}
func incrementButton() -> VButton<Msg>
{
return VButton(
title: "+",
styles: .init {
$0.frame = CGRect(x: rootWidth/2 + space/2, y: 150, width: buttonWidth, height: 50)
$0.backgroundColor = #colorLiteral(red: 0.4666666687, green: 0.7647058964, blue: 0.2666666806, alpha: 1)
$0.font = .systemFont(ofSize: 24)
},
handlers: [.touchUpInside: .increment]
)
}
func decrementButton() -> VButton<Msg>
{
return VButton(
title: "-",
styles: .init {
$0.frame = CGRect(x: space, y: 150, width: buttonWidth, height: 50)
$0.backgroundColor = #colorLiteral(red: 0.9372549057, green: 0.3490196168, blue: 0.1921568662, alpha: 1)
$0.font = .systemFont(ofSize: 24)
},
handlers: [.touchUpInside: .decrement]
)
}
let count = model.count
return rootView([
*label(count),
*incrementButton(),
*decrementButton()
])
}
// MARK: Main
let initial = Model(count: 0)
let program = Program(model: initial, update: update, view: view)
program.window.bounds.size = initial.rootSize
PlaygroundPage.current.liveView = program.window
| mit | ee7be9caddb9be09d7f7fd31ebbab879 | 26.287234 | 120 | 0.541131 | 3.862952 | false | false | false | false |
yonadev/yona-app-ios | Yona/Yona/CustomCells/PKSwipeTableViewCell.swift | 1 | 10651 | //
// PKSwipeTableViewCell.swift
// PKSwipeTableViewCell
//
// Created by Pradeep Kumar Yadav on 16/04/16.
// Copyright © 2016 iosbucket. All rights reserved.
//
protocol PKSwipeCellDelegateProtocol {
func swipeBeginInCell(_ cell:PKSwipeTableViewCell)
func swipeDoneOnPreviousCell()->PKSwipeTableViewCell?
}
protocol YonaUserCellDelegate {
func messageNeedToBeDeleted(_ cell: YonaUserTableViewCell, message: Message);
}
protocol CommentCellDelegate {
func deleteComment(_ cell: CommentControlCell, comment: Comment);
func showSendComment(_ comment: Comment?);
}
protocol DeleteTimezoneCellDelegateProtocol {
func deleteTimezone(_ cell: TimeZoneTableViewCell);
}
import UIKit
class PKSwipeTableViewCell: UITableViewCell , PKSwipeCellDelegateProtocol {
//MARK: Variables
//Set the delegate object
internal var commentDelegate:CommentCellDelegate?
internal var yonaUserDelegate:YonaUserCellDelegate?
internal var pkdelegate:PKSwipeTableViewCell?
internal var timezoneCellDelegate:DeleteTimezoneCellDelegateProtocol?
//set the view of right Side
internal var isPanEnabled = true
fileprivate var viewRightAccessory = UIView()
fileprivate var backview:UIView = UIView()
//MARK: Cell Methods
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
resetCellState()
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
if #available(iOS 8.0, *) {
initializeCell()
} else {
// Fallback on earlier versions
}
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
if #available(iOS 8.0, *) {
initializeCell()
} else {
// Fallback on earlier versions
}
}
override func prepareForReuse() {
super.prepareForReuse()
}
//MARK: Gesture Method
override func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
if gestureRecognizer.isKind(of: UIPanGestureRecognizer.classForCoder()) {
let point = (gestureRecognizer as! UIPanGestureRecognizer).translation(in: self.superview)
return ((abs(point.x) / abs(point.y))) > 1 ? true : false
}
return false
}
//MARK: Private Functions
/**
This Method is used to initialize the cell with pan gesture and back views.
*/
@available(iOS 8.0, *)
fileprivate func initializeCell() {
let panGesture = UIPanGestureRecognizer(target: self, action: #selector(PKSwipeTableViewCell.handlePanGesture(_:)))
self.addGestureRecognizer(panGesture)
panGesture.delegate = self
let cellFrame = CGRect(x: 0, y: 0,width: self.screenBoundsFixedToPortraitOrientation().height, height: self.frame.size.height)
let viewBackground = UIView(frame: cellFrame)
self.backgroundView = viewBackground
self.backview = UIView(frame:cellFrame)
self.backview.autoresizingMask = UIView.AutoresizingMask.flexibleHeight
self.isExclusiveTouch = true
self.contentView.isExclusiveTouch = true
self.backview.isExclusiveTouch = true
}
/**
This function is used to get the screen frame independent of orientation
- returns: frame of screen
*/
@available(iOS 8.0, *)
func screenBoundsFixedToPortraitOrientation()->CGRect {
let screen = UIScreen.main
if screen.responds(to: #selector(getter: UIScreen.fixedCoordinateSpace)) {
return screen.coordinateSpace.convert(screen.bounds, to: screen.fixedCoordinateSpace)
}
return screen.bounds
}
/**
This Method will be called when user will start the panning
- parameter panGestureRecognizer: panGesture Object
*/
@objc func handlePanGesture(_ panGestureRecognizer : UIPanGestureRecognizer) {
if isPanEnabled == false{
return
}
if ((self.pkdelegate?.responds(to: #selector(PKSwipeTableViewCell.swipeDoneOnPreviousCell))) != nil) {
let cell = self.pkdelegate?.swipeDoneOnPreviousCell()
if cell != self && cell != nil {
cell?.resetCellState()
}
}
if ((self.pkdelegate?.responds(to: #selector(PKSwipeTableViewCell.swipeBeginInCell(_:)))) != nil) {
self.pkdelegate?.swipeBeginInCell(self)
}
let translation = panGestureRecognizer.translation(in: panGestureRecognizer.view)
let velocity = panGestureRecognizer .velocity(in: panGestureRecognizer.view)
let panOffset = translation.x
let actualTranslation = CGPoint(x: panOffset, y: translation.y)
if panGestureRecognizer.state == UIGestureRecognizer.State.began && panGestureRecognizer.numberOfTouches > 0 {
//start swipe
self.backgroundView!.addSubview(backview)
self.backgroundView?.bringSubviewToFront(self.backview)
self.backview.autoresizingMask = [UIView.AutoresizingMask.flexibleHeight ,UIView.AutoresizingMask.flexibleWidth]
animateContentViewForPoint(actualTranslation, velocity: velocity)
} else if(panGestureRecognizer.state == UIGestureRecognizer.State.changed && panGestureRecognizer.numberOfTouches > 0) {
//animate
animateContentViewForPoint(actualTranslation, velocity: velocity)
} else {
//reset the state
self.resetCellFromPoint(actualTranslation, withVelocity: velocity)
}
}
/**
This function is called when panning will start to update the frames to show the panning
- parameter point: point of panning
- parameter velocity: velocity of panning
*/
fileprivate func animateContentViewForPoint(_ point:CGPoint, velocity:CGPoint) {
if (point.x < 0) {
self.contentView.frame = self.contentView.bounds.offsetBy(dx: point.x, dy: 0)
self.viewRightAccessory.frame = CGRect(x: max(self.frame.maxX-self.viewRightAccessory.frame.width,self.contentView.frame.maxX), y: self.viewRightAccessory.frame.minY, width: self.viewRightAccessory.frame.width, height: self.viewRightAccessory.frame.height)
} else {
UIView.animate(withDuration: 0.5, animations: { () -> Void in
self.contentView.frame = self.contentView.bounds.offsetBy(dx: 0, dy: 0);
self.resetCellState()
}, completion: { (Bool) -> Void in
})
}
}
/**
This function is called to reset the panning state. If panning is less then it will reset to the original position depending on panning direction.
- parameter point: point of panning
- parameter velocity: velocity of panning
*/
fileprivate func resetCellFromPoint(_ point:CGPoint, withVelocity velocity:CGPoint) {
if (point.x > 0 && point.x <= self.frame.height) {
UIView.animate(withDuration: 0.5, animations: { () -> Void in
self.contentView.frame = self.contentView.bounds.offsetBy(dx: 0, dy: 0);
self.viewRightAccessory.frame = CGRect(x: self.contentView.frame.maxX, y: 0, width: self.viewRightAccessory.frame.width, height: self.frame.height)
}, completion: { (Bool) -> Void in
})
} else if point.x < 0 {
if (point.x < -self.viewRightAccessory.frame.width) {
// SCROLL MORE THAN VIEW ACCESSORY
UIView.animate(withDuration: 0.5, animations: { () -> Void in
self.contentView.frame = self.contentView.bounds.offsetBy(dx: -self.viewRightAccessory.frame.width, dy: 0);
}, completion: { (Bool) -> Void in
})
} else if -point.x < self.viewRightAccessory.frame.width {
// IF SCROLL MORE THAN 50% THEN MAKE THE OPTIONS VISIBLE
if -point.x > self.viewRightAccessory.frame.size.width / 2.0 {
UIView.animate(withDuration: 0.5, animations: { () -> Void in
self.contentView.frame = self.contentView.bounds.offsetBy(dx: -self.viewRightAccessory.frame.width, dy: 0)
self.viewRightAccessory.frame = CGRect(x: UIScreen.main.bounds.size.width - self.viewRightAccessory.frame.width, y: 0, width: self.viewRightAccessory.frame.width, height: self.frame.height)
}, completion: { (Bool) -> Void in
})
}else { // IF SCROLL LESS THEN MOVE TO ORIGINAL STATE
UIView.animate(withDuration: 0.5, animations: { () -> Void in
self.contentView.frame = self.contentView.bounds.offsetBy(dx: 0, dy: 0);
self.viewRightAccessory.frame = CGRect(x: self.contentView.frame.maxX, y: 0, width: self.viewRightAccessory.frame.width, height: self.frame.height)
}, completion: { (Bool) -> Void in
})
}
}
}
}
//MARK: public Methods
/**
This function is used to add the view in right side
- parameter view: view to be displayed on the right hsnd side of the cell
*/
internal func addRightOptionsView(_ view:UIView) {
viewRightAccessory.removeFromSuperview()
viewRightAccessory = view
viewRightAccessory.autoresizingMask = UIView.AutoresizingMask.flexibleLeftMargin
self.backview.addSubview(viewRightAccessory)
}
/**
This function is used to reset the cell state back to original position to hide the right view options.
*/
func resetCellState() {
UIView.animate(withDuration: 0.5, animations: { () -> Void in
self.contentView.frame = self.contentView.bounds.offsetBy(dx: 0, dy: 0);
self.viewRightAccessory.frame = CGRect(x: self.contentView.frame.maxX, y: 0, width: self.viewRightAccessory.frame.width, height: self.frame.height)
}, completion: { (Bool) -> Void in
})
}
@objc func swipeBeginInCell(_ cell: PKSwipeTableViewCell) {
}
@objc func swipeDoneOnPreviousCell() -> PKSwipeTableViewCell? {
return self
}
}
| mpl-2.0 | e81cf55132942a1432dfbb77674db007 | 41.6 | 268 | 0.641972 | 4.727031 | false | false | false | false |
steelwheels/KiwiGraphics | Source/Graphics/KGVelocity.swift | 1 | 3128 | /**
* @file KGVelocity.swift
* @brief Define KGVelocity data structure
* @par Copyright
* Copyright (C) 2016 Steel Wheels Project
*/
import CoreGraphics
public struct KGVelocity
{
private var mX: CGFloat = 0.0
private var mY: CGFloat = 0.0
private var mV: CGFloat = 0.0
private var mAngle: CGFloat = 0.0
private static func angle2point(v vval:CGFloat, angle aval:CGFloat) -> (CGFloat, CGFloat) {
let x = vval * sin(aval)
let y = vval * cos(aval)
return (x, y)
}
private static func point2angle(x xval:CGFloat, y yval:CGFloat) -> (CGFloat, CGFloat) {
let angle = atan2(xval, yval)
let speed = sqrt(xval*xval + yval*yval)
return (speed, angle)
}
public init(x xval:CGFloat, y yval:CGFloat){
mX = xval
mY = yval
(mV, mAngle) = KGVelocity.point2angle(x: xval, y: yval)
}
public init(v vval:CGFloat, angle aval:CGFloat){
mV = vval
mAngle = aval
(mX, mY) = KGVelocity.angle2point(v: vval, angle: aval)
}
public var x:CGFloat {
get{ return mX }
set(newx) {
mX = newx
(mV, mAngle) = KGVelocity.point2angle(x: newx, y: mY)
}
}
public var y:CGFloat {
get{ return mY }
set(newy) {
mY = newy
(mV, mAngle) = KGVelocity.point2angle(x: mX, y: newy)
}
}
public var v:CGFloat {
get{ return mV }
set(newv){
mV = newv
(mX, mY) = KGVelocity.angle2point(v: newv, angle: mAngle)
}
}
public var angle:CGFloat {
get{ return mAngle }
set(newangle){
mAngle = newangle
(mX, mY) = KGVelocity.angle2point(v: mV, angle: newangle)
}
}
public mutating func set(x xval:CGFloat, y yval:CGFloat){
mX = xval
mY = yval
(mV, mAngle) = KGVelocity.point2angle(x: x, y: yval)
}
public mutating func set(v vval:CGFloat, angle aval:CGFloat){
mV = vval
mAngle = aval
(mX, mY) = KGVelocity.angle2point(v: vval, angle: aval)
}
public var xAndY:CGPoint {
get { return CGPoint(x: mX, y: mY) }
}
public var longDescription: String {
let xstr = NSString(format: "%.2lf", Double(mX))
let ystr = NSString(format: "%.2lf", Double(mY))
let vstr = NSString(format: "%.2lf", Double(mV))
let astr = NSString(format: "%.2lf", Double(Double(mAngle) / Double.pi))
return "((x:\(xstr), y:\(ystr))=(v:\(vstr), angle:\(astr)PI))"
}
public var shortDescription: String {
let vstr = NSString(format: "%.2lf", Double(mV))
let astr = NSString(format: "%.2lf", Double(Double(mAngle) / Double.pi))
return "(v:\(vstr), angle:\(astr)PI)"
}
public static func serialize(velocity: KGVelocity) -> Dictionary<String, AnyObject> {
var dict: Dictionary<String, AnyObject> = [:]
dict["x"] = NSNumber(value: Double(velocity.x))
dict["y"] = NSNumber(value: Double(velocity.y))
return dict
}
public static func unserialize(dictionary dict : Dictionary<String, AnyObject>) -> KGVelocity? {
var x,y: Double
if let xval = dict["x"] as? NSNumber {
x = xval.doubleValue
} else {
return nil
}
if let yval = dict["y"] as? NSNumber {
y = yval.doubleValue
} else {
return nil
}
return KGVelocity(x: CGFloat(x), y: CGFloat(y))
}
}
| gpl-2.0 | 3ebad24bbc9913564552af4225260edb | 23.825397 | 97 | 0.629156 | 2.727114 | false | false | false | false |
mownier/photostream | Photostream/Module Extensions/PostUploadModuleExtension.swift | 1 | 741 | //
// PostUploadModuleExtension.swift
// Photostream
//
// Created by Mounir Ybanez on 19/12/2016.
// Copyright © 2016 Mounir Ybanez. All rights reserved.
//
extension UploadedPost {
func covertToNewsFeedPost() -> NewsFeedPost {
var post = NewsFeedPost()
post.id = id
post.message = message
post.timestamp = timestamp
post.photoUrl = photoUrl
post.photoWidth = photoWidth
post.photoHeight = photoHeight
post.likes = likes
post.comments = comments
post.isLiked = isLiked
post.userId = userId
post.avatarUrl = avatarUrl
post.displayName = displayName
return post
}
}
| mit | 786b4a134bcdddb7ab0642aa4d7ac428 | 22.125 | 56 | 0.586486 | 4.805195 | false | false | false | false |
Kila2/Tetris | Tetris/GameOverViewController.swift | 1 | 1630 | //
// GameOverViewController.swift
// Tetris
//
// Created by junlianglee on 2017/5/18.
// Copyright © 2017年 kila. All rights reserved.
//
import UIKit
class GameOverViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func dismiss(_ sender: UIButton) {
UIView.animate(withDuration: 0.5) {
self.view.alpha = 0
}
}
@IBAction func show(_ sender: UIButton) {
UIView.animate(withDuration: 0.5) {
self.view.alpha = 0.8
}
}
@IBAction func goToAppleStore(_ sender: UIButton) {
let appid = 12345
let url = URL(string:"itms-apps://itunes.apple.com/WebObjects/MZStore.woa/wa/viewContentsUserReviews?type=Purple+Software&id=\(appid)")!
UIApplication.shared.open(url, options: [:], completionHandler: nil)
}
@IBAction func restart(_ sender: UIButton) {
self.dismiss(animated: true) {
GameViewController.restart()
}
}
/*
// 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.
}
*/
}
| gpl-3.0 | eb9030ad139fdcb741bcba81ec23de7a | 26.576271 | 144 | 0.62815 | 4.519444 | false | false | false | false |
xqz001/WWDC | WWDC/ActionButtonsViewController.swift | 1 | 3425 | //
// ActionButtonsController.swift
// WWDC
//
// Created by Guilherme Rambo on 26/04/15.
// Copyright (c) 2015 Guilherme Rambo. All rights reserved.
//
import Cocoa
class ActionButtonsViewController: NSViewController {
var session: Session! {
didSet {
updateUI()
}
}
var stackView: NSStackView {
return view as! NSStackView
}
var watchHDVideoCallback: () -> () = {}
var watchVideoCallback: () -> () = {}
var showSlidesCallback: () -> () = {}
var toggleWatchedCallback: () -> () = {}
var afterCallback: () -> () = {}
/* these outlets are not weak because we will be removing the buttons from the view
but we have to keep our reference to put them back later */
@IBOutlet var watchHDButton: NSButton!
@IBOutlet var watchButton: NSButton!
@IBOutlet var slidesButton: NSButton!
@IBOutlet var progressButton: NSButton!
override func viewDidLoad() {
super.viewDidLoad()
updateUI()
}
private func updateUI() {
if !self.viewLoaded {
return
}
noSession()
if let session = session {
setSessionCanBeWatched(true)
setSessionCanBeWatchedInHD((session.hd_url != nil))
setSessionHasSlides((session.slides != nil))
reflectSessionProgress()
} else {
noSession()
}
}
private func noSession() {
setSessionCanBeWatched(false)
setSessionCanBeWatchedInHD(false)
setSessionHasSlides(false)
hideProgressButton()
}
private func setSessionCanBeWatched(can: Bool) {
if can {
stackView.addView(watchButton, inGravity: .Top)
} else {
if watchButton.superview != nil {
watchButton.removeFromSuperviewWithoutNeedingDisplay()
}
}
}
private func setSessionCanBeWatchedInHD(can: Bool) {
if can {
stackView.addView(watchHDButton, inGravity: .Top)
} else {
if watchHDButton.superview != nil {
watchHDButton.removeFromSuperviewWithoutNeedingDisplay()
}
}
}
private func setSessionHasSlides(has: Bool) {
if has {
stackView.addView(slidesButton, inGravity: .Top)
} else {
if slidesButton.superview != nil {
slidesButton.removeFromSuperviewWithoutNeedingDisplay()
}
}
}
private func hideProgressButton() {
if progressButton.superview != nil {
progressButton.removeFromSuperviewWithoutNeedingDisplay()
}
}
private func reflectSessionProgress() {
if session.progress < 100 {
if progressButton.superview == nil {
stackView.addView(progressButton, inGravity: .Top)
}
} else {
hideProgressButton()
}
}
@IBAction func watchHD(sender: NSButton) {
watchHDVideoCallback()
afterCallback()
}
@IBAction func watch(sender: NSButton) {
watchVideoCallback()
afterCallback()
}
@IBAction func watchSlides(sender: NSButton) {
showSlidesCallback()
afterCallback()
}
@IBAction func toggleWatched(sender: NSButton) {
toggleWatchedCallback()
afterCallback()
}
}
| bsd-2-clause | 0fd595fbe01c2cac1ab28d3e86469e18 | 26.845528 | 87 | 0.579854 | 4.823944 | false | false | false | false |
valitovaza/NewsAP | NewsAP/NewsFeed/NewsVController.swift | 1 | 8343 | import UIKit
protocol PresenterView: class, CellsOpenActionProtocol {
var tableView: Reloadable {get set}
var errorView: HidableView {get set}
func resetTableContentOffset()
func insertSection(with rows: Int, at index: Int)
func addRows(_ rows: Int, to section: Int)
func setTopTitleHidden(_ isHidden: Bool)
func setTopSegmentHidden(_ isHidden: Bool)
func setFaveViewHidded(_ isHidden: Bool)
func reloadFavorite()
}
class NewsVController: UIViewController, ViewPresentable {
static let newsCellIdentifier = "NewsCell"
static let sectionCellIdentifier = "NewsHeaderCell"
static let sctimatedRowHeight: CGFloat = 400
static let sectionHeight: CGFloat = 44.0
enum AccessibilityStrings: String {
case SelectSource = "Select source for news"
case Refresh = "Refresh news"
}
enum SegueIdentifier: String {
case SelectSource = "SelectSource"
}
var configurator: NewsConfiguratorProtocol = NewsConfigurator()
var eventHandler: NewsEventHandlerProtocol?
var cellPresenter: TableViewPresenter?
var refreshBarButtonItem: UIBarButtonItem?
@IBOutlet weak var topTitle: UILabel!
@IBOutlet weak var topSegment: UISegmentedControl!
@IBOutlet weak var faveView: UIView!
@IBOutlet weak var loadAnimationView: UIView!
@IBOutlet weak var tbl: UITableView!
@IBOutlet weak var faveTbl: UITableView!
@IBOutlet weak var errView: UIView!
@IBAction func refresh(_ sender: Any) {
eventHandler?.refresh()
}
@IBAction func segmentAction(_ sender: Any) {
eventHandler?.segmentSelected(topSegment.selectedSegmentIndex)
}
}
extension NewsVController: PresenterView {
var tableView: Reloadable {
get {
return tbl
}
set {
tbl = newValue as! UITableView
}
}
var errorView: HidableView {
get {
return errView
}
set {
errView = newValue as! UIView
}
}
func resetTableContentOffset() {
tbl.setContentOffset(CGPoint.zero, animated: false)
}
func insertSection(with rows: Int, at index: Int) {
tbl.beginUpdates()
tbl.insertSections(IndexSet(integer: index), with: .none)
tbl.insertRows(at: indexPaths(for: rows, at: index), with: .none)
tbl.endUpdates()
}
private func indexPaths(for rows: Int, at index: Int) -> [IndexPath] {
return (0..<rows).map{IndexPath(row: $0, section: index)}
}
func addRows(_ rows: Int, to section: Int) {
tbl.insertRows(at: indexPaths(for: rows, at: section),
with: .automatic)
}
func setTopTitleHidden(_ isHidden: Bool) {
topTitle.isHidden = isHidden
}
func setTopSegmentHidden(_ isHidden: Bool) {
topSegment.isHidden = isHidden
if isHidden {
topSegment.selectedSegmentIndex = 0
}
}
func setFaveViewHidded(_ isHidden: Bool) {
faveView.isHidden = isHidden
navigationItem.rightBarButtonItem?.tintColor = isHidden ? view.tintColor : .clear
navigationItem.rightBarButtonItem?.isEnabled = isHidden
navigationItem.leftBarButtonItem = isHidden ? refreshBarButtonItem : settingsNavigationItem()
}
private func settingsNavigationItem() -> UIBarButtonItem {
let button = UIButton(type: .custom)
button.addTarget(self, action: #selector(openNotificationSettings),
for: .touchUpInside)
let image = UIImage(asset: .Settings)
button.setImage(image, for: .normal)
button.setImage(UIImage(asset: .SettingsHightlighted), for: .highlighted)
button.frame = CGRect(x: 0, y: 0,
width: image.size.width,
height: image.size.height)
return UIBarButtonItem(customView: button)
}
func openNotificationSettings() {
eventHandler?.openSettings()
}
func reloadFavorite() {
faveTbl.reloadData()
}
}
extension NewsVController {
override func viewDidLoad() {
super.viewDidLoad()
configureViews()
applyAccessibility()
configurator.configure(self)
eventHandler?.viewDidLoad()
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
let navigationController = segue.destination as! UINavigationController
let receiver = navigationController.viewControllers.first as! NewsRefresherReceivable
receiver.setRefresher(eventHandler!)
}
private func applyAccessibility() {
navigationItem.leftBarButtonItem?.accessibilityLabel = AccessibilityStrings.Refresh.rawValue
navigationItem.rightBarButtonItem?.accessibilityLabel = AccessibilityStrings.SelectSource.rawValue
}
private func configureViews() {
refreshBarButtonItem = navigationItem.leftBarButtonItem
let nib = UINib(nibName: NewsVController.newsCellIdentifier, bundle: nil)
tbl.register(nib, forCellReuseIdentifier: NewsVController.newsCellIdentifier)
tbl.isHidden = true
tbl.estimatedRowHeight = NewsVController.sctimatedRowHeight
tbl.rowHeight = UITableViewAutomaticDimension
faveTbl.register(nib, forCellReuseIdentifier: NewsVController.newsCellIdentifier)
faveTbl.estimatedRowHeight = NewsVController.sctimatedRowHeight
faveTbl.rowHeight = UITableViewAutomaticDimension
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
eventHandler?.viewDidAppear()
}
fileprivate func isFave(_ tableView: UITableView) -> Bool {
return tableView == faveTbl
}
}
extension NewsVController: UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int {
return isFave(tableView) ? cellPresenter?.faveSectionCount() ?? 0 : cellPresenter?.sectionCount() ?? 0
}
func tableView(_ tableView: UITableView,
numberOfRowsInSection section: Int) -> Int {
return isFave(tableView) ? cellPresenter?.faveCount() ?? 0 : cellPresenter?.count(in: section) ?? 0
}
func tableView(_ tableView: UITableView,
cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: NewsVController.newsCellIdentifier,
for: indexPath) as! NewsCell
if isFave(tableView) {
cellPresenter?.presentFave(cell: cell, at: indexPath.row)
}else{
cellPresenter?.present(cell: cell, at: indexPath.row, section: indexPath.section)
}
return cell
}
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
if isFave(tableView) {return nil}
let header = NewsHeader(CGRect(x: 0, y: 0,
width: view.frame.width,
height: NewsVController.sectionHeight))
cellPresenter?.present(header: header, at: section)
return header
}
}
extension NewsVController: UITableViewDelegate {
func tableView(_ tableView: UITableView,
heightForHeaderInSection section: Int) -> CGFloat {
return isFave(tableView) ? 0.0 : NewsVController.sectionHeight
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
eventHandler?.select(at: indexPath.row, section: indexPath.section)
}
}
extension NewsVController: CellsOpenActionProtocol {
func openActions(for cell: UITableViewCell) {
if topSegment.selectedSegmentIndex == 0 {
openActionsForAll(cell)
}else{
openActionsForFave(cell)
}
}
private func openActionsForAll(_ cell: UITableViewCell) {
if let indexPath = tbl.indexPath(for: cell) {
eventHandler?.openActions(for: indexPath.row,
section: indexPath.section)
}
}
private func openActionsForFave(_ cell: UITableViewCell) {
if let indexPath = faveTbl.indexPath(for: cell) {
eventHandler?.openActions(forFavorite: indexPath.row)
}
}
}
| mit | fb0a3b75f5557aa19f502643e97d79c2 | 38.728571 | 110 | 0.656239 | 4.951335 | false | false | false | false |
eduarenas/GithubClient | Sources/GitHubClient/Utils/PageLinkParser.swift | 1 | 1039 | //
// PageLinkParser.swift
// GithubClient
//
// Created by Eduardo Arenas on 2/18/18.
// Copyright © 2018 GameChanger. All rights reserved.
//
import Foundation
struct PageLinks {
let first: String?
let previous: String?
let next: String?
let last: String?
}
final class PageLinkParser {
private static let regex = try! NSRegularExpression(pattern: "<(?<url>[^>]*)>; ?rel=\"(?<rel>[^\"]*)\"")
static func parse(linkString: String) -> PageLinks {
let matches = regex.matches(in: linkString, range: NSRange(linkString.startIndex..., in: linkString))
let relations = matches.map { String(linkString[Range($0.range(at: 2), in: linkString)!]) }
let urls = matches.map { String(linkString[Range($0.range(at: 1), in: linkString)!]) }
let dictionary = Dictionary(uniqueKeysWithValues: zip(relations, urls))
return PageLinks(first: dictionary["first"],
previous: dictionary["prev"],
next: dictionary["next"],
last: dictionary["last"])
}
}
| mit | c8348b8ba46e22161578ddff579fd55d | 30.454545 | 106 | 0.640655 | 3.844444 | false | false | false | false |
benlangmuir/swift | stdlib/public/core/Integers.swift | 4 | 141560 | //===--- Integers.swift ---------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2020 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
//
//===----------------------------------------------------------------------===//
//===----------------------------------------------------------------------===//
//===--- Bits for the Stdlib ----------------------------------------------===//
//===----------------------------------------------------------------------===//
// FIXME(integers): This should go in the stdlib separately, probably.
extension ExpressibleByIntegerLiteral
where Self: _ExpressibleByBuiltinIntegerLiteral {
@_transparent
public init(integerLiteral value: Self) {
self = value
}
}
//===----------------------------------------------------------------------===//
//===--- AdditiveArithmetic -----------------------------------------------===//
//===----------------------------------------------------------------------===//
/// A type with values that support addition and subtraction.
///
/// The `AdditiveArithmetic` protocol provides a suitable basis for additive
/// arithmetic on scalar values, such as integers and floating-point numbers,
/// or vectors. You can write generic methods that operate on any numeric type
/// in the standard library by using the `AdditiveArithmetic` protocol as a
/// generic constraint.
///
/// The following code declares a method that calculates the total of any
/// sequence with `AdditiveArithmetic` elements.
///
/// extension Sequence where Element: AdditiveArithmetic {
/// func sum() -> Element {
/// return reduce(.zero, +)
/// }
/// }
///
/// The `sum()` method is now available on any sequence with values that
/// conform to `AdditiveArithmetic`, whether it is an array of `Double` or a
/// range of `Int`.
///
/// let arraySum = [1.1, 2.2, 3.3, 4.4, 5.5].sum()
/// // arraySum == 16.5
///
/// let rangeSum = (1..<10).sum()
/// // rangeSum == 45
///
/// Conforming to the AdditiveArithmetic Protocol
/// =============================================
///
/// To add `AdditiveArithmetic` protocol conformance to your own custom type,
/// implement the required operators, and provide a static `zero` property.
public protocol AdditiveArithmetic: Equatable {
/// The zero value.
///
/// Zero is the identity element for addition. For any value,
/// `x + .zero == x` and `.zero + x == x`.
static var zero: Self { get }
/// Adds two values and produces their sum.
///
/// The addition operator (`+`) calculates the sum of its two arguments. For
/// example:
///
/// 1 + 2 // 3
/// -10 + 15 // 5
/// -15 + -5 // -20
/// 21.5 + 3.25 // 24.75
///
/// You cannot use `+` with arguments of different types. To add values of
/// different types, convert one of the values to the other value's type.
///
/// let x: Int8 = 21
/// let y: Int = 1000000
/// Int(x) + y // 1000021
///
/// - Parameters:
/// - lhs: The first value to add.
/// - rhs: The second value to add.
static func +(lhs: Self, rhs: Self) -> Self
/// Adds two values and stores the result in the left-hand-side variable.
///
/// - Parameters:
/// - lhs: The first value to add.
/// - rhs: The second value to add.
static func +=(lhs: inout Self, rhs: Self)
/// Subtracts one value from another and produces their difference.
///
/// The subtraction operator (`-`) calculates the difference of its two
/// arguments. For example:
///
/// 8 - 3 // 5
/// -10 - 5 // -15
/// 100 - -5 // 105
/// 10.5 - 100.0 // -89.5
///
/// You cannot use `-` with arguments of different types. To subtract values
/// of different types, convert one of the values to the other value's type.
///
/// let x: UInt8 = 21
/// let y: UInt = 1000000
/// y - UInt(x) // 999979
///
/// - Parameters:
/// - lhs: A numeric value.
/// - rhs: The value to subtract from `lhs`.
static func -(lhs: Self, rhs: Self) -> Self
/// Subtracts the second value from the first and stores the difference in the
/// left-hand-side variable.
///
/// - Parameters:
/// - lhs: A numeric value.
/// - rhs: The value to subtract from `lhs`.
static func -=(lhs: inout Self, rhs: Self)
}
public extension AdditiveArithmetic {
@_alwaysEmitIntoClient
static func +=(lhs: inout Self, rhs: Self) {
lhs = lhs + rhs
}
@_alwaysEmitIntoClient
static func -=(lhs: inout Self, rhs: Self) {
lhs = lhs - rhs
}
}
public extension AdditiveArithmetic where Self: ExpressibleByIntegerLiteral {
/// The zero value.
///
/// Zero is the identity element for addition. For any value,
/// `x + .zero == x` and `.zero + x == x`.
@inlinable @inline(__always)
static var zero: Self {
return 0
}
}
//===----------------------------------------------------------------------===//
//===--- Numeric ----------------------------------------------------------===//
//===----------------------------------------------------------------------===//
/// A type with values that support multiplication.
///
/// The `Numeric` protocol provides a suitable basis for arithmetic on
/// scalar values, such as integers and floating-point numbers. You can write
/// generic methods that operate on any numeric type in the standard library
/// by using the `Numeric` protocol as a generic constraint.
///
/// The following example extends `Sequence` with a method that returns an
/// array with the sequence's values multiplied by two.
///
/// extension Sequence where Element: Numeric {
/// func doublingAll() -> [Element] {
/// return map { $0 * 2 }
/// }
/// }
///
/// With this extension, any sequence with elements that conform to `Numeric`
/// has the `doublingAll()` method. For example, you can double the elements of
/// an array of doubles or a range of integers:
///
/// let observations = [1.5, 2.0, 3.25, 4.875, 5.5]
/// let doubledObservations = observations.doublingAll()
/// // doubledObservations == [3.0, 4.0, 6.5, 9.75, 11.0]
///
/// let integers = 0..<8
/// let doubledIntegers = integers.doublingAll()
/// // doubledIntegers == [0, 2, 4, 6, 8, 10, 12, 14]
///
/// Conforming to the Numeric Protocol
/// ==================================
///
/// To add `Numeric` protocol conformance to your own custom type, implement
/// the required initializer and operators, and provide a `magnitude` property
/// using a type that can represent the magnitude of any value of your custom
/// type.
public protocol Numeric: AdditiveArithmetic, ExpressibleByIntegerLiteral {
/// Creates a new instance from the given integer, if it can be represented
/// exactly.
///
/// If the value passed as `source` is not representable exactly, the result
/// is `nil`. In the following example, the constant `x` is successfully
/// created from a value of `100`, while the attempt to initialize the
/// constant `y` from `1_000` fails because the `Int8` type can represent
/// `127` at maximum:
///
/// let x = Int8(exactly: 100)
/// // x == Optional(100)
/// let y = Int8(exactly: 1_000)
/// // y == nil
///
/// - Parameter source: A value to convert to this type.
init?<T: BinaryInteger>(exactly source: T)
/// A type that can represent the absolute value of any possible value of the
/// conforming type.
associatedtype Magnitude: Comparable, Numeric
/// The magnitude of this value.
///
/// For any numeric value `x`, `x.magnitude` is the absolute value of `x`.
/// You can use the `magnitude` property in operations that are simpler to
/// implement in terms of unsigned values, such as printing the value of an
/// integer, which is just printing a '-' character in front of an absolute
/// value.
///
/// let x = -200
/// // x.magnitude == 200
///
/// The global `abs(_:)` function provides more familiar syntax when you need
/// to find an absolute value. In addition, because `abs(_:)` always returns
/// a value of the same type, even in a generic context, using the function
/// instead of the `magnitude` property is encouraged.
var magnitude: Magnitude { get }
/// Multiplies two values and produces their product.
///
/// The multiplication operator (`*`) calculates the product of its two
/// arguments. For example:
///
/// 2 * 3 // 6
/// 100 * 21 // 2100
/// -10 * 15 // -150
/// 3.5 * 2.25 // 7.875
///
/// You cannot use `*` with arguments of different types. To multiply values
/// of different types, convert one of the values to the other value's type.
///
/// let x: Int8 = 21
/// let y: Int = 1000000
/// Int(x) * y // 21000000
///
/// - Parameters:
/// - lhs: The first value to multiply.
/// - rhs: The second value to multiply.
static func *(lhs: Self, rhs: Self) -> Self
/// Multiplies two values and stores the result in the left-hand-side
/// variable.
///
/// - Parameters:
/// - lhs: The first value to multiply.
/// - rhs: The second value to multiply.
static func *=(lhs: inout Self, rhs: Self)
}
/// A numeric type with a negation operation.
///
/// The `SignedNumeric` protocol extends the operations defined by the
/// `Numeric` protocol to include a value's additive inverse.
///
/// Conforming to the SignedNumeric Protocol
/// ========================================
///
/// Because the `SignedNumeric` protocol provides default implementations of
/// both of its required methods, you don't need to do anything beyond
/// declaring conformance to the protocol and ensuring that the values of your
/// type support negation. To customize your type's implementation, provide
/// your own mutating `negate()` method.
///
/// When the additive inverse of a value is unrepresentable in a conforming
/// type, the operation should either trap or return an exceptional value. For
/// example, using the negation operator (prefix `-`) with `Int.min` results in
/// a runtime error.
///
/// let x = Int.min
/// let y = -x
/// // Overflow error
public protocol SignedNumeric: Numeric {
/// Returns the additive inverse of the specified value.
///
/// The negation operator (prefix `-`) returns the additive inverse of its
/// argument.
///
/// let x = 21
/// let y = -x
/// // y == -21
///
/// The resulting value must be representable in the same type as the
/// argument. In particular, negating a signed, fixed-width integer type's
/// minimum results in a value that cannot be represented.
///
/// let z = -Int8.min
/// // Overflow error
///
/// - Returns: The additive inverse of this value.
static prefix func - (_ operand: Self) -> Self
/// Replaces this value with its additive inverse.
///
/// The following example uses the `negate()` method to negate the value of
/// an integer `x`:
///
/// var x = 21
/// x.negate()
/// // x == -21
///
/// The resulting value must be representable within the value's type. In
/// particular, negating a signed, fixed-width integer type's minimum
/// results in a value that cannot be represented.
///
/// var y = Int8.min
/// y.negate()
/// // Overflow error
mutating func negate()
}
extension SignedNumeric {
/// Returns the additive inverse of the specified value.
///
/// The negation operator (prefix `-`) returns the additive inverse of its
/// argument.
///
/// let x = 21
/// let y = -x
/// // y == -21
///
/// The resulting value must be representable in the same type as the
/// argument. In particular, negating a signed, fixed-width integer type's
/// minimum results in a value that cannot be represented.
///
/// let z = -Int8.min
/// // Overflow error
///
/// - Returns: The additive inverse of the argument.
@_transparent
public static prefix func - (_ operand: Self) -> Self {
var result = operand
result.negate()
return result
}
/// Replaces this value with its additive inverse.
///
/// The following example uses the `negate()` method to negate the value of
/// an integer `x`:
///
/// var x = 21
/// x.negate()
/// // x == -21
///
/// The resulting value must be representable within the value's type. In
/// particular, negating a signed, fixed-width integer type's minimum
/// results in a value that cannot be represented.
///
/// var y = Int8.min
/// y.negate()
/// // Overflow error
@_transparent
public mutating func negate() {
self = 0 - self
}
}
/// Returns the absolute value of the given number.
///
/// The absolute value of `x` must be representable in the same type. In
/// particular, the absolute value of a signed, fixed-width integer type's
/// minimum cannot be represented.
///
/// let x = Int8.min
/// // x == -128
/// let y = abs(x)
/// // Overflow error
///
/// - Parameter x: A signed number.
/// - Returns: The absolute value of `x`.
@inlinable
public func abs<T: SignedNumeric & Comparable>(_ x: T) -> T {
if T.self == T.Magnitude.self {
return unsafeBitCast(x.magnitude, to: T.self)
}
return x < (0 as T) ? -x : x
}
extension AdditiveArithmetic {
/// Returns the given number unchanged.
///
/// You can use the unary plus operator (`+`) to provide symmetry in your
/// code for positive numbers when also using the unary minus operator.
///
/// let x = -21
/// let y = +21
/// // x == -21
/// // y == 21
///
/// - Returns: The given argument without any changes.
@_transparent
public static prefix func + (x: Self) -> Self {
return x
}
}
//===----------------------------------------------------------------------===//
//===--- BinaryInteger ----------------------------------------------------===//
//===----------------------------------------------------------------------===//
/// An integer type with a binary representation.
///
/// The `BinaryInteger` protocol is the basis for all the integer types
/// provided by the standard library. All of the standard library's integer
/// types, such as `Int` and `UInt32`, conform to `BinaryInteger`.
///
/// Converting Between Numeric Types
/// ================================
///
/// You can create new instances of a type that conforms to the `BinaryInteger`
/// protocol from a floating-point number or another binary integer of any
/// type. The `BinaryInteger` protocol provides initializers for four
/// different kinds of conversion.
///
/// Range-Checked Conversion
/// ------------------------
///
/// You use the default `init(_:)` initializer to create a new instance when
/// you're sure that the value passed is representable in the new type. For
/// example, an instance of `Int16` can represent the value `500`, so the
/// first conversion in the code sample below succeeds. That same value is too
/// large to represent as an `Int8` instance, so the second conversion fails,
/// triggering a runtime error.
///
/// let x: Int = 500
/// let y = Int16(x)
/// // y == 500
///
/// let z = Int8(x)
/// // Error: Not enough bits to represent...
///
/// When you create a binary integer from a floating-point value using the
/// default initializer, the value is rounded toward zero before the range is
/// checked. In the following example, the value `127.75` is rounded to `127`,
/// which is representable by the `Int8` type. `128.25` is rounded to `128`,
/// which is not representable as an `Int8` instance, triggering a runtime
/// error.
///
/// let e = Int8(127.75)
/// // e == 127
///
/// let f = Int8(128.25)
/// // Error: Double value cannot be converted...
///
///
/// Exact Conversion
/// ----------------
///
/// Use the `init?(exactly:)` initializer to create a new instance after
/// checking whether the passed value is representable. Instead of trapping on
/// out-of-range values, using the failable `init?(exactly:)`
/// initializer results in `nil`.
///
/// let x = Int16(exactly: 500)
/// // x == Optional(500)
///
/// let y = Int8(exactly: 500)
/// // y == nil
///
/// When converting floating-point values, the `init?(exactly:)` initializer
/// checks both that the passed value has no fractional part and that the
/// value is representable in the resulting type.
///
/// let e = Int8(exactly: 23.0) // integral value, representable
/// // e == Optional(23)
///
/// let f = Int8(exactly: 23.75) // fractional value, representable
/// // f == nil
///
/// let g = Int8(exactly: 500.0) // integral value, nonrepresentable
/// // g == nil
///
/// Clamping Conversion
/// -------------------
///
/// Use the `init(clamping:)` initializer to create a new instance of a binary
/// integer type where out-of-range values are clamped to the representable
/// range of the type. For a type `T`, the resulting value is in the range
/// `T.min...T.max`.
///
/// let x = Int16(clamping: 500)
/// // x == 500
///
/// let y = Int8(clamping: 500)
/// // y == 127
///
/// let z = UInt8(clamping: -500)
/// // z == 0
///
/// Bit Pattern Conversion
/// ----------------------
///
/// Use the `init(truncatingIfNeeded:)` initializer to create a new instance
/// with the same bit pattern as the passed value, extending or truncating the
/// value's representation as necessary. Note that the value may not be
/// preserved, particularly when converting between signed to unsigned integer
/// types or when the destination type has a smaller bit width than the source
/// type. The following example shows how extending and truncating work for
/// nonnegative integers:
///
/// let q: Int16 = 850
/// // q == 0b00000011_01010010
///
/// let r = Int8(truncatingIfNeeded: q) // truncate 'q' to fit in 8 bits
/// // r == 82
/// // == 0b01010010
///
/// let s = Int16(truncatingIfNeeded: r) // extend 'r' to fill 16 bits
/// // s == 82
/// // == 0b00000000_01010010
///
/// Any padding is performed by *sign-extending* the passed value. When
/// nonnegative integers are extended, the result is padded with zeroes. When
/// negative integers are extended, the result is padded with ones. This
/// example shows several extending conversions of a negative value---note
/// that negative values are sign-extended even when converting to an unsigned
/// type.
///
/// let t: Int8 = -100
/// // t == -100
/// // t's binary representation == 0b10011100
///
/// let u = UInt8(truncatingIfNeeded: t)
/// // u == 156
/// // u's binary representation == 0b10011100
///
/// let v = Int16(truncatingIfNeeded: t)
/// // v == -100
/// // v's binary representation == 0b11111111_10011100
///
/// let w = UInt16(truncatingIfNeeded: t)
/// // w == 65436
/// // w's binary representation == 0b11111111_10011100
///
///
/// Comparing Across Integer Types
/// ==============================
///
/// You can use relational operators, such as the less-than and equal-to
/// operators (`<` and `==`), to compare instances of different binary integer
/// types. The following example compares instances of the `Int`, `UInt`, and
/// `UInt8` types:
///
/// let x: Int = -23
/// let y: UInt = 1_000
/// let z: UInt8 = 23
///
/// if x < y {
/// print("\(x) is less than \(y).")
/// }
/// // Prints "-23 is less than 1000."
///
/// if z > x {
/// print("\(z) is greater than \(x).")
/// }
/// // Prints "23 is greater than -23."
public protocol BinaryInteger :
Hashable, Numeric, CustomStringConvertible, Strideable
where Magnitude: BinaryInteger, Magnitude.Magnitude == Magnitude
{
/// A Boolean value indicating whether this type is a signed integer type.
///
/// *Signed* integer types can represent both positive and negative values.
/// *Unsigned* integer types can represent only nonnegative values.
static var isSigned: Bool { get }
/// Creates an integer from the given floating-point value, if it can be
/// represented exactly.
///
/// If the value passed as `source` is not representable exactly, the result
/// is `nil`. In the following example, the constant `x` is successfully
/// created from a value of `21.0`, while the attempt to initialize the
/// constant `y` from `21.5` fails:
///
/// let x = Int(exactly: 21.0)
/// // x == Optional(21)
/// let y = Int(exactly: 21.5)
/// // y == nil
///
/// - Parameter source: A floating-point value to convert to an integer.
init?<T: BinaryFloatingPoint>(exactly source: T)
/// Creates an integer from the given floating-point value, rounding toward
/// zero.
///
/// Any fractional part of the value passed as `source` is removed, rounding
/// the value toward zero.
///
/// let x = Int(21.5)
/// // x == 21
/// let y = Int(-21.5)
/// // y == -21
///
/// If `source` is outside the bounds of this type after rounding toward
/// zero, a runtime error may occur.
///
/// let z = UInt(-21.5)
/// // Error: ...the result would be less than UInt.min
///
/// - Parameter source: A floating-point value to convert to an integer.
/// `source` must be representable in this type after rounding toward
/// zero.
init<T: BinaryFloatingPoint>(_ source: T)
/// Creates a new instance from the given integer.
///
/// If the value passed as `source` is not representable in this type, a
/// runtime error may occur.
///
/// let x = -500 as Int
/// let y = Int32(x)
/// // y == -500
///
/// // -500 is not representable as a 'UInt32' instance
/// let z = UInt32(x)
/// // Error
///
/// - Parameter source: An integer to convert. `source` must be representable
/// in this type.
init<T: BinaryInteger>(_ source: T)
/// Creates a new instance from the bit pattern of the given instance by
/// sign-extending or truncating to fit this type.
///
/// When the bit width of `T` (the type of `source`) is equal to or greater
/// than this type's bit width, the result is the truncated
/// least-significant bits of `source`. For example, when converting a
/// 16-bit value to an 8-bit type, only the lower 8 bits of `source` are
/// used.
///
/// let p: Int16 = -500
/// // 'p' has a binary representation of 11111110_00001100
/// let q = Int8(truncatingIfNeeded: p)
/// // q == 12
/// // 'q' has a binary representation of 00001100
///
/// When the bit width of `T` is less than this type's bit width, the result
/// is *sign-extended* to fill the remaining bits. That is, if `source` is
/// negative, the result is padded with ones; otherwise, the result is
/// padded with zeros.
///
/// let u: Int8 = 21
/// // 'u' has a binary representation of 00010101
/// let v = Int16(truncatingIfNeeded: u)
/// // v == 21
/// // 'v' has a binary representation of 00000000_00010101
///
/// let w: Int8 = -21
/// // 'w' has a binary representation of 11101011
/// let x = Int16(truncatingIfNeeded: w)
/// // x == -21
/// // 'x' has a binary representation of 11111111_11101011
/// let y = UInt16(truncatingIfNeeded: w)
/// // y == 65515
/// // 'y' has a binary representation of 11111111_11101011
///
/// - Parameter source: An integer to convert to this type.
init<T: BinaryInteger>(truncatingIfNeeded source: T)
/// Creates a new instance with the representable value that's closest to the
/// given integer.
///
/// If the value passed as `source` is greater than the maximum representable
/// value in this type, the result is the type's `max` value. If `source` is
/// less than the smallest representable value in this type, the result is
/// the type's `min` value.
///
/// In this example, `x` is initialized as an `Int8` instance by clamping
/// `500` to the range `-128...127`, and `y` is initialized as a `UInt`
/// instance by clamping `-500` to the range `0...UInt.max`.
///
/// let x = Int8(clamping: 500)
/// // x == 127
/// // x == Int8.max
///
/// let y = UInt(clamping: -500)
/// // y == 0
///
/// - Parameter source: An integer to convert to this type.
init<T: BinaryInteger>(clamping source: T)
/// A type that represents the words of a binary integer.
///
/// The `Words` type must conform to the `RandomAccessCollection` protocol
/// with an `Element` type of `UInt` and `Index` type of `Int`.
associatedtype Words: RandomAccessCollection
where Words.Element == UInt, Words.Index == Int
/// A collection containing the words of this value's binary
/// representation, in order from the least significant to most significant.
///
/// Negative values are returned in two's complement representation,
/// regardless of the type's underlying implementation.
var words: Words { get }
/// The least significant word in this value's binary representation.
var _lowWord: UInt { get }
/// The number of bits in the current binary representation of this value.
///
/// This property is a constant for instances of fixed-width integer
/// types.
var bitWidth: Int { get }
/// Returns the integer binary logarithm of this value.
///
/// If the value is negative or zero, a runtime error will occur.
func _binaryLogarithm() -> Int
/// The number of trailing zeros in this value's binary representation.
///
/// For example, in a fixed-width integer type with a `bitWidth` value of 8,
/// the number -8 has three trailing zeros.
///
/// let x = Int8(bitPattern: 0b1111_1000)
/// // x == -8
/// // x.trailingZeroBitCount == 3
///
/// If the value is zero, then `trailingZeroBitCount` is equal to `bitWidth`.
var trailingZeroBitCount: Int { get }
/// Returns the quotient of dividing the first value by the second.
///
/// For integer types, any remainder of the division is discarded.
///
/// let x = 21 / 5
/// // x == 4
///
/// - Parameters:
/// - lhs: The value to divide.
/// - rhs: The value to divide `lhs` by. `rhs` must not be zero.
static func /(lhs: Self, rhs: Self) -> Self
/// Divides the first value by the second and stores the quotient in the
/// left-hand-side variable.
///
/// For integer types, any remainder of the division is discarded.
///
/// var x = 21
/// x /= 5
/// // x == 4
///
/// - Parameters:
/// - lhs: The value to divide.
/// - rhs: The value to divide `lhs` by. `rhs` must not be zero.
static func /=(lhs: inout Self, rhs: Self)
/// Returns the remainder of dividing the first value by the second.
///
/// The result of the remainder operator (`%`) has the same sign as `lhs` and
/// has a magnitude less than `rhs.magnitude`.
///
/// let x = 22 % 5
/// // x == 2
/// let y = 22 % -5
/// // y == 2
/// let z = -22 % -5
/// // z == -2
///
/// For any two integers `a` and `b`, their quotient `q`, and their remainder
/// `r`, `a == b * q + r`.
///
/// - Parameters:
/// - lhs: The value to divide.
/// - rhs: The value to divide `lhs` by. `rhs` must not be zero.
static func %(lhs: Self, rhs: Self) -> Self
/// Divides the first value by the second and stores the remainder in the
/// left-hand-side variable.
///
/// The result has the same sign as `lhs` and has a magnitude less than
/// `rhs.magnitude`.
///
/// var x = 22
/// x %= 5
/// // x == 2
///
/// var y = 22
/// y %= -5
/// // y == 2
///
/// var z = -22
/// z %= -5
/// // z == -2
///
/// - Parameters:
/// - lhs: The value to divide.
/// - rhs: The value to divide `lhs` by. `rhs` must not be zero.
static func %=(lhs: inout Self, rhs: Self)
/// Adds two values and produces their sum.
///
/// The addition operator (`+`) calculates the sum of its two arguments. For
/// example:
///
/// 1 + 2 // 3
/// -10 + 15 // 5
/// -15 + -5 // -20
/// 21.5 + 3.25 // 24.75
///
/// You cannot use `+` with arguments of different types. To add values of
/// different types, convert one of the values to the other value's type.
///
/// let x: Int8 = 21
/// let y: Int = 1000000
/// Int(x) + y // 1000021
///
/// - Parameters:
/// - lhs: The first value to add.
/// - rhs: The second value to add.
override static func +(lhs: Self, rhs: Self) -> Self
/// Adds two values and stores the result in the left-hand-side variable.
///
/// - Parameters:
/// - lhs: The first value to add.
/// - rhs: The second value to add.
override static func +=(lhs: inout Self, rhs: Self)
/// Subtracts one value from another and produces their difference.
///
/// The subtraction operator (`-`) calculates the difference of its two
/// arguments. For example:
///
/// 8 - 3 // 5
/// -10 - 5 // -15
/// 100 - -5 // 105
/// 10.5 - 100.0 // -89.5
///
/// You cannot use `-` with arguments of different types. To subtract values
/// of different types, convert one of the values to the other value's type.
///
/// let x: UInt8 = 21
/// let y: UInt = 1000000
/// y - UInt(x) // 999979
///
/// - Parameters:
/// - lhs: A numeric value.
/// - rhs: The value to subtract from `lhs`.
override static func -(lhs: Self, rhs: Self) -> Self
/// Subtracts the second value from the first and stores the difference in the
/// left-hand-side variable.
///
/// - Parameters:
/// - lhs: A numeric value.
/// - rhs: The value to subtract from `lhs`.
override static func -=(lhs: inout Self, rhs: Self)
/// Multiplies two values and produces their product.
///
/// The multiplication operator (`*`) calculates the product of its two
/// arguments. For example:
///
/// 2 * 3 // 6
/// 100 * 21 // 2100
/// -10 * 15 // -150
/// 3.5 * 2.25 // 7.875
///
/// You cannot use `*` with arguments of different types. To multiply values
/// of different types, convert one of the values to the other value's type.
///
/// let x: Int8 = 21
/// let y: Int = 1000000
/// Int(x) * y // 21000000
///
/// - Parameters:
/// - lhs: The first value to multiply.
/// - rhs: The second value to multiply.
override static func *(lhs: Self, rhs: Self) -> Self
/// Multiplies two values and stores the result in the left-hand-side
/// variable.
///
/// - Parameters:
/// - lhs: The first value to multiply.
/// - rhs: The second value to multiply.
override static func *=(lhs: inout Self, rhs: Self)
/// Returns the inverse of the bits set in the argument.
///
/// The bitwise NOT operator (`~`) is a prefix operator that returns a value
/// in which all the bits of its argument are flipped: Bits that are `1` in
/// the argument are `0` in the result, and bits that are `0` in the argument
/// are `1` in the result. This is equivalent to the inverse of a set. For
/// example:
///
/// let x: UInt8 = 5 // 0b00000101
/// let notX = ~x // 0b11111010
///
/// Performing a bitwise NOT operation on 0 returns a value with every bit
/// set to `1`.
///
/// let allOnes = ~UInt8.min // 0b11111111
///
/// - Complexity: O(1).
static prefix func ~ (_ x: Self) -> Self
/// Returns the result of performing a bitwise AND operation on the two given
/// values.
///
/// A bitwise AND operation results in a value that has each bit set to `1`
/// where *both* of its arguments have that bit set to `1`. For example:
///
/// let x: UInt8 = 5 // 0b00000101
/// let y: UInt8 = 14 // 0b00001110
/// let z = x & y // 0b00000100
/// // z == 4
///
/// - Parameters:
/// - lhs: An integer value.
/// - rhs: Another integer value.
static func &(lhs: Self, rhs: Self) -> Self
/// Stores the result of performing a bitwise AND operation on the two given
/// values in the left-hand-side variable.
///
/// A bitwise AND operation results in a value that has each bit set to `1`
/// where *both* of its arguments have that bit set to `1`. For example:
///
/// var x: UInt8 = 5 // 0b00000101
/// let y: UInt8 = 14 // 0b00001110
/// x &= y // 0b00000100
///
/// - Parameters:
/// - lhs: An integer value.
/// - rhs: Another integer value.
static func &=(lhs: inout Self, rhs: Self)
/// Returns the result of performing a bitwise OR operation on the two given
/// values.
///
/// A bitwise OR operation results in a value that has each bit set to `1`
/// where *one or both* of its arguments have that bit set to `1`. For
/// example:
///
/// let x: UInt8 = 5 // 0b00000101
/// let y: UInt8 = 14 // 0b00001110
/// let z = x | y // 0b00001111
/// // z == 15
///
/// - Parameters:
/// - lhs: An integer value.
/// - rhs: Another integer value.
static func |(lhs: Self, rhs: Self) -> Self
/// Stores the result of performing a bitwise OR operation on the two given
/// values in the left-hand-side variable.
///
/// A bitwise OR operation results in a value that has each bit set to `1`
/// where *one or both* of its arguments have that bit set to `1`. For
/// example:
///
/// var x: UInt8 = 5 // 0b00000101
/// let y: UInt8 = 14 // 0b00001110
/// x |= y // 0b00001111
///
/// - Parameters:
/// - lhs: An integer value.
/// - rhs: Another integer value.
static func |=(lhs: inout Self, rhs: Self)
/// Returns the result of performing a bitwise XOR operation on the two given
/// values.
///
/// A bitwise XOR operation, also known as an exclusive OR operation, results
/// in a value that has each bit set to `1` where *one or the other but not
/// both* of its arguments had that bit set to `1`. For example:
///
/// let x: UInt8 = 5 // 0b00000101
/// let y: UInt8 = 14 // 0b00001110
/// let z = x ^ y // 0b00001011
/// // z == 11
///
/// - Parameters:
/// - lhs: An integer value.
/// - rhs: Another integer value.
static func ^(lhs: Self, rhs: Self) -> Self
/// Stores the result of performing a bitwise XOR operation on the two given
/// values in the left-hand-side variable.
///
/// A bitwise XOR operation, also known as an exclusive OR operation, results
/// in a value that has each bit set to `1` where *one or the other but not
/// both* of its arguments had that bit set to `1`. For example:
///
/// var x: UInt8 = 5 // 0b00000101
/// let y: UInt8 = 14 // 0b00001110
/// x ^= y // 0b00001011
///
/// - Parameters:
/// - lhs: An integer value.
/// - rhs: Another integer value.
static func ^=(lhs: inout Self, rhs: Self)
/// Returns the result of shifting a value's binary representation the
/// specified number of digits to the right.
///
/// The `>>` operator performs a *smart shift*, which defines a result for a
/// shift of any value.
///
/// - Using a negative value for `rhs` performs a left shift using
/// `abs(rhs)`.
/// - Using a value for `rhs` that is greater than or equal to the bit width
/// of `lhs` is an *overshift*. An overshift results in `-1` for a
/// negative value of `lhs` or `0` for a nonnegative value.
/// - Using any other value for `rhs` performs a right shift on `lhs` by that
/// amount.
///
/// The following example defines `x` as an instance of `UInt8`, an 8-bit,
/// unsigned integer type. If you use `2` as the right-hand-side value in an
/// operation on `x`, the value is shifted right by two bits.
///
/// let x: UInt8 = 30 // 0b00011110
/// let y = x >> 2
/// // y == 7 // 0b00000111
///
/// If you use `11` as `rhs`, `x` is overshifted such that all of its bits
/// are set to zero.
///
/// let z = x >> 11
/// // z == 0 // 0b00000000
///
/// Using a negative value as `rhs` is the same as performing a left shift
/// using `abs(rhs)`.
///
/// let a = x >> -3
/// // a == 240 // 0b11110000
/// let b = x << 3
/// // b == 240 // 0b11110000
///
/// Right shift operations on negative values "fill in" the high bits with
/// ones instead of zeros.
///
/// let q: Int8 = -30 // 0b11100010
/// let r = q >> 2
/// // r == -8 // 0b11111000
///
/// let s = q >> 11
/// // s == -1 // 0b11111111
///
/// - Parameters:
/// - lhs: The value to shift.
/// - rhs: The number of bits to shift `lhs` to the right.
static func >> <RHS: BinaryInteger>(lhs: Self, rhs: RHS) -> Self
/// Stores the result of shifting a value's binary representation the
/// specified number of digits to the right in the left-hand-side variable.
///
/// The `>>=` operator performs a *smart shift*, which defines a result for a
/// shift of any value.
///
/// - Using a negative value for `rhs` performs a left shift using
/// `abs(rhs)`.
/// - Using a value for `rhs` that is greater than or equal to the bit width
/// of `lhs` is an *overshift*. An overshift results in `-1` for a
/// negative value of `lhs` or `0` for a nonnegative value.
/// - Using any other value for `rhs` performs a right shift on `lhs` by that
/// amount.
///
/// The following example defines `x` as an instance of `UInt8`, an 8-bit,
/// unsigned integer type. If you use `2` as the right-hand-side value in an
/// operation on `x`, the value is shifted right by two bits.
///
/// var x: UInt8 = 30 // 0b00011110
/// x >>= 2
/// // x == 7 // 0b00000111
///
/// If you use `11` as `rhs`, `x` is overshifted such that all of its bits
/// are set to zero.
///
/// var y: UInt8 = 30 // 0b00011110
/// y >>= 11
/// // y == 0 // 0b00000000
///
/// Using a negative value as `rhs` is the same as performing a left shift
/// using `abs(rhs)`.
///
/// var a: UInt8 = 30 // 0b00011110
/// a >>= -3
/// // a == 240 // 0b11110000
///
/// var b: UInt8 = 30 // 0b00011110
/// b <<= 3
/// // b == 240 // 0b11110000
///
/// Right shift operations on negative values "fill in" the high bits with
/// ones instead of zeros.
///
/// var q: Int8 = -30 // 0b11100010
/// q >>= 2
/// // q == -8 // 0b11111000
///
/// var r: Int8 = -30 // 0b11100010
/// r >>= 11
/// // r == -1 // 0b11111111
///
/// - Parameters:
/// - lhs: The value to shift.
/// - rhs: The number of bits to shift `lhs` to the right.
static func >>= <RHS: BinaryInteger>(lhs: inout Self, rhs: RHS)
/// Returns the result of shifting a value's binary representation the
/// specified number of digits to the left.
///
/// The `<<` operator performs a *smart shift*, which defines a result for a
/// shift of any value.
///
/// - Using a negative value for `rhs` performs a right shift using
/// `abs(rhs)`.
/// - Using a value for `rhs` that is greater than or equal to the bit width
/// of `lhs` is an *overshift*, resulting in zero.
/// - Using any other value for `rhs` performs a left shift on `lhs` by that
/// amount.
///
/// The following example defines `x` as an instance of `UInt8`, an 8-bit,
/// unsigned integer type. If you use `2` as the right-hand-side value in an
/// operation on `x`, the value is shifted left by two bits.
///
/// let x: UInt8 = 30 // 0b00011110
/// let y = x << 2
/// // y == 120 // 0b01111000
///
/// If you use `11` as `rhs`, `x` is overshifted such that all of its bits
/// are set to zero.
///
/// let z = x << 11
/// // z == 0 // 0b00000000
///
/// Using a negative value as `rhs` is the same as performing a right shift
/// with `abs(rhs)`.
///
/// let a = x << -3
/// // a == 3 // 0b00000011
/// let b = x >> 3
/// // b == 3 // 0b00000011
///
/// - Parameters:
/// - lhs: The value to shift.
/// - rhs: The number of bits to shift `lhs` to the left.
static func << <RHS: BinaryInteger>(lhs: Self, rhs: RHS) -> Self
/// Stores the result of shifting a value's binary representation the
/// specified number of digits to the left in the left-hand-side variable.
///
/// The `<<` operator performs a *smart shift*, which defines a result for a
/// shift of any value.
///
/// - Using a negative value for `rhs` performs a right shift using
/// `abs(rhs)`.
/// - Using a value for `rhs` that is greater than or equal to the bit width
/// of `lhs` is an *overshift*, resulting in zero.
/// - Using any other value for `rhs` performs a left shift on `lhs` by that
/// amount.
///
/// The following example defines `x` as an instance of `UInt8`, an 8-bit,
/// unsigned integer type. If you use `2` as the right-hand-side value in an
/// operation on `x`, the value is shifted left by two bits.
///
/// var x: UInt8 = 30 // 0b00011110
/// x <<= 2
/// // x == 120 // 0b01111000
///
/// If you use `11` as `rhs`, `x` is overshifted such that all of its bits
/// are set to zero.
///
/// var y: UInt8 = 30 // 0b00011110
/// y <<= 11
/// // y == 0 // 0b00000000
///
/// Using a negative value as `rhs` is the same as performing a right shift
/// with `abs(rhs)`.
///
/// var a: UInt8 = 30 // 0b00011110
/// a <<= -3
/// // a == 3 // 0b00000011
///
/// var b: UInt8 = 30 // 0b00011110
/// b >>= 3
/// // b == 3 // 0b00000011
///
/// - Parameters:
/// - lhs: The value to shift.
/// - rhs: The number of bits to shift `lhs` to the left.
static func <<=<RHS: BinaryInteger>(lhs: inout Self, rhs: RHS)
/// Returns the quotient and remainder of this value divided by the given
/// value.
///
/// Use this method to calculate the quotient and remainder of a division at
/// the same time.
///
/// let x = 1_000_000
/// let (q, r) = x.quotientAndRemainder(dividingBy: 933)
/// // q == 1071
/// // r == 757
///
/// - Parameter rhs: The value to divide this value by.
/// - Returns: A tuple containing the quotient and remainder of this value
/// divided by `rhs`. The remainder has the same sign as `lhs`.
func quotientAndRemainder(dividingBy rhs: Self)
-> (quotient: Self, remainder: Self)
/// Returns `true` if this value is a multiple of the given value, and `false`
/// otherwise.
///
/// For two integers *a* and *b*, *a* is a multiple of *b* if there exists a
/// third integer *q* such that _a = q*b_. For example, *6* is a multiple of
/// *3* because _6 = 2*3_. Zero is a multiple of everything because _0 = 0*x_
/// for any integer *x*.
///
/// Two edge cases are worth particular attention:
/// - `x.isMultiple(of: 0)` is `true` if `x` is zero and `false` otherwise.
/// - `T.min.isMultiple(of: -1)` is `true` for signed integer `T`, even
/// though the quotient `T.min / -1` isn't representable in type `T`.
///
/// - Parameter other: The value to test.
func isMultiple(of other: Self) -> Bool
/// Returns `-1` if this value is negative and `1` if it's positive;
/// otherwise, `0`.
///
/// - Returns: The sign of this number, expressed as an integer of the same
/// type.
func signum() -> Self
}
extension BinaryInteger {
/// Creates a new value equal to zero.
@_transparent
public init() {
self = 0
}
/// Returns `-1` if this value is negative and `1` if it's positive;
/// otherwise, `0`.
///
/// - Returns: The sign of this number, expressed as an integer of the same
/// type.
@inlinable
public func signum() -> Self {
return (self > (0 as Self) ? 1 : 0) - (self < (0 as Self) ? 1 : 0)
}
@_transparent
public var _lowWord: UInt {
var it = words.makeIterator()
return it.next() ?? 0
}
@inlinable
public func _binaryLogarithm() -> Int {
_precondition(self > (0 as Self))
var (quotient, remainder) =
(bitWidth &- 1).quotientAndRemainder(dividingBy: UInt.bitWidth)
remainder = remainder &+ 1
var word = UInt(truncatingIfNeeded: self >> (bitWidth &- remainder))
// If, internally, a variable-width binary integer uses digits of greater
// bit width than that of Magnitude.Words.Element (i.e., UInt), then it is
// possible that `word` could be zero. Additionally, a signed variable-width
// binary integer may have a leading word that is zero to store a clear sign
// bit.
while word == 0 {
quotient = quotient &- 1
remainder = remainder &+ UInt.bitWidth
word = UInt(truncatingIfNeeded: self >> (bitWidth &- remainder))
}
// Note that the order of operations below is important to guarantee that
// we won't overflow.
return UInt.bitWidth &* quotient &+
(UInt.bitWidth &- (word.leadingZeroBitCount &+ 1))
}
/// Returns the quotient and remainder of this value divided by the given
/// value.
///
/// Use this method to calculate the quotient and remainder of a division at
/// the same time.
///
/// let x = 1_000_000
/// let (q, r) = x.quotientAndRemainder(dividingBy: 933)
/// // q == 1071
/// // r == 757
///
/// - Parameter rhs: The value to divide this value by.
/// - Returns: A tuple containing the quotient and remainder of this value
/// divided by `rhs`.
@inlinable
public func quotientAndRemainder(dividingBy rhs: Self)
-> (quotient: Self, remainder: Self) {
return (self / rhs, self % rhs)
}
@inlinable
public func isMultiple(of other: Self) -> Bool {
// Nothing but zero is a multiple of zero.
if other == 0 { return self == 0 }
// Do the test in terms of magnitude, which guarantees there are no other
// edge cases. If we write this as `self % other` instead, it could trap
// for types that are not symmetric around zero.
return self.magnitude % other.magnitude == 0
}
//===----------------------------------------------------------------------===//
//===--- Homogeneous ------------------------------------------------------===//
//===----------------------------------------------------------------------===//
/// Returns the result of performing a bitwise AND operation on the two given
/// values.
///
/// A bitwise AND operation results in a value that has each bit set to `1`
/// where *both* of its arguments have that bit set to `1`. For example:
///
/// let x: UInt8 = 5 // 0b00000101
/// let y: UInt8 = 14 // 0b00001110
/// let z = x & y // 0b00000100
/// // z == 4
///
/// - Parameters:
/// - lhs: An integer value.
/// - rhs: Another integer value.
@_transparent
public static func & (lhs: Self, rhs: Self) -> Self {
var lhs = lhs
lhs &= rhs
return lhs
}
/// Returns the result of performing a bitwise OR operation on the two given
/// values.
///
/// A bitwise OR operation results in a value that has each bit set to `1`
/// where *one or both* of its arguments have that bit set to `1`. For
/// example:
///
/// let x: UInt8 = 5 // 0b00000101
/// let y: UInt8 = 14 // 0b00001110
/// let z = x | y // 0b00001111
/// // z == 15
///
/// - Parameters:
/// - lhs: An integer value.
/// - rhs: Another integer value.
@_transparent
public static func | (lhs: Self, rhs: Self) -> Self {
var lhs = lhs
lhs |= rhs
return lhs
}
/// Returns the result of performing a bitwise XOR operation on the two given
/// values.
///
/// A bitwise XOR operation, also known as an exclusive OR operation, results
/// in a value that has each bit set to `1` where *one or the other but not
/// both* of its arguments had that bit set to `1`. For example:
///
/// let x: UInt8 = 5 // 0b00000101
/// let y: UInt8 = 14 // 0b00001110
/// let z = x ^ y // 0b00001011
/// // z == 11
///
/// - Parameters:
/// - lhs: An integer value.
/// - rhs: Another integer value.
@_transparent
public static func ^ (lhs: Self, rhs: Self) -> Self {
var lhs = lhs
lhs ^= rhs
return lhs
}
//===----------------------------------------------------------------------===//
//===--- Heterogeneous non-masking shift in terms of shift-assignment -----===//
//===----------------------------------------------------------------------===//
/// Returns the result of shifting a value's binary representation the
/// specified number of digits to the right.
///
/// The `>>` operator performs a *smart shift*, which defines a result for a
/// shift of any value.
///
/// - Using a negative value for `rhs` performs a left shift using
/// `abs(rhs)`.
/// - Using a value for `rhs` that is greater than or equal to the bit width
/// of `lhs` is an *overshift*. An overshift results in `-1` for a
/// negative value of `lhs` or `0` for a nonnegative value.
/// - Using any other value for `rhs` performs a right shift on `lhs` by that
/// amount.
///
/// The following example defines `x` as an instance of `UInt8`, an 8-bit,
/// unsigned integer type. If you use `2` as the right-hand-side value in an
/// operation on `x`, the value is shifted right by two bits.
///
/// let x: UInt8 = 30 // 0b00011110
/// let y = x >> 2
/// // y == 7 // 0b00000111
///
/// If you use `11` as `rhs`, `x` is overshifted such that all of its bits
/// are set to zero.
///
/// let z = x >> 11
/// // z == 0 // 0b00000000
///
/// Using a negative value as `rhs` is the same as performing a left shift
/// using `abs(rhs)`.
///
/// let a = x >> -3
/// // a == 240 // 0b11110000
/// let b = x << 3
/// // b == 240 // 0b11110000
///
/// Right shift operations on negative values "fill in" the high bits with
/// ones instead of zeros.
///
/// let q: Int8 = -30 // 0b11100010
/// let r = q >> 2
/// // r == -8 // 0b11111000
///
/// let s = q >> 11
/// // s == -1 // 0b11111111
///
/// - Parameters:
/// - lhs: The value to shift.
/// - rhs: The number of bits to shift `lhs` to the right.
@_semantics("optimize.sil.specialize.generic.partial.never")
@_transparent
public static func >> <RHS: BinaryInteger>(lhs: Self, rhs: RHS) -> Self {
var r = lhs
r >>= rhs
return r
}
/// Returns the result of shifting a value's binary representation the
/// specified number of digits to the left.
///
/// The `<<` operator performs a *smart shift*, which defines a result for a
/// shift of any value.
///
/// - Using a negative value for `rhs` performs a right shift using
/// `abs(rhs)`.
/// - Using a value for `rhs` that is greater than or equal to the bit width
/// of `lhs` is an *overshift*, resulting in zero.
/// - Using any other value for `rhs` performs a left shift on `lhs` by that
/// amount.
///
/// The following example defines `x` as an instance of `UInt8`, an 8-bit,
/// unsigned integer type. If you use `2` as the right-hand-side value in an
/// operation on `x`, the value is shifted left by two bits.
///
/// let x: UInt8 = 30 // 0b00011110
/// let y = x << 2
/// // y == 120 // 0b01111000
///
/// If you use `11` as `rhs`, `x` is overshifted such that all of its bits
/// are set to zero.
///
/// let z = x << 11
/// // z == 0 // 0b00000000
///
/// Using a negative value as `rhs` is the same as performing a right shift
/// with `abs(rhs)`.
///
/// let a = x << -3
/// // a == 3 // 0b00000011
/// let b = x >> 3
/// // b == 3 // 0b00000011
///
/// - Parameters:
/// - lhs: The value to shift.
/// - rhs: The number of bits to shift `lhs` to the left.
@_semantics("optimize.sil.specialize.generic.partial.never")
@_transparent
public static func << <RHS: BinaryInteger>(lhs: Self, rhs: RHS) -> Self {
var r = lhs
r <<= rhs
return r
}
}
//===----------------------------------------------------------------------===//
//===--- CustomStringConvertible conformance ------------------------------===//
//===----------------------------------------------------------------------===//
extension BinaryInteger {
internal func _description(radix: Int, uppercase: Bool) -> String {
_precondition(2...36 ~= radix, "Radix must be between 2 and 36")
if bitWidth <= 64 {
let radix_ = Int64(radix)
return Self.isSigned
? _int64ToString(
Int64(truncatingIfNeeded: self), radix: radix_, uppercase: uppercase)
: _uint64ToString(
UInt64(truncatingIfNeeded: self), radix: radix_, uppercase: uppercase)
}
if self == (0 as Self) { return "0" }
// Bit shifting can be faster than division when `radix` is a power of two
// (although not necessarily the case for builtin types).
let isRadixPowerOfTwo = radix.nonzeroBitCount == 1
let radix_ = Magnitude(radix)
func _quotientAndRemainder(_ value: Magnitude) -> (Magnitude, Magnitude) {
return isRadixPowerOfTwo
? (value >> radix.trailingZeroBitCount, value & (radix_ - 1))
: value.quotientAndRemainder(dividingBy: radix_)
}
let hasLetters = radix > 10
func _ascii(_ digit: UInt8) -> UInt8 {
let base: UInt8
if !hasLetters || digit < 10 {
base = UInt8(("0" as Unicode.Scalar).value)
} else if uppercase {
base = UInt8(("A" as Unicode.Scalar).value) &- 10
} else {
base = UInt8(("a" as Unicode.Scalar).value) &- 10
}
return base &+ digit
}
let isNegative = Self.isSigned && self < (0 as Self)
var value = magnitude
// TODO(FIXME JIRA): All current stdlib types fit in small. Use a stack
// buffer instead of an array on the heap.
var result: [UInt8] = []
while value != 0 {
let (quotient, remainder) = _quotientAndRemainder(value)
result.append(_ascii(UInt8(truncatingIfNeeded: remainder)))
value = quotient
}
if isNegative {
result.append(UInt8(("-" as Unicode.Scalar).value))
}
result.reverse()
return result.withUnsafeBufferPointer {
return String._fromASCII($0)
}
}
/// A textual representation of this value.
@_semantics("binaryInteger.description")
public var description: String {
return _description(radix: 10, uppercase: false)
}
}
//===----------------------------------------------------------------------===//
//===--- Strideable conformance -------------------------------------------===//
//===----------------------------------------------------------------------===//
extension BinaryInteger {
/// Returns the distance from this value to the given value, expressed as a
/// stride.
///
/// For two values `x` and `y`, and a distance `n = x.distance(to: y)`,
/// `x.advanced(by: n) == y`.
///
/// - Parameter other: The value to calculate the distance to.
/// - Returns: The distance from this value to `other`.
@inlinable
@inline(__always)
public func distance(to other: Self) -> Int {
if !Self.isSigned {
if self > other {
if let result = Int(exactly: self - other) {
return -result
}
} else {
if let result = Int(exactly: other - self) {
return result
}
}
} else {
let isNegative = self < (0 as Self)
if isNegative == (other < (0 as Self)) {
if let result = Int(exactly: other - self) {
return result
}
} else {
if let result = Int(exactly: self.magnitude + other.magnitude) {
return isNegative ? result : -result
}
}
}
_preconditionFailure("Distance is not representable in Int")
}
/// Returns a value that is offset the specified distance from this value.
///
/// Use the `advanced(by:)` method in generic code to offset a value by a
/// specified distance. If you're working directly with numeric values, use
/// the addition operator (`+`) instead of this method.
///
/// For a value `x`, a distance `n`, and a value `y = x.advanced(by: n)`,
/// `x.distance(to: y) == n`.
///
/// - Parameter n: The distance to advance this value.
/// - Returns: A value that is offset from this value by `n`.
@inlinable
@inline(__always)
public func advanced(by n: Int) -> Self {
if !Self.isSigned {
return n < (0 as Int)
? self - Self(-n)
: self + Self(n)
}
if (self < (0 as Self)) == (n < (0 as Self)) {
return self + Self(n)
}
return self.magnitude < n.magnitude
? Self(Int(self) + n)
: self + Self(n)
}
}
//===----------------------------------------------------------------------===//
//===--- Heterogeneous comparison -----------------------------------------===//
//===----------------------------------------------------------------------===//
extension BinaryInteger {
/// Returns a Boolean value indicating whether the two given values are
/// equal.
///
/// You can check the equality of instances of any `BinaryInteger` types
/// using the equal-to operator (`==`). For example, you can test whether
/// the first `UInt8` value in a string's UTF-8 encoding is equal to the
/// first `UInt32` value in its Unicode scalar view:
///
/// let gameName = "Red Light, Green Light"
/// if let firstUTF8 = gameName.utf8.first,
/// let firstScalar = gameName.unicodeScalars.first?.value {
/// print("First code values are equal: \(firstUTF8 == firstScalar)")
/// }
/// // Prints "First code values are equal: true"
///
/// - Parameters:
/// - lhs: An integer to compare.
/// - rhs: Another integer to compare.
@_transparent
public static func == <
Other: BinaryInteger
>(lhs: Self, rhs: Other) -> Bool {
let lhsNegative = Self.isSigned && lhs < (0 as Self)
let rhsNegative = Other.isSigned && rhs < (0 as Other)
if lhsNegative != rhsNegative { return false }
// Here we know the values are of the same sign.
//
// There are a few possible scenarios from here:
//
// 1. Both values are negative
// - If one value is strictly wider than the other, then it is safe to
// convert to the wider type.
// - If the values are of the same width, it does not matter which type we
// choose to convert to as the values are already negative, and thus
// include the sign bit if two's complement representation already.
// 2. Both values are non-negative
// - If one value is strictly wider than the other, then it is safe to
// convert to the wider type.
// - If the values are of the same width, than signedness matters, as not
// unsigned types are 'wider' in a sense they don't need to 'waste' the
// sign bit. Therefore it is safe to convert to the unsigned type.
if lhs.bitWidth < rhs.bitWidth {
return Other(truncatingIfNeeded: lhs) == rhs
}
if lhs.bitWidth > rhs.bitWidth {
return lhs == Self(truncatingIfNeeded: rhs)
}
if Self.isSigned {
return Other(truncatingIfNeeded: lhs) == rhs
}
return lhs == Self(truncatingIfNeeded: rhs)
}
/// Returns a Boolean value indicating whether the two given values are not
/// equal.
///
/// You can check the inequality of instances of any `BinaryInteger` types
/// using the not-equal-to operator (`!=`). For example, you can test
/// whether the first `UInt8` value in a string's UTF-8 encoding is not
/// equal to the first `UInt32` value in its Unicode scalar view:
///
/// let gameName = "Red Light, Green Light"
/// if let firstUTF8 = gameName.utf8.first,
/// let firstScalar = gameName.unicodeScalars.first?.value {
/// print("First code values are different: \(firstUTF8 != firstScalar)")
/// }
/// // Prints "First code values are different: false"
///
/// - Parameters:
/// - lhs: An integer to compare.
/// - rhs: Another integer to compare.
@_transparent
public static func != <
Other: BinaryInteger
>(lhs: Self, rhs: Other) -> Bool {
return !(lhs == rhs)
}
/// Returns a Boolean value indicating whether the value of the first
/// argument is less than that of the second argument.
///
/// You can compare instances of any `BinaryInteger` types using the
/// less-than operator (`<`), even if the two instances are of different
/// types.
///
/// - Parameters:
/// - lhs: An integer to compare.
/// - rhs: Another integer to compare.
@_transparent
public static func < <Other: BinaryInteger>(lhs: Self, rhs: Other) -> Bool {
let lhsNegative = Self.isSigned && lhs < (0 as Self)
let rhsNegative = Other.isSigned && rhs < (0 as Other)
if lhsNegative != rhsNegative { return lhsNegative }
if lhs == (0 as Self) && rhs == (0 as Other) { return false }
// if we get here, lhs and rhs have the same sign. If they're negative,
// then Self and Other are both signed types, and one of them can represent
// values of the other type. Otherwise, lhs and rhs are positive, and one
// of Self, Other may be signed and the other unsigned.
let rhsAsSelf = Self(truncatingIfNeeded: rhs)
let rhsAsSelfNegative = rhsAsSelf < (0 as Self)
// Can we round-trip rhs through Other?
if Other(truncatingIfNeeded: rhsAsSelf) == rhs &&
// This additional check covers the `Int8.max < (128 as UInt8)` case.
// Since the types are of the same width, init(truncatingIfNeeded:)
// will result in a simple bitcast, so that rhsAsSelf would be -128, and
// `lhs < rhsAsSelf` will return false.
// We basically guard against that bitcast by requiring rhs and rhsAsSelf
// to be the same sign.
rhsNegative == rhsAsSelfNegative {
return lhs < rhsAsSelf
}
return Other(truncatingIfNeeded: lhs) < rhs
}
/// Returns a Boolean value indicating whether the value of the first
/// argument is less than or equal to that of the second argument.
///
/// You can compare instances of any `BinaryInteger` types using the
/// less-than-or-equal-to operator (`<=`), even if the two instances are of
/// different types.
///
/// - Parameters:
/// - lhs: An integer to compare.
/// - rhs: Another integer to compare.
@_transparent
public static func <= <Other: BinaryInteger>(lhs: Self, rhs: Other) -> Bool {
return !(rhs < lhs)
}
/// Returns a Boolean value indicating whether the value of the first
/// argument is greater than or equal to that of the second argument.
///
/// You can compare instances of any `BinaryInteger` types using the
/// greater-than-or-equal-to operator (`>=`), even if the two instances are
/// of different types.
///
/// - Parameters:
/// - lhs: An integer to compare.
/// - rhs: Another integer to compare.
@_transparent
public static func >= <Other: BinaryInteger>(lhs: Self, rhs: Other) -> Bool {
return !(lhs < rhs)
}
/// Returns a Boolean value indicating whether the value of the first
/// argument is greater than that of the second argument.
///
/// You can compare instances of any `BinaryInteger` types using the
/// greater-than operator (`>`), even if the two instances are of different
/// types.
///
/// - Parameters:
/// - lhs: An integer to compare.
/// - rhs: Another integer to compare.
@_transparent
public static func > <Other: BinaryInteger>(lhs: Self, rhs: Other) -> Bool {
return rhs < lhs
}
}
//===----------------------------------------------------------------------===//
//===--- Ambiguity breakers -----------------------------------------------===//
//
// These two versions of the operators are not ordered with respect to one
// another, but the compiler choses the second one, and that results in infinite
// recursion.
//
// <T: Comparable>(T, T) -> Bool
// <T: BinaryInteger, U: BinaryInteger>(T, U) -> Bool
//
// so we define:
//
// <T: BinaryInteger>(T, T) -> Bool
//
//===----------------------------------------------------------------------===//
extension BinaryInteger {
@_transparent
public static func != (lhs: Self, rhs: Self) -> Bool {
return !(lhs == rhs)
}
@_transparent
public static func <= (lhs: Self, rhs: Self) -> Bool {
return !(rhs < lhs)
}
@_transparent
public static func >= (lhs: Self, rhs: Self) -> Bool {
return !(lhs < rhs)
}
@_transparent
public static func > (lhs: Self, rhs: Self) -> Bool {
return rhs < lhs
}
}
//===----------------------------------------------------------------------===//
//===--- FixedWidthInteger ------------------------------------------------===//
//===----------------------------------------------------------------------===//
/// An integer type that uses a fixed size for every instance.
///
/// The `FixedWidthInteger` protocol adds binary bitwise operations, bit
/// shifts, and overflow handling to the operations supported by the
/// `BinaryInteger` protocol.
///
/// Use the `FixedWidthInteger` protocol as a constraint or extension point
/// when writing operations that depend on bit shifting, performing bitwise
/// operations, catching overflows, or having access to the maximum or minimum
/// representable value of a type. For example, the following code provides a
/// `binaryString` property on every fixed-width integer that represents the
/// number's binary representation, split into 8-bit chunks.
///
/// extension FixedWidthInteger {
/// var binaryString: String {
/// var result: [String] = []
/// for i in 0..<(Self.bitWidth / 8) {
/// let byte = UInt8(truncatingIfNeeded: self >> (i * 8))
/// let byteString = String(byte, radix: 2)
/// let padding = String(repeating: "0",
/// count: 8 - byteString.count)
/// result.append(padding + byteString)
/// }
/// return "0b" + result.reversed().joined(separator: "_")
/// }
/// }
///
/// print(Int16.max.binaryString)
/// // Prints "0b01111111_11111111"
/// print((101 as UInt8).binaryString)
/// // Prints "0b01100101"
///
/// The `binaryString` implementation uses the static `bitWidth` property and
/// the right shift operator (`>>`), both of which are available to any type
/// that conforms to the `FixedWidthInteger` protocol.
///
/// The next example declares a generic `squared` function, which accepts an
/// instance `x` of any fixed-width integer type. The function uses the
/// `multipliedReportingOverflow(by:)` method to multiply `x` by itself and
/// check whether the result is too large to represent in the same type.
///
/// func squared<T: FixedWidthInteger>(_ x: T) -> T? {
/// let (result, overflow) = x.multipliedReportingOverflow(by: x)
/// if overflow {
/// return nil
/// }
/// return result
/// }
///
/// let (x, y): (Int8, Int8) = (9, 123)
/// print(squared(x))
/// // Prints "Optional(81)"
/// print(squared(y))
/// // Prints "nil"
///
/// Conforming to the FixedWidthInteger Protocol
/// ============================================
///
/// To make your own custom type conform to the `FixedWidthInteger` protocol,
/// declare the required initializers, properties, and methods. The required
/// methods that are suffixed with `ReportingOverflow` serve as the
/// customization points for arithmetic operations. When you provide just those
/// methods, the standard library provides default implementations for all
/// other arithmetic methods and operators.
public protocol FixedWidthInteger: BinaryInteger, LosslessStringConvertible
where Magnitude: FixedWidthInteger & UnsignedInteger,
Stride: FixedWidthInteger & SignedInteger {
/// The number of bits used for the underlying binary representation of
/// values of this type.
///
/// An unsigned, fixed-width integer type can represent values from 0 through
/// `(2 ** bitWidth) - 1`, where `**` is exponentiation. A signed,
/// fixed-width integer type can represent values from
/// `-(2 ** (bitWidth - 1))` through `(2 ** (bitWidth - 1)) - 1`. For example,
/// the `Int8` type has a `bitWidth` value of 8 and can store any integer in
/// the range `-128...127`.
static var bitWidth: Int { get }
/// The maximum representable integer in this type.
///
/// For unsigned integer types, this value is `(2 ** bitWidth) - 1`, where
/// `**` is exponentiation. For signed integer types, this value is
/// `(2 ** (bitWidth - 1)) - 1`.
static var max: Self { get }
/// The minimum representable integer in this type.
///
/// For unsigned integer types, this value is always `0`. For signed integer
/// types, this value is `-(2 ** (bitWidth - 1))`, where `**` is
/// exponentiation.
static var min: Self { get }
/// Returns the sum of this value and the given value, along with a Boolean
/// value indicating whether overflow occurred in the operation.
///
/// - Parameter rhs: The value to add to this value.
/// - Returns: A tuple containing the result of the addition along with a
/// Boolean value indicating whether overflow occurred. If the `overflow`
/// component is `false`, the `partialValue` component contains the entire
/// sum. If the `overflow` component is `true`, an overflow occurred and
/// the `partialValue` component contains the truncated sum of this value
/// and `rhs`.
func addingReportingOverflow(
_ rhs: Self
) -> (partialValue: Self, overflow: Bool)
/// Returns the difference obtained by subtracting the given value from this
/// value, along with a Boolean value indicating whether overflow occurred in
/// the operation.
///
/// - Parameter rhs: The value to subtract from this value.
/// - Returns: A tuple containing the result of the subtraction along with a
/// Boolean value indicating whether overflow occurred. If the `overflow`
/// component is `false`, the `partialValue` component contains the entire
/// difference. If the `overflow` component is `true`, an overflow occurred
/// and the `partialValue` component contains the truncated result of `rhs`
/// subtracted from this value.
func subtractingReportingOverflow(
_ rhs: Self
) -> (partialValue: Self, overflow: Bool)
/// Returns the product of this value and the given value, along with a
/// Boolean value indicating whether overflow occurred in the operation.
///
/// - Parameter rhs: The value to multiply by this value.
/// - Returns: A tuple containing the result of the multiplication along with
/// a Boolean value indicating whether overflow occurred. If the `overflow`
/// component is `false`, the `partialValue` component contains the entire
/// product. If the `overflow` component is `true`, an overflow occurred and
/// the `partialValue` component contains the truncated product of this
/// value and `rhs`.
func multipliedReportingOverflow(
by rhs: Self
) -> (partialValue: Self, overflow: Bool)
/// Returns the quotient obtained by dividing this value by the given value,
/// along with a Boolean value indicating whether overflow occurred in the
/// operation.
///
/// Dividing by zero is not an error when using this method. For a value `x`,
/// the result of `x.dividedReportingOverflow(by: 0)` is `(x, true)`.
///
/// - Parameter rhs: The value to divide this value by.
/// - Returns: A tuple containing the result of the division along with a
/// Boolean value indicating whether overflow occurred. If the `overflow`
/// component is `false`, the `partialValue` component contains the entire
/// quotient. If the `overflow` component is `true`, an overflow occurred
/// and the `partialValue` component contains either the truncated quotient
/// or, if the quotient is undefined, the dividend.
func dividedReportingOverflow(
by rhs: Self
) -> (partialValue: Self, overflow: Bool)
/// Returns the remainder after dividing this value by the given value, along
/// with a Boolean value indicating whether overflow occurred during division.
///
/// Dividing by zero is not an error when using this method. For a value `x`,
/// the result of `x.remainderReportingOverflow(dividingBy: 0)` is
/// `(x, true)`.
///
/// - Parameter rhs: The value to divide this value by.
/// - Returns: A tuple containing the result of the operation along with a
/// Boolean value indicating whether overflow occurred. If the `overflow`
/// component is `false`, the `partialValue` component contains the entire
/// remainder. If the `overflow` component is `true`, an overflow occurred
/// during division and the `partialValue` component contains either the
/// entire remainder or, if the remainder is undefined, the dividend.
func remainderReportingOverflow(
dividingBy rhs: Self
) -> (partialValue: Self, overflow: Bool)
/// Returns a tuple containing the high and low parts of the result of
/// multiplying this value by the given value.
///
/// Use this method to calculate the full result of a product that would
/// otherwise overflow. Unlike traditional truncating multiplication, the
/// `multipliedFullWidth(by:)` method returns a tuple containing both the
/// `high` and `low` parts of the product of this value and `other`. The
/// following example uses this method to multiply two `Int8` values that
/// normally overflow when multiplied:
///
/// let x: Int8 = 48
/// let y: Int8 = -40
/// let result = x.multipliedFullWidth(by: y)
/// // result.high == -8
/// // result.low == 128
///
/// The product of `x` and `y` is `-1920`, which is too large to represent in
/// an `Int8` instance. The `high` and `low` components of the `result` value
/// represent `-1920` when concatenated to form a double-width integer; that
/// is, using `result.high` as the high byte and `result.low` as the low byte
/// of an `Int16` instance.
///
/// let z = Int16(result.high) << 8 | Int16(result.low)
/// // z == -1920
///
/// - Parameter other: The value to multiply this value by.
/// - Returns: A tuple containing the high and low parts of the result of
/// multiplying this value and `other`.
func multipliedFullWidth(by other: Self) -> (high: Self, low: Self.Magnitude)
/// Returns a tuple containing the quotient and remainder obtained by dividing
/// the given value by this value.
///
/// The resulting quotient must be representable within the bounds of the
/// type. If the quotient is too large to represent in the type, a runtime
/// error may occur.
///
/// The following example divides a value that is too large to be represented
/// using a single `Int` instance by another `Int` value. Because the quotient
/// is representable as an `Int`, the division succeeds.
///
/// // 'dividend' represents the value 0x506f70652053616e74612049494949
/// let dividend = (22640526660490081, 7959093232766896457 as UInt)
/// let divisor = 2241543570477705381
///
/// let (quotient, remainder) = divisor.dividingFullWidth(dividend)
/// // quotient == 186319822866995413
/// // remainder == 0
///
/// - Parameter dividend: A tuple containing the high and low parts of a
/// double-width integer.
/// - Returns: A tuple containing the quotient and remainder obtained by
/// dividing `dividend` by this value.
func dividingFullWidth(_ dividend: (high: Self, low: Self.Magnitude))
-> (quotient: Self, remainder: Self)
init(_truncatingBits bits: UInt)
/// The number of bits equal to 1 in this value's binary representation.
///
/// For example, in a fixed-width integer type with a `bitWidth` value of 8,
/// the number *31* has five bits equal to *1*.
///
/// let x: Int8 = 0b0001_1111
/// // x == 31
/// // x.nonzeroBitCount == 5
var nonzeroBitCount: Int { get }
/// The number of leading zeros in this value's binary representation.
///
/// For example, in a fixed-width integer type with a `bitWidth` value of 8,
/// the number *31* has three leading zeros.
///
/// let x: Int8 = 0b0001_1111
/// // x == 31
/// // x.leadingZeroBitCount == 3
///
/// If the value is zero, then `leadingZeroBitCount` is equal to `bitWidth`.
var leadingZeroBitCount: Int { get }
/// Creates an integer from its big-endian representation, changing the byte
/// order if necessary.
///
/// - Parameter value: A value to use as the big-endian representation of the
/// new integer.
init(bigEndian value: Self)
/// Creates an integer from its little-endian representation, changing the
/// byte order if necessary.
///
/// - Parameter value: A value to use as the little-endian representation of
/// the new integer.
init(littleEndian value: Self)
/// The big-endian representation of this integer.
///
/// If necessary, the byte order of this value is reversed from the typical
/// byte order of this integer type. On a big-endian platform, for any
/// integer `x`, `x == x.bigEndian`.
var bigEndian: Self { get }
/// The little-endian representation of this integer.
///
/// If necessary, the byte order of this value is reversed from the typical
/// byte order of this integer type. On a little-endian platform, for any
/// integer `x`, `x == x.littleEndian`.
var littleEndian: Self { get }
/// A representation of this integer with the byte order swapped.
var byteSwapped: Self { get }
/// Returns the result of shifting a value's binary representation the
/// specified number of digits to the right, masking the shift amount to the
/// type's bit width.
///
/// Use the masking right shift operator (`&>>`) when you need to perform a
/// shift and are sure that the shift amount is in the range
/// `0..<lhs.bitWidth`. Before shifting, the masking right shift operator
/// masks the shift to this range. The shift is performed using this masked
/// value.
///
/// The following example defines `x` as an instance of `UInt8`, an 8-bit,
/// unsigned integer type. If you use `2` as the right-hand-side value in an
/// operation on `x`, the shift amount requires no masking.
///
/// let x: UInt8 = 30 // 0b00011110
/// let y = x &>> 2
/// // y == 7 // 0b00000111
///
/// However, if you use `8` as the shift amount, the method first masks the
/// shift amount to zero, and then performs the shift, resulting in no change
/// to the original value.
///
/// let z = x &>> 8
/// // z == 30 // 0b00011110
///
/// If the bit width of the shifted integer type is a power of two, masking
/// is performed using a bitmask; otherwise, masking is performed using a
/// modulo operation.
///
/// - Parameters:
/// - lhs: The value to shift.
/// - rhs: The number of bits to shift `lhs` to the right. If `rhs` is
/// outside the range `0..<lhs.bitWidth`, it is masked to produce a
/// value within that range.
static func &>>(lhs: Self, rhs: Self) -> Self
/// Calculates the result of shifting a value's binary representation the
/// specified number of digits to the right, masking the shift amount to the
/// type's bit width, and stores the result in the left-hand-side variable.
///
/// The `&>>=` operator performs a *masking shift*, where the value passed as
/// `rhs` is masked to produce a value in the range `0..<lhs.bitWidth`. The
/// shift is performed using this masked value.
///
/// The following example defines `x` as an instance of `UInt8`, an 8-bit,
/// unsigned integer type. If you use `2` as the right-hand-side value in an
/// operation on `x`, the shift amount requires no masking.
///
/// var x: UInt8 = 30 // 0b00011110
/// x &>>= 2
/// // x == 7 // 0b00000111
///
/// However, if you use `19` as `rhs`, the operation first bitmasks `rhs` to
/// `3`, and then uses that masked value as the number of bits to shift `lhs`.
///
/// var y: UInt8 = 30 // 0b00011110
/// y &>>= 19
/// // y == 3 // 0b00000011
///
/// - Parameters:
/// - lhs: The value to shift.
/// - rhs: The number of bits to shift `lhs` to the right. If `rhs` is
/// outside the range `0..<lhs.bitWidth`, it is masked to produce a
/// value within that range.
static func &>>=(lhs: inout Self, rhs: Self)
/// Returns the result of shifting a value's binary representation the
/// specified number of digits to the left, masking the shift amount to the
/// type's bit width.
///
/// Use the masking left shift operator (`&<<`) when you need to perform a
/// shift and are sure that the shift amount is in the range
/// `0..<lhs.bitWidth`. Before shifting, the masking left shift operator
/// masks the shift to this range. The shift is performed using this masked
/// value.
///
/// The following example defines `x` as an instance of `UInt8`, an 8-bit,
/// unsigned integer type. If you use `2` as the right-hand-side value in an
/// operation on `x`, the shift amount requires no masking.
///
/// let x: UInt8 = 30 // 0b00011110
/// let y = x &<< 2
/// // y == 120 // 0b01111000
///
/// However, if you use `8` as the shift amount, the method first masks the
/// shift amount to zero, and then performs the shift, resulting in no change
/// to the original value.
///
/// let z = x &<< 8
/// // z == 30 // 0b00011110
///
/// If the bit width of the shifted integer type is a power of two, masking
/// is performed using a bitmask; otherwise, masking is performed using a
/// modulo operation.
///
/// - Parameters:
/// - lhs: The value to shift.
/// - rhs: The number of bits to shift `lhs` to the left. If `rhs` is
/// outside the range `0..<lhs.bitWidth`, it is masked to produce a
/// value within that range.
static func &<<(lhs: Self, rhs: Self) -> Self
/// Returns the result of shifting a value's binary representation the
/// specified number of digits to the left, masking the shift amount to the
/// type's bit width, and stores the result in the left-hand-side variable.
///
/// The `&<<=` operator performs a *masking shift*, where the value used as
/// `rhs` is masked to produce a value in the range `0..<lhs.bitWidth`. The
/// shift is performed using this masked value.
///
/// The following example defines `x` as an instance of `UInt8`, an 8-bit,
/// unsigned integer type. If you use `2` as the right-hand-side value in an
/// operation on `x`, the shift amount requires no masking.
///
/// var x: UInt8 = 30 // 0b00011110
/// x &<<= 2
/// // x == 120 // 0b01111000
///
/// However, if you pass `19` as `rhs`, the method first bitmasks `rhs` to
/// `3`, and then uses that masked value as the number of bits to shift `lhs`.
///
/// var y: UInt8 = 30 // 0b00011110
/// y &<<= 19
/// // y == 240 // 0b11110000
///
/// - Parameters:
/// - lhs: The value to shift.
/// - rhs: The number of bits to shift `lhs` to the left. If `rhs` is
/// outside the range `0..<lhs.bitWidth`, it is masked to produce a
/// value within that range.
static func &<<=(lhs: inout Self, rhs: Self)
}
extension FixedWidthInteger {
/// The number of bits in the binary representation of this value.
@inlinable
public var bitWidth: Int { return Self.bitWidth }
@inlinable
public func _binaryLogarithm() -> Int {
_precondition(self > (0 as Self))
return Self.bitWidth &- (leadingZeroBitCount &+ 1)
}
/// Creates an integer from its little-endian representation, changing the
/// byte order if necessary.
///
/// - Parameter value: A value to use as the little-endian representation of
/// the new integer.
@inlinable
public init(littleEndian value: Self) {
#if _endian(little)
self = value
#else
self = value.byteSwapped
#endif
}
/// Creates an integer from its big-endian representation, changing the byte
/// order if necessary.
///
/// - Parameter value: A value to use as the big-endian representation of the
/// new integer.
@inlinable
public init(bigEndian value: Self) {
#if _endian(big)
self = value
#else
self = value.byteSwapped
#endif
}
/// The little-endian representation of this integer.
///
/// If necessary, the byte order of this value is reversed from the typical
/// byte order of this integer type. On a little-endian platform, for any
/// integer `x`, `x == x.littleEndian`.
@inlinable
public var littleEndian: Self {
#if _endian(little)
return self
#else
return byteSwapped
#endif
}
/// The big-endian representation of this integer.
///
/// If necessary, the byte order of this value is reversed from the typical
/// byte order of this integer type. On a big-endian platform, for any
/// integer `x`, `x == x.bigEndian`.
@inlinable
public var bigEndian: Self {
#if _endian(big)
return self
#else
return byteSwapped
#endif
}
// Default implementation of multipliedFullWidth.
//
// This implementation is mainly intended for [U]Int64 on 32b platforms. It
// will not be especially efficient for other types that do not provide their
// own implementation, but neither will it be catastrophically bad. It can
// surely be improved on even for Int64, but that is mostly an optimization
// problem; the basic algorithm here gives the compiler all the information
// that it needs to generate efficient code.
@_alwaysEmitIntoClient
public func multipliedFullWidth(by other: Self) -> (high: Self, low: Magnitude) {
// We define a utility function for splitting an integer into high and low
// halves. Note that the low part is always unsigned, while the high part
// matches the signedness of the input type. Both result types are the
// full width of the original number; this may be surprising at first, but
// there are two reasons for it:
//
// - we're going to use these as inputs to a multiplication operation, and
// &* is quite a bit less verbose than `multipliedFullWidth`, so it makes
// the rest of the code in this function somewhat easier to read.
//
// - there's no "half width type" that we can get at from this generic
// context, so there's not really another option anyway.
//
// Fortunately, the compiler is pretty good about propagating the necessary
// information to optimize away unnecessary arithmetic.
func split<T: FixedWidthInteger>(_ x: T) -> (high: T, low: T.Magnitude) {
let n = T.bitWidth/2
return (x >> n, T.Magnitude(truncatingIfNeeded: x) & ((1 &<< n) &- 1))
}
// Split `self` and `other` into high and low parts, compute the partial
// products carrying high words in as we go. We use the wrapping operators
// and `truncatingIfNeeded` inits purely as an optimization hint to the
// compiler; none of these operations will ever wrap due to the constraints
// on the arithmetic. The bounds are documented before each line for signed
// types. For unsigned types, the bounds are much more well known and
// easier to derive, so I haven't bothered to document them here, but they
// all boil down to the fact that a*b + c + d cannot overflow a double-
// width result with unsigned a, b, c, d.
let (x1, x0) = split(self)
let (y1, y0) = split(other)
// If B is 2^bitWidth/2, x0 and y0 are in 0 ... B-1, so their product is
// in 0 ... B^2-2B+1. For further analysis, we'll need the fact that
// the high word is in 0 ... B-2.
let p00 = x0 &* y0
// x1 is in -B/2 ... B/2-1, so the product x1*y0 is in
// -(B^2-B)/2 ... (B^2-3B+2)/2; after adding the high word of p00, the
// result is in -(B^2-B)/2 ... (B^2-B-2)/2.
let p01 = x1 &* Self(y0) &+ Self(split(p00).high)
// The previous analysis holds for this product as well, and the sum is
// in -(B^2-B)/2 ... (B^2-B)/2.
let p10 = Self(x0) &* y1 &+ Self(split(p01).low)
// No analysis is necessary for this term, because we know the product as
// a whole cannot overflow, and this term is the final high word of the
// product.
let p11 = x1 &* y1 &+ split(p01).high &+ split(p10).high
// Now we only need to assemble the low word of the product.
return (p11, split(p10).low << (bitWidth/2) | split(p00).low)
}
/// Returns the result of shifting a value's binary representation the
/// specified number of digits to the right, masking the shift amount to the
/// type's bit width.
///
/// Use the masking right shift operator (`&>>`) when you need to perform a
/// shift and are sure that the shift amount is in the range
/// `0..<lhs.bitWidth`. Before shifting, the masking right shift operator
/// masks the shift to this range. The shift is performed using this masked
/// value.
///
/// The following example defines `x` as an instance of `UInt8`, an 8-bit,
/// unsigned integer type. If you use `2` as the right-hand-side value in an
/// operation on `x`, the shift amount requires no masking.
///
/// let x: UInt8 = 30 // 0b00011110
/// let y = x &>> 2
/// // y == 7 // 0b00000111
///
/// However, if you use `8` as the shift amount, the method first masks the
/// shift amount to zero, and then performs the shift, resulting in no change
/// to the original value.
///
/// let z = x &>> 8
/// // z == 30 // 0b00011110
///
/// If the bit width of the shifted integer type is a power of two, masking
/// is performed using a bitmask; otherwise, masking is performed using a
/// modulo operation.
///
/// - Parameters:
/// - lhs: The value to shift.
/// - rhs: The number of bits to shift `lhs` to the right. If `rhs` is
/// outside the range `0..<lhs.bitWidth`, it is masked to produce a
/// value within that range.
@_semantics("optimize.sil.specialize.generic.partial.never")
@_transparent
public static func &>> (lhs: Self, rhs: Self) -> Self {
var lhs = lhs
lhs &>>= rhs
return lhs
}
/// Returns the result of shifting a value's binary representation the
/// specified number of digits to the right, masking the shift amount to the
/// type's bit width.
///
/// Use the masking right shift operator (`&>>`) when you need to perform a
/// shift and are sure that the shift amount is in the range
/// `0..<lhs.bitWidth`. Before shifting, the masking right shift operator
/// masks the shift to this range. The shift is performed using this masked
/// value.
///
/// The following example defines `x` as an instance of `UInt8`, an 8-bit,
/// unsigned integer type. If you use `2` as the right-hand-side value in an
/// operation on `x`, the shift amount requires no masking.
///
/// let x: UInt8 = 30 // 0b00011110
/// let y = x &>> 2
/// // y == 7 // 0b00000111
///
/// However, if you use `8` as the shift amount, the method first masks the
/// shift amount to zero, and then performs the shift, resulting in no change
/// to the original value.
///
/// let z = x &>> 8
/// // z == 30 // 0b00011110
///
/// If the bit width of the shifted integer type is a power of two, masking
/// is performed using a bitmask; otherwise, masking is performed using a
/// modulo operation.
///
/// - Parameters:
/// - lhs: The value to shift.
/// - rhs: The number of bits to shift `lhs` to the right. If `rhs` is
/// outside the range `0..<lhs.bitWidth`, it is masked to produce a
/// value within that range.
@_semantics("optimize.sil.specialize.generic.partial.never")
@_transparent
public static func &>> <
Other: BinaryInteger
>(lhs: Self, rhs: Other) -> Self {
return lhs &>> Self(truncatingIfNeeded: rhs)
}
/// Calculates the result of shifting a value's binary representation the
/// specified number of digits to the right, masking the shift amount to the
/// type's bit width, and stores the result in the left-hand-side variable.
///
/// The `&>>=` operator performs a *masking shift*, where the value passed as
/// `rhs` is masked to produce a value in the range `0..<lhs.bitWidth`. The
/// shift is performed using this masked value.
///
/// The following example defines `x` as an instance of `UInt8`, an 8-bit,
/// unsigned integer type. If you use `2` as the right-hand-side value in an
/// operation on `x`, the shift amount requires no masking.
///
/// var x: UInt8 = 30 // 0b00011110
/// x &>>= 2
/// // x == 7 // 0b00000111
///
/// However, if you use `19` as `rhs`, the operation first bitmasks `rhs` to
/// `3`, and then uses that masked value as the number of bits to shift `lhs`.
///
/// var y: UInt8 = 30 // 0b00011110
/// y &>>= 19
/// // y == 3 // 0b00000011
///
/// - Parameters:
/// - lhs: The value to shift.
/// - rhs: The number of bits to shift `lhs` to the right. If `rhs` is
/// outside the range `0..<lhs.bitWidth`, it is masked to produce a
/// value within that range.
@_semantics("optimize.sil.specialize.generic.partial.never")
@_transparent
public static func &>>= <
Other: BinaryInteger
>(lhs: inout Self, rhs: Other) {
lhs = lhs &>> rhs
}
/// Returns the result of shifting a value's binary representation the
/// specified number of digits to the left, masking the shift amount to the
/// type's bit width.
///
/// Use the masking left shift operator (`&<<`) when you need to perform a
/// shift and are sure that the shift amount is in the range
/// `0..<lhs.bitWidth`. Before shifting, the masking left shift operator
/// masks the shift to this range. The shift is performed using this masked
/// value.
///
/// The following example defines `x` as an instance of `UInt8`, an 8-bit,
/// unsigned integer type. If you use `2` as the right-hand-side value in an
/// operation on `x`, the shift amount requires no masking.
///
/// let x: UInt8 = 30 // 0b00011110
/// let y = x &<< 2
/// // y == 120 // 0b01111000
///
/// However, if you use `8` as the shift amount, the method first masks the
/// shift amount to zero, and then performs the shift, resulting in no change
/// to the original value.
///
/// let z = x &<< 8
/// // z == 30 // 0b00011110
///
/// If the bit width of the shifted integer type is a power of two, masking
/// is performed using a bitmask; otherwise, masking is performed using a
/// modulo operation.
///
/// - Parameters:
/// - lhs: The value to shift.
/// - rhs: The number of bits to shift `lhs` to the left. If `rhs` is
/// outside the range `0..<lhs.bitWidth`, it is masked to produce a
/// value within that range.
@_semantics("optimize.sil.specialize.generic.partial.never")
@_transparent
public static func &<< (lhs: Self, rhs: Self) -> Self {
var lhs = lhs
lhs &<<= rhs
return lhs
}
/// Returns the result of shifting a value's binary representation the
/// specified number of digits to the left, masking the shift amount to the
/// type's bit width.
///
/// Use the masking left shift operator (`&<<`) when you need to perform a
/// shift and are sure that the shift amount is in the range
/// `0..<lhs.bitWidth`. Before shifting, the masking left shift operator
/// masks the shift to this range. The shift is performed using this masked
/// value.
///
/// The following example defines `x` as an instance of `UInt8`, an 8-bit,
/// unsigned integer type. If you use `2` as the right-hand-side value in an
/// operation on `x`, the shift amount requires no masking.
///
/// let x: UInt8 = 30 // 0b00011110
/// let y = x &<< 2
/// // y == 120 // 0b01111000
///
/// However, if you use `8` as the shift amount, the method first masks the
/// shift amount to zero, and then performs the shift, resulting in no change
/// to the original value.
///
/// let z = x &<< 8
/// // z == 30 // 0b00011110
///
/// If the bit width of the shifted integer type is a power of two, masking
/// is performed using a bitmask; otherwise, masking is performed using a
/// modulo operation.
///
/// - Parameters:
/// - lhs: The value to shift.
/// - rhs: The number of bits to shift `lhs` to the left. If `rhs` is
/// outside the range `0..<lhs.bitWidth`, it is masked to produce a
/// value within that range.
@_semantics("optimize.sil.specialize.generic.partial.never")
@_transparent
public static func &<< <
Other: BinaryInteger
>(lhs: Self, rhs: Other) -> Self {
return lhs &<< Self(truncatingIfNeeded: rhs)
}
/// Returns the result of shifting a value's binary representation the
/// specified number of digits to the left, masking the shift amount to the
/// type's bit width, and stores the result in the left-hand-side variable.
///
/// The `&<<=` operator performs a *masking shift*, where the value used as
/// `rhs` is masked to produce a value in the range `0..<lhs.bitWidth`. The
/// shift is performed using this masked value.
///
/// The following example defines `x` as an instance of `UInt8`, an 8-bit,
/// unsigned integer type. If you use `2` as the right-hand-side value in an
/// operation on `x`, the shift amount requires no masking.
///
/// var x: UInt8 = 30 // 0b00011110
/// x &<<= 2
/// // x == 120 // 0b01111000
///
/// However, if you pass `19` as `rhs`, the method first bitmasks `rhs` to
/// `3`, and then uses that masked value as the number of bits to shift `lhs`.
///
/// var y: UInt8 = 30 // 0b00011110
/// y &<<= 19
/// // y == 240 // 0b11110000
///
/// - Parameters:
/// - lhs: The value to shift.
/// - rhs: The number of bits to shift `lhs` to the left. If `rhs` is
/// outside the range `0..<lhs.bitWidth`, it is masked to produce a
/// value within that range.
@_semantics("optimize.sil.specialize.generic.partial.never")
@_transparent
public static func &<<= <
Other: BinaryInteger
>(lhs: inout Self, rhs: Other) {
lhs = lhs &<< rhs
}
}
extension FixedWidthInteger {
/// Returns a random value within the specified range, using the given
/// generator as a source for randomness.
///
/// Use this method to generate an integer within a specific range when you
/// are using a custom random number generator. This example creates three
/// new values in the range `1..<100`.
///
/// for _ in 1...3 {
/// print(Int.random(in: 1..<100, using: &myGenerator))
/// }
/// // Prints "7"
/// // Prints "44"
/// // Prints "21"
///
/// - Note: The algorithm used to create random values may change in a future
/// version of Swift. If you're passing a generator that results in the
/// same sequence of integer values each time you run your program, that
/// sequence may change when your program is compiled using a different
/// version of Swift.
///
/// - Parameters:
/// - range: The range in which to create a random value.
/// `range` must not be empty.
/// - generator: The random number generator to use when creating the
/// new random value.
/// - Returns: A random value within the bounds of `range`.
@inlinable
public static func random<T: RandomNumberGenerator>(
in range: Range<Self>,
using generator: inout T
) -> Self {
_precondition(
!range.isEmpty,
"Can't get random value with an empty range"
)
// Compute delta, the distance between the lower and upper bounds. This
// value may not representable by the type Bound if Bound is signed, but
// is always representable as Bound.Magnitude.
let delta = Magnitude(truncatingIfNeeded: range.upperBound &- range.lowerBound)
// The mathematical result we want is lowerBound plus a random value in
// 0 ..< delta. We need to be slightly careful about how we do this
// arithmetic; the Bound type cannot generally represent the random value,
// so we use a wrapping addition on Bound.Magnitude. This will often
// overflow, but produces the correct bit pattern for the result when
// converted back to Bound.
return Self(truncatingIfNeeded:
Magnitude(truncatingIfNeeded: range.lowerBound) &+
generator.next(upperBound: delta)
)
}
/// Returns a random value within the specified range.
///
/// Use this method to generate an integer within a specific range. This
/// example creates three new values in the range `1..<100`.
///
/// for _ in 1...3 {
/// print(Int.random(in: 1..<100))
/// }
/// // Prints "53"
/// // Prints "64"
/// // Prints "5"
///
/// This method is equivalent to calling the version that takes a generator,
/// passing in the system's default random generator.
///
/// - Parameter range: The range in which to create a random value.
/// `range` must not be empty.
/// - Returns: A random value within the bounds of `range`.
@inlinable
public static func random(in range: Range<Self>) -> Self {
var g = SystemRandomNumberGenerator()
return Self.random(in: range, using: &g)
}
/// Returns a random value within the specified range, using the given
/// generator as a source for randomness.
///
/// Use this method to generate an integer within a specific range when you
/// are using a custom random number generator. This example creates three
/// new values in the range `1...100`.
///
/// for _ in 1...3 {
/// print(Int.random(in: 1...100, using: &myGenerator))
/// }
/// // Prints "7"
/// // Prints "44"
/// // Prints "21"
///
/// - Parameters:
/// - range: The range in which to create a random value.
/// - generator: The random number generator to use when creating the
/// new random value.
/// - Returns: A random value within the bounds of `range`.
@inlinable
public static func random<T: RandomNumberGenerator>(
in range: ClosedRange<Self>,
using generator: inout T
) -> Self {
// Compute delta, the distance between the lower and upper bounds. This
// value may not representable by the type Bound if Bound is signed, but
// is always representable as Bound.Magnitude.
var delta = Magnitude(truncatingIfNeeded: range.upperBound &- range.lowerBound)
// Subtle edge case: if the range is the whole set of representable values,
// then adding one to delta to account for a closed range will overflow.
// If we used &+ instead, the result would be zero, which isn't helpful,
// so we actually need to handle this case separately.
if delta == Magnitude.max {
return Self(truncatingIfNeeded: generator.next() as Magnitude)
}
// Need to widen delta to account for the right-endpoint of a closed range.
delta += 1
// The mathematical result we want is lowerBound plus a random value in
// 0 ..< delta. We need to be slightly careful about how we do this
// arithmetic; the Bound type cannot generally represent the random value,
// so we use a wrapping addition on Bound.Magnitude. This will often
// overflow, but produces the correct bit pattern for the result when
// converted back to Bound.
return Self(truncatingIfNeeded:
Magnitude(truncatingIfNeeded: range.lowerBound) &+
generator.next(upperBound: delta)
)
}
/// Returns a random value within the specified range.
///
/// Use this method to generate an integer within a specific range. This
/// example creates three new values in the range `1...100`.
///
/// for _ in 1...3 {
/// print(Int.random(in: 1...100))
/// }
/// // Prints "53"
/// // Prints "64"
/// // Prints "5"
///
/// This method is equivalent to calling `random(in:using:)`, passing in the
/// system's default random generator.
///
/// - Parameter range: The range in which to create a random value.
/// - Returns: A random value within the bounds of `range`.
@inlinable
public static func random(in range: ClosedRange<Self>) -> Self {
var g = SystemRandomNumberGenerator()
return Self.random(in: range, using: &g)
}
}
//===----------------------------------------------------------------------===//
//===--- Operators on FixedWidthInteger -----------------------------------===//
//===----------------------------------------------------------------------===//
extension FixedWidthInteger {
/// Returns the inverse of the bits set in the argument.
///
/// The bitwise NOT operator (`~`) is a prefix operator that returns a value
/// in which all the bits of its argument are flipped: Bits that are `1` in
/// the argument are `0` in the result, and bits that are `0` in the argument
/// are `1` in the result. This is equivalent to the inverse of a set. For
/// example:
///
/// let x: UInt8 = 5 // 0b00000101
/// let notX = ~x // 0b11111010
///
/// Performing a bitwise NOT operation on 0 returns a value with every bit
/// set to `1`.
///
/// let allOnes = ~UInt8.min // 0b11111111
///
/// - Complexity: O(1).
@_transparent
public static prefix func ~ (x: Self) -> Self {
return 0 &- x &- 1
}
//===----------------------------------------------------------------------===//
//=== "Smart right shift", supporting overshifts and negative shifts ------===//
//===----------------------------------------------------------------------===//
/// Returns the result of shifting a value's binary representation the
/// specified number of digits to the right.
///
/// The `>>` operator performs a *smart shift*, which defines a result for a
/// shift of any value.
///
/// - Using a negative value for `rhs` performs a left shift using
/// `abs(rhs)`.
/// - Using a value for `rhs` that is greater than or equal to the bit width
/// of `lhs` is an *overshift*. An overshift results in `-1` for a
/// negative value of `lhs` or `0` for a nonnegative value.
/// - Using any other value for `rhs` performs a right shift on `lhs` by that
/// amount.
///
/// The following example defines `x` as an instance of `UInt8`, an 8-bit,
/// unsigned integer type. If you use `2` as the right-hand-side value in an
/// operation on `x`, the value is shifted right by two bits.
///
/// let x: UInt8 = 30 // 0b00011110
/// let y = x >> 2
/// // y == 7 // 0b00000111
///
/// If you use `11` as `rhs`, `x` is overshifted such that all of its bits
/// are set to zero.
///
/// let z = x >> 11
/// // z == 0 // 0b00000000
///
/// Using a negative value as `rhs` is the same as performing a left shift
/// using `abs(rhs)`.
///
/// let a = x >> -3
/// // a == 240 // 0b11110000
/// let b = x << 3
/// // b == 240 // 0b11110000
///
/// Right shift operations on negative values "fill in" the high bits with
/// ones instead of zeros.
///
/// let q: Int8 = -30 // 0b11100010
/// let r = q >> 2
/// // r == -8 // 0b11111000
///
/// let s = q >> 11
/// // s == -1 // 0b11111111
///
/// - Parameters:
/// - lhs: The value to shift.
/// - rhs: The number of bits to shift `lhs` to the right.
@_semantics("optimize.sil.specialize.generic.partial.never")
@_transparent
public static func >> <
Other: BinaryInteger
>(lhs: Self, rhs: Other) -> Self {
var lhs = lhs
_nonMaskingRightShiftGeneric(&lhs, rhs)
return lhs
}
@_transparent
@_semantics("optimize.sil.specialize.generic.partial.never")
public static func >>= <
Other: BinaryInteger
>(lhs: inout Self, rhs: Other) {
_nonMaskingRightShiftGeneric(&lhs, rhs)
}
@_transparent
public static func _nonMaskingRightShiftGeneric <
Other: BinaryInteger
>(_ lhs: inout Self, _ rhs: Other) {
let shift = rhs < -Self.bitWidth ? -Self.bitWidth
: rhs > Self.bitWidth ? Self.bitWidth
: Int(rhs)
lhs = _nonMaskingRightShift(lhs, shift)
}
@_transparent
public static func _nonMaskingRightShift(_ lhs: Self, _ rhs: Int) -> Self {
let overshiftR = Self.isSigned ? lhs &>> (Self.bitWidth - 1) : 0
let overshiftL: Self = 0
if _fastPath(rhs >= 0) {
if _fastPath(rhs < Self.bitWidth) {
return lhs &>> Self(truncatingIfNeeded: rhs)
}
return overshiftR
}
if _slowPath(rhs <= -Self.bitWidth) {
return overshiftL
}
return lhs &<< -rhs
}
//===----------------------------------------------------------------------===//
//=== "Smart left shift", supporting overshifts and negative shifts -------===//
//===----------------------------------------------------------------------===//
/// Returns the result of shifting a value's binary representation the
/// specified number of digits to the left.
///
/// The `<<` operator performs a *smart shift*, which defines a result for a
/// shift of any value.
///
/// - Using a negative value for `rhs` performs a right shift using
/// `abs(rhs)`.
/// - Using a value for `rhs` that is greater than or equal to the bit width
/// of `lhs` is an *overshift*, resulting in zero.
/// - Using any other value for `rhs` performs a left shift on `lhs` by that
/// amount.
///
/// The following example defines `x` as an instance of `UInt8`, an 8-bit,
/// unsigned integer type. If you use `2` as the right-hand-side value in an
/// operation on `x`, the value is shifted left by two bits.
///
/// let x: UInt8 = 30 // 0b00011110
/// let y = x << 2
/// // y == 120 // 0b01111000
///
/// If you use `11` as `rhs`, `x` is overshifted such that all of its bits
/// are set to zero.
///
/// let z = x << 11
/// // z == 0 // 0b00000000
///
/// Using a negative value as `rhs` is the same as performing a right shift
/// with `abs(rhs)`.
///
/// let a = x << -3
/// // a == 3 // 0b00000011
/// let b = x >> 3
/// // b == 3 // 0b00000011
///
/// - Parameters:
/// - lhs: The value to shift.
/// - rhs: The number of bits to shift `lhs` to the left.
@_semantics("optimize.sil.specialize.generic.partial.never")
@_transparent
public static func << <
Other: BinaryInteger
>(lhs: Self, rhs: Other) -> Self {
var lhs = lhs
_nonMaskingLeftShiftGeneric(&lhs, rhs)
return lhs
}
@_transparent
@_semantics("optimize.sil.specialize.generic.partial.never")
public static func <<= <
Other: BinaryInteger
>(lhs: inout Self, rhs: Other) {
_nonMaskingLeftShiftGeneric(&lhs, rhs)
}
@_transparent
public static func _nonMaskingLeftShiftGeneric <
Other: BinaryInteger
>(_ lhs: inout Self, _ rhs: Other) {
let shift = rhs < -Self.bitWidth ? -Self.bitWidth
: rhs > Self.bitWidth ? Self.bitWidth
: Int(rhs)
lhs = _nonMaskingLeftShift(lhs, shift)
}
@_transparent
public static func _nonMaskingLeftShift(_ lhs: Self, _ rhs: Int) -> Self {
let overshiftR = Self.isSigned ? lhs &>> (Self.bitWidth - 1) : 0
let overshiftL: Self = 0
if _fastPath(rhs >= 0) {
if _fastPath(rhs < Self.bitWidth) {
return lhs &<< Self(truncatingIfNeeded: rhs)
}
return overshiftL
}
if _slowPath(rhs <= -Self.bitWidth) {
return overshiftR
}
return lhs &>> -rhs
}
}
extension FixedWidthInteger {
@inlinable
@_semantics("optimize.sil.specialize.generic.partial.never")
public // @testable
static func _convert<Source: BinaryFloatingPoint>(
from source: Source
) -> (value: Self?, exact: Bool) {
guard _fastPath(!source.isZero) else { return (0, true) }
guard _fastPath(source.isFinite) else { return (nil, false) }
guard Self.isSigned || source > -1 else { return (nil, false) }
let exponent = source.exponent
if _slowPath(Self.bitWidth <= exponent) { return (nil, false) }
let minBitWidth = source.significandWidth
let isExact = (minBitWidth <= exponent)
let bitPattern = source.significandBitPattern
// Determine the actual number of fractional significand bits.
// `Source.significandBitCount` would not reflect the actual number of
// fractional significand bits if `Source` is not a fixed-width floating-point
// type; we can compute this value as follows if `source` is finite:
let bitWidth = minBitWidth &+ bitPattern.trailingZeroBitCount
let shift = exponent - Source.Exponent(bitWidth)
// Use `Self.Magnitude` to prevent sign extension if `shift < 0`.
let shiftedBitPattern = Self.Magnitude.bitWidth > bitWidth
? Self.Magnitude(truncatingIfNeeded: bitPattern) << shift
: Self.Magnitude(truncatingIfNeeded: bitPattern << shift)
if _slowPath(Self.isSigned && Self.bitWidth &- 1 == exponent) {
return source < 0 && shiftedBitPattern == 0
? (Self.min, isExact)
: (nil, false)
}
let magnitude = ((1 as Self.Magnitude) << exponent) | shiftedBitPattern
return (
Self.isSigned && source < 0 ? 0 &- Self(magnitude) : Self(magnitude),
isExact)
}
/// Creates an integer from the given floating-point value, rounding toward
/// zero. Any fractional part of the value passed as `source` is removed.
///
/// let x = Int(21.5)
/// // x == 21
/// let y = Int(-21.5)
/// // y == -21
///
/// If `source` is outside the bounds of this type after rounding toward
/// zero, a runtime error may occur.
///
/// let z = UInt(-21.5)
/// // Error: ...outside the representable range
///
/// - Parameter source: A floating-point value to convert to an integer.
/// `source` must be representable in this type after rounding toward
/// zero.
@inlinable
@_semantics("optimize.sil.specialize.generic.partial.never")
@inline(__always)
public init<T: BinaryFloatingPoint>(_ source: T) {
guard let value = Self._convert(from: source).value else {
fatalError("""
\(T.self) value cannot be converted to \(Self.self) because it is \
outside the representable range
""")
}
self = value
}
/// Creates an integer from the given floating-point value, if it can be
/// represented exactly.
///
/// If the value passed as `source` is not representable exactly, the result
/// is `nil`. In the following example, the constant `x` is successfully
/// created from a value of `21.0`, while the attempt to initialize the
/// constant `y` from `21.5` fails:
///
/// let x = Int(exactly: 21.0)
/// // x == Optional(21)
/// let y = Int(exactly: 21.5)
/// // y == nil
///
/// - Parameter source: A floating-point value to convert to an integer.
@_semantics("optimize.sil.specialize.generic.partial.never")
@inlinable
public init?<T: BinaryFloatingPoint>(exactly source: T) {
let (temporary, exact) = Self._convert(from: source)
guard exact, let value = temporary else {
return nil
}
self = value
}
/// Creates a new instance with the representable value that's closest to the
/// given integer.
///
/// If the value passed as `source` is greater than the maximum representable
/// value in this type, the result is the type's `max` value. If `source` is
/// less than the smallest representable value in this type, the result is
/// the type's `min` value.
///
/// In this example, `x` is initialized as an `Int8` instance by clamping
/// `500` to the range `-128...127`, and `y` is initialized as a `UInt`
/// instance by clamping `-500` to the range `0...UInt.max`.
///
/// let x = Int8(clamping: 500)
/// // x == 127
/// // x == Int8.max
///
/// let y = UInt(clamping: -500)
/// // y == 0
///
/// - Parameter source: An integer to convert to this type.
@inlinable
@_semantics("optimize.sil.specialize.generic.partial.never")
public init<Other: BinaryInteger>(clamping source: Other) {
if _slowPath(source < Self.min) {
self = Self.min
}
else if _slowPath(source > Self.max) {
self = Self.max
}
else { self = Self(truncatingIfNeeded: source) }
}
/// Creates a new instance from the bit pattern of the given instance by
/// truncating or sign-extending if needed to fit this type.
///
/// When the bit width of `T` (the type of `source`) is equal to or greater
/// than this type's bit width, the result is the truncated
/// least-significant bits of `source`. For example, when converting a
/// 16-bit value to an 8-bit type, only the lower 8 bits of `source` are
/// used.
///
/// let p: Int16 = -500
/// // 'p' has a binary representation of 11111110_00001100
/// let q = Int8(truncatingIfNeeded: p)
/// // q == 12
/// // 'q' has a binary representation of 00001100
///
/// When the bit width of `T` is less than this type's bit width, the result
/// is *sign-extended* to fill the remaining bits. That is, if `source` is
/// negative, the result is padded with ones; otherwise, the result is
/// padded with zeros.
///
/// let u: Int8 = 21
/// // 'u' has a binary representation of 00010101
/// let v = Int16(truncatingIfNeeded: u)
/// // v == 21
/// // 'v' has a binary representation of 00000000_00010101
///
/// let w: Int8 = -21
/// // 'w' has a binary representation of 11101011
/// let x = Int16(truncatingIfNeeded: w)
/// // x == -21
/// // 'x' has a binary representation of 11111111_11101011
/// let y = UInt16(truncatingIfNeeded: w)
/// // y == 65515
/// // 'y' has a binary representation of 11111111_11101011
///
/// - Parameter source: An integer to convert to this type.
@inlinable // FIXME(inline-always)
@inline(__always)
public init<T: BinaryInteger>(truncatingIfNeeded source: T) {
if Self.bitWidth <= Int.bitWidth {
self = Self(_truncatingBits: source._lowWord)
}
else {
self = Self._truncatingInit(source)
}
}
@_alwaysEmitIntoClient
internal static func _truncatingInit<T: BinaryInteger>(_ source: T) -> Self {
let neg = source < (0 as T)
var result: Self = neg ? ~0 : 0
var shift: Self = 0
let width = Self(_truncatingBits: Self.bitWidth._lowWord)
for word in source.words {
guard shift < width else { break }
// Masking shift is OK here because we have already ensured
// that shift < Self.bitWidth. Not masking results in
// infinite recursion.
result ^= Self(_truncatingBits: neg ? ~word : word) &<< shift
shift += Self(_truncatingBits: Int.bitWidth._lowWord)
}
return result
}
@_transparent
public // transparent
static var _highBitIndex: Self {
return Self.init(_truncatingBits: UInt(Self.bitWidth._value) &- 1)
}
/// Returns the sum of the two given values, wrapping the result in case of
/// any overflow.
///
/// The overflow addition operator (`&+`) discards any bits that overflow the
/// fixed width of the integer type. In the following example, the sum of
/// `100` and `121` is greater than the maximum representable `Int8` value,
/// so the result is the partial value after discarding the overflowing
/// bits.
///
/// let x: Int8 = 10 &+ 21
/// // x == 31
/// let y: Int8 = 100 &+ 121
/// // y == -35 (after overflow)
///
/// For more about arithmetic with overflow operators, see [Overflow
/// Operators][overflow] in *[The Swift Programming Language][tspl]*.
///
/// [overflow]: https://docs.swift.org/swift-book/LanguageGuide/AdvancedOperators.html#ID37
/// [tspl]: https://docs.swift.org/swift-book/
///
/// - Parameters:
/// - lhs: The first value to add.
/// - rhs: The second value to add.
@_transparent
public static func &+ (lhs: Self, rhs: Self) -> Self {
return lhs.addingReportingOverflow(rhs).partialValue
}
/// Adds two values and stores the result in the left-hand-side variable,
/// wrapping any overflow.
///
/// The masking addition assignment operator (`&+=`) silently wraps any
/// overflow that occurs during the operation. In the following example, the
/// sum of `100` and `121` is greater than the maximum representable `Int8`
/// value, so the result is the partial value after discarding the
/// overflowing bits.
///
/// var x: Int8 = 10
/// x &+= 21
/// // x == 31
/// var y: Int8 = 100
/// y &+= 121
/// // y == -35 (after overflow)
///
/// For more about arithmetic with overflow operators, see [Overflow
/// Operators][overflow] in *[The Swift Programming Language][tspl]*.
///
/// [overflow]: https://docs.swift.org/swift-book/LanguageGuide/AdvancedOperators.html#ID37
/// [tspl]: https://docs.swift.org/swift-book/
///
/// - Parameters:
/// - lhs: The first value to add.
/// - rhs: The second value to add.
@_transparent
public static func &+= (lhs: inout Self, rhs: Self) {
lhs = lhs &+ rhs
}
/// Returns the difference of the two given values, wrapping the result in
/// case of any overflow.
///
/// The overflow subtraction operator (`&-`) discards any bits that overflow
/// the fixed width of the integer type. In the following example, the
/// difference of `10` and `21` is less than zero, the minimum representable
/// `UInt` value, so the result is the partial value after discarding the
/// overflowing bits.
///
/// let x: UInt8 = 21 &- 10
/// // x == 11
/// let y: UInt8 = 10 &- 21
/// // y == 245 (after overflow)
///
/// For more about arithmetic with overflow operators, see [Overflow
/// Operators][overflow] in *[The Swift Programming Language][tspl]*.
///
/// [overflow]: https://docs.swift.org/swift-book/LanguageGuide/AdvancedOperators.html#ID37
/// [tspl]: https://docs.swift.org/swift-book/
///
/// - Parameters:
/// - lhs: A numeric value.
/// - rhs: The value to subtract from `lhs`.
@_transparent
public static func &- (lhs: Self, rhs: Self) -> Self {
return lhs.subtractingReportingOverflow(rhs).partialValue
}
/// Subtracts the second value from the first and stores the difference in the
/// left-hand-side variable, wrapping any overflow.
///
/// The masking subtraction assignment operator (`&-=`) silently wraps any
/// overflow that occurs during the operation. In the following example, the
/// difference of `10` and `21` is less than zero, the minimum representable
/// `UInt` value, so the result is the result is the partial value after
/// discarding the overflowing bits.
///
/// var x: Int8 = 21
/// x &-= 10
/// // x == 11
/// var y: UInt8 = 10
/// y &-= 21
/// // y == 245 (after overflow)
///
/// For more about arithmetic with overflow operators, see [Overflow
/// Operators][overflow] in *[The Swift Programming Language][tspl]*.
///
/// [overflow]: https://docs.swift.org/swift-book/LanguageGuide/AdvancedOperators.html#ID37
/// [tspl]: https://docs.swift.org/swift-book/
///
/// - Parameters:
/// - lhs: A numeric value.
/// - rhs: The value to subtract from `lhs`.
@_transparent
public static func &-= (lhs: inout Self, rhs: Self) {
lhs = lhs &- rhs
}
/// Returns the product of the two given values, wrapping the result in case
/// of any overflow.
///
/// The overflow multiplication operator (`&*`) discards any bits that
/// overflow the fixed width of the integer type. In the following example,
/// the product of `10` and `50` is greater than the maximum representable
/// `Int8` value, so the result is the partial value after discarding the
/// overflowing bits.
///
/// let x: Int8 = 10 &* 5
/// // x == 50
/// let y: Int8 = 10 &* 50
/// // y == -12 (after overflow)
///
/// For more about arithmetic with overflow operators, see [Overflow
/// Operators][overflow] in *[The Swift Programming Language][tspl]*.
///
/// [overflow]: https://docs.swift.org/swift-book/LanguageGuide/AdvancedOperators.html#ID37
/// [tspl]: https://docs.swift.org/swift-book/
///
/// - Parameters:
/// - lhs: The first value to multiply.
/// - rhs: The second value to multiply.
@_transparent
public static func &* (lhs: Self, rhs: Self) -> Self {
return lhs.multipliedReportingOverflow(by: rhs).partialValue
}
/// Multiplies two values and stores the result in the left-hand-side
/// variable, wrapping any overflow.
///
/// The masking multiplication assignment operator (`&*=`) silently wraps
/// any overflow that occurs during the operation. In the following example,
/// the product of `10` and `50` is greater than the maximum representable
/// `Int8` value, so the result is the partial value after discarding the
/// overflowing bits.
///
/// var x: Int8 = 10
/// x &*= 5
/// // x == 50
/// var y: Int8 = 10
/// y &*= 50
/// // y == -12 (after overflow)
///
/// For more about arithmetic with overflow operators, see [Overflow
/// Operators][overflow] in *[The Swift Programming Language][tspl]*.
///
/// [overflow]: https://docs.swift.org/swift-book/LanguageGuide/AdvancedOperators.html#ID37
/// [tspl]: https://docs.swift.org/swift-book/
///
/// - Parameters:
/// - lhs: The first value to multiply.
/// - rhs: The second value to multiply.
@_transparent
public static func &*= (lhs: inout Self, rhs: Self) {
lhs = lhs &* rhs
}
}
extension FixedWidthInteger {
@inlinable
public static func _random<R: RandomNumberGenerator>(
using generator: inout R
) -> Self {
if bitWidth <= UInt64.bitWidth {
return Self(truncatingIfNeeded: generator.next())
}
let (quotient, remainder) = bitWidth.quotientAndRemainder(
dividingBy: UInt64.bitWidth
)
var tmp: Self = 0
for i in 0 ..< quotient + remainder.signum() {
let next: UInt64 = generator.next()
tmp += Self(truncatingIfNeeded: next) &<< (UInt64.bitWidth * i)
}
return tmp
}
}
//===----------------------------------------------------------------------===//
//===--- UnsignedInteger --------------------------------------------------===//
//===----------------------------------------------------------------------===//
/// An integer type that can represent only nonnegative values.
public protocol UnsignedInteger: BinaryInteger { }
extension UnsignedInteger {
/// The magnitude of this value.
///
/// Every unsigned integer is its own magnitude, so for any value `x`,
/// `x == x.magnitude`.
///
/// The global `abs(_:)` function provides more familiar syntax when you need
/// to find an absolute value. In addition, because `abs(_:)` always returns
/// a value of the same type, even in a generic context, using the function
/// instead of the `magnitude` property is encouraged.
@inlinable // FIXME(inline-always)
public var magnitude: Self {
@inline(__always)
get { return self }
}
/// A Boolean value indicating whether this type is a signed integer type.
///
/// This property is always `false` for unsigned integer types.
@inlinable // FIXME(inline-always)
public static var isSigned: Bool {
@inline(__always)
get { return false }
}
}
extension UnsignedInteger where Self: FixedWidthInteger {
/// Creates a new instance from the given integer.
///
/// Use this initializer to convert from another integer type when you know
/// the value is within the bounds of this type. Passing a value that can't
/// be represented in this type results in a runtime error.
///
/// In the following example, the constant `y` is successfully created from
/// `x`, an `Int` instance with a value of `100`. Because the `Int8` type
/// can represent `127` at maximum, the attempt to create `z` with a value
/// of `1000` results in a runtime error.
///
/// let x = 100
/// let y = Int8(x)
/// // y == 100
/// let z = Int8(x * 10)
/// // Error: Not enough bits to represent the given value
///
/// - Parameter source: A value to convert to this type of integer. The value
/// passed as `source` must be representable in this type.
@_semantics("optimize.sil.specialize.generic.partial.never")
@inlinable // FIXME(inline-always)
@inline(__always)
public init<T: BinaryInteger>(_ source: T) {
// This check is potentially removable by the optimizer
if T.isSigned {
_precondition(source >= (0 as T), "Negative value is not representable")
}
// This check is potentially removable by the optimizer
if source.bitWidth >= Self.bitWidth {
_precondition(source <= Self.max,
"Not enough bits to represent the passed value")
}
self.init(truncatingIfNeeded: source)
}
/// Creates a new instance from the given integer, if it can be represented
/// exactly.
///
/// If the value passed as `source` is not representable exactly, the result
/// is `nil`. In the following example, the constant `x` is successfully
/// created from a value of `100`, while the attempt to initialize the
/// constant `y` from `1_000` fails because the `Int8` type can represent
/// `127` at maximum:
///
/// let x = Int8(exactly: 100)
/// // x == Optional(100)
/// let y = Int8(exactly: 1_000)
/// // y == nil
///
/// - Parameter source: A value to convert to this type of integer.
@_semantics("optimize.sil.specialize.generic.partial.never")
@inlinable // FIXME(inline-always)
@inline(__always)
public init?<T: BinaryInteger>(exactly source: T) {
// This check is potentially removable by the optimizer
if T.isSigned && source < (0 as T) {
return nil
}
// The width check can be eliminated by the optimizer
if source.bitWidth >= Self.bitWidth &&
source > Self.max {
return nil
}
self.init(truncatingIfNeeded: source)
}
/// The maximum representable integer in this type.
///
/// For unsigned integer types, this value is `(2 ** bitWidth) - 1`, where
/// `**` is exponentiation.
@_transparent
public static var max: Self { return ~0 }
/// The minimum representable integer in this type.
///
/// For unsigned integer types, this value is always `0`.
@_transparent
public static var min: Self { return 0 }
}
//===----------------------------------------------------------------------===//
//===--- SignedInteger ----------------------------------------------------===//
//===----------------------------------------------------------------------===//
/// An integer type that can represent both positive and negative values.
public protocol SignedInteger: BinaryInteger, SignedNumeric {
// These requirements are needed for binary compatibility; the following:
//
// func foo<T>(_ a: T) -> T
// where T: SignedInteger & FixedWidthInteger {
// a &+ 1
// }
//
// generated a call to `static Swift.SignedInteger._maskingAdd(A, A) -> A`
// when compiled with Swift 5.5 and earlier.
@available(*, deprecated, message: "Use &+ instead.")
static func _maskingAdd(_ lhs: Self, _ rhs: Self) -> Self
@available(*, deprecated, message: "Use &- instead.")
static func _maskingSubtract(_ lhs: Self, _ rhs: Self) -> Self
}
extension SignedInteger {
/// A Boolean value indicating whether this type is a signed integer type.
///
/// This property is always `true` for signed integer types.
@inlinable // FIXME(inline-always)
public static var isSigned: Bool {
@inline(__always)
get { return true }
}
}
extension SignedInteger where Self: FixedWidthInteger {
/// Creates a new instance from the given integer.
///
/// Use this initializer to convert from another integer type when you know
/// the value is within the bounds of this type. Passing a value that can't
/// be represented in this type results in a runtime error.
///
/// In the following example, the constant `y` is successfully created from
/// `x`, an `Int` instance with a value of `100`. Because the `Int8` type
/// can represent `127` at maximum, the attempt to create `z` with a value
/// of `1000` results in a runtime error.
///
/// let x = 100
/// let y = Int8(x)
/// // y == 100
/// let z = Int8(x * 10)
/// // Error: Not enough bits to represent the given value
///
/// - Parameter source: A value to convert to this type of integer. The value
/// passed as `source` must be representable in this type.
@_semantics("optimize.sil.specialize.generic.partial.never")
@inlinable // FIXME(inline-always)
@inline(__always)
public init<T: BinaryInteger>(_ source: T) {
// This check is potentially removable by the optimizer
if T.isSigned && source.bitWidth > Self.bitWidth {
_precondition(source >= Self.min,
"Not enough bits to represent a signed value")
}
// This check is potentially removable by the optimizer
if (source.bitWidth > Self.bitWidth) ||
(source.bitWidth == Self.bitWidth && !T.isSigned) {
_precondition(source <= Self.max,
"Not enough bits to represent the passed value")
}
self.init(truncatingIfNeeded: source)
}
/// Creates a new instance from the given integer, if it can be represented
/// exactly.
///
/// If the value passed as `source` is not representable exactly, the result
/// is `nil`. In the following example, the constant `x` is successfully
/// created from a value of `100`, while the attempt to initialize the
/// constant `y` from `1_000` fails because the `Int8` type can represent
/// `127` at maximum:
///
/// let x = Int8(exactly: 100)
/// // x == Optional(100)
/// let y = Int8(exactly: 1_000)
/// // y == nil
///
/// - Parameter source: A value to convert to this type of integer.
@_semantics("optimize.sil.specialize.generic.partial.never")
@inlinable // FIXME(inline-always)
@inline(__always)
public init?<T: BinaryInteger>(exactly source: T) {
// This check is potentially removable by the optimizer
if T.isSigned && source.bitWidth > Self.bitWidth && source < Self.min {
return nil
}
// The width check can be eliminated by the optimizer
if (source.bitWidth > Self.bitWidth ||
(source.bitWidth == Self.bitWidth && !T.isSigned)) &&
source > Self.max {
return nil
}
self.init(truncatingIfNeeded: source)
}
/// The maximum representable integer in this type.
///
/// For signed integer types, this value is `(2 ** (bitWidth - 1)) - 1`,
/// where `**` is exponentiation.
@_transparent
public static var max: Self { return ~min }
/// The minimum representable integer in this type.
///
/// For signed integer types, this value is `-(2 ** (bitWidth - 1))`, where
/// `**` is exponentiation.
@_transparent
public static var min: Self {
return (-1 as Self) &<< Self._highBitIndex
}
@inlinable
public func isMultiple(of other: Self) -> Bool {
// Nothing but zero is a multiple of zero.
if other == 0 { return self == 0 }
// Special case to avoid overflow on .min / -1 for signed types.
if other == -1 { return true }
// Having handled those special cases, this is safe.
return self % other == 0
}
}
/// Returns the given integer as the equivalent value in a different integer
/// type.
///
/// Calling the `numericCast(_:)` function is equivalent to calling an
/// initializer for the destination type. `numericCast(_:)` traps on overflow
/// in `-O` and `-Onone` builds.
///
/// - Parameter x: The integer to convert, an instance of type `T`.
/// - Returns: The value of `x` converted to type `U`.
@inlinable
public func numericCast<T: BinaryInteger, U: BinaryInteger>(_ x: T) -> U {
return U(x)
}
// Needed to support user-defined types conformance to SignedInteger.
// We need these defaults to exist, but they are not called.
extension SignedInteger {
@available(*, deprecated, message: "Use &+ instead.")
public static func _maskingAdd(_ lhs: Self, _ rhs: Self) -> Self {
fatalError("Should be overridden in a more specific type")
}
@available(*, deprecated, message: "Use &- instead.")
public static func _maskingSubtract(_ lhs: Self, _ rhs: Self) -> Self {
fatalError("Should be overridden in a more specific type")
}
}
// These symbols have to exist for ABI compatibility, but should not be used
// any longer; we want to find the FixedWidthInteger definitions instead.
extension SignedInteger where Self: FixedWidthInteger {
@available(*, unavailable)
public static func &+(lhs: Self, rhs: Self) -> Self {
lhs.addingReportingOverflow(rhs).partialValue
}
// This may be called in rare situations by binaries compiled with
// Swift 5.5 and earlier, so we need to keep it around for compatibility.
// We can't mark it unavailable, because then the concrete signed integer
// types in the standard library would not satisfy the protocol requirements.
@available(*, deprecated, message: "Use &+ instead.")
public static func _maskingAdd(_ lhs: Self, _ rhs: Self) -> Self {
lhs.addingReportingOverflow(rhs).partialValue
}
@available(*, unavailable)
public static func &-(lhs: Self, rhs: Self) -> Self {
lhs.subtractingReportingOverflow(rhs).partialValue
}
// This may be called in rare situations by binaries compiled with
// Swift 5.5 and earlier, so we need to keep it around for compatibility.
// We can't mark it unavailable, because then the concrete signed integer
// types in the standard library would not satisfy the protocol requirements.
@available(*, deprecated, message: "Use &- instead.")
public static func _maskingSubtract(_ lhs: Self, _ rhs: Self) -> Self {
lhs.subtractingReportingOverflow(rhs).partialValue
}
}
| apache-2.0 | 0418c85bd539d77bd3bfefbf15d7367e | 37.394359 | 93 | 0.595578 | 4.073435 | false | false | false | false |
wireapp/wire-ios-sync-engine | Source/Notifications/Push notifications/Notification Types/PushNotificationCategory.swift | 1 | 2934 | //
// Wire
// Copyright (C) 2018 Wire Swiss GmbH
//
// 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 Foundation
import UserNotifications
/**
* The categories of notifications supported by the app.
*/
enum PushNotificationCategory: String, CaseIterable {
case incomingCall = "incomingCallCategory"
case missedCall = "missedCallCategory"
case conversation = "conversationCategory"
case conversationWithMute = "conversationCategoryWithMute"
case conversationWithLike = "conversationCategoryWithLike"
case conversationWithLikeAndMute = "conversationCategoryWithLikeAndMute"
case connect = "connectCategory"
case alert = "alertCategory"
case conversationUnderEncryptionAtRest = "conversationUnderEncryptionAtRestCategory"
case conversationUnderEncryptionAtRestWithMute = "conversationUnderEncryptionAtRestWithMuteCategory"
/// All the supported categories.
static var allCategories: Set<UNNotificationCategory> {
let categories = PushNotificationCategory.allCases.map(\.userNotificationCategory)
return Set(categories)
}
/// The actions for notifications of this category.
var actions: [NotificationAction] {
switch self {
case .incomingCall:
return [CallNotificationAction.ignore]
case .missedCall:
return [CallNotificationAction.callBack]
case .conversation:
return []
case .conversationWithMute:
return [ConversationNotificationAction.mute]
case .conversationWithLike:
return []
case .conversationWithLikeAndMute:
return [ConversationNotificationAction.mute]
case .connect:
return [ConversationNotificationAction.connect]
case .alert:
return []
case .conversationUnderEncryptionAtRest:
return []
case .conversationUnderEncryptionAtRestWithMute:
return [ConversationNotificationAction.mute]
}
}
/// The representation of the category that can be used with `UserNotifications` API.
var userNotificationCategory: UNNotificationCategory {
let userActions = self.actions.map(\.userAction)
return UNNotificationCategory(identifier: rawValue, actions: userActions, intentIdentifiers: [], options: [])
}
}
| gpl-3.0 | 232f01e2dfef40bc8b47d3b379ec2b10 | 36.615385 | 117 | 0.718473 | 5.129371 | false | false | false | false |
byss/KBAPISupport | KBAPISupport/Core/Internal/CoderUtils.swift | 1 | 3924 | //
// CoderUtils.swift
// Copyright © 2018 Kirill byss Bystrov. 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
internal typealias CodingPath = [CodingKey];
internal extension KeyedEncodingContainerProtocol {
internal mutating func superEncoder () -> Encoder {
return self.superEncoder (forKey: .super);
}
}
internal extension Array where Element == CodingKey {
internal static func += (lhs: inout Array, rhs: CodingKey) {
lhs.append (rhs);
}
internal static func += <Key> (lhs: inout Array, rhs: Key) where Key: CodingKey {
lhs.append (rhs);
}
internal static func += <Path> (lhs: inout Array, rhs: Path) where Path: Sequence, Path.Element: CodingKey {
lhs.reserveCapacity (lhs.count + rhs.underestimatedCount);
for element in rhs {
lhs += element;
}
}
internal static func + (lhs: Array, rhs: CodingKey) -> Array {
var lhs = lhs;
lhs += rhs;
return lhs;
}
internal static func + <Key> (lhs: Array, rhs: Key) -> Array where Key: CodingKey {
var lhs = lhs;
lhs += rhs;
return lhs;
}
internal static func + <Path> (lhs: Array, rhs: Path) -> Array where Path: Sequence, Path.Element: CodingKey {
var lhs = lhs;
lhs += rhs;
return lhs;
}
internal var urlencodedParameterName: String {
guard let nameHead = self.first?.stringValue else {
return "";
}
let nameTail = self.dropFirst ();
guard !nameTail.isEmpty else {
return nameHead;
}
return nameHead + "[" + nameTail.map { $0.stringValue }.joined (separator: "][") + "]";
}
}
internal extension String {
internal init <T> (urlRequestSerialized value: T) where T: Encodable {
print (value);
switch (value) {
case let boolValue as Bool:
self = (boolValue ? "1" : "0");
case let string as String:
self = string;
case let convertible as CustomStringConvertible:
self = convertible.description;
default:
self.init (reflecting: value);
}
}
internal init <T> (urlRequestSerialized value: T) where T: Encodable, T: StringProtocol {
self.init (value);
}
internal init <T> (urlRequestSerialized value: T) where T: Encodable, T: FixedWidthInteger {
self.init (value);
}
}
internal struct ContainerIndexKey: CodingKey {
internal var intValue: Int? {
return self.value;
}
internal var stringValue: String {
return "\(self.value)";
}
private let value: Int;
internal init (intValue: Int) {
self.value = intValue;
}
internal init? (stringValue: String) {
guard let value = Int (stringValue) else {
return nil;
}
self.value = value;
}
}
fileprivate extension CodingKey {
fileprivate static var `super`: Self {
guard let result = Self (stringValue: "super") ?? Self (intValue: 0) else {
log.fault ("Cannot instantiate \"super\" / zero key");
return Self (stringValue: "super")!;
}
return result;
}
}
private let log = KBLoggerWrapper ();
| mit | 0cd70f3f69e27dc4720dd7e63f3936d5 | 27.635036 | 111 | 0.696916 | 3.662932 | false | false | false | false |
matfur92/SwiftMongoDB | swiftMongoDB/MongoObject.swift | 1 | 1209 | //
// MongoObject.swift
// swiftMongoDB
//
// Created by Dan Appel on 8/28/15.
// Copyright © 2015 Dan Appel. All rights reserved.
//
import Foundation
/**
* A protocol that allows documents to be described in an Object Orientated way.
*/
public protocol MongoObject {
func Document() throws -> MongoDocument
func properties() -> DocumentData
}
public extension MongoObject {
/**
- returns: Returns a MongoDocument initialized from the Schema.
*/
func Document() throws -> MongoDocument {
return try MongoDocument(withSchemaObject: self)
}
/**
- returns: Returns each of the properties of class in the form of DocumentData ([String : AnyObject])
*/
func properties() -> DocumentData {
var children = DocumentData()
for child in Mirror(reflecting: self).children {
if let label = child.label {
if label.characters[label.startIndex] != "_" {
if let value = child.value as? AnyObject {
children[label] = value
}
}
}
}
return children
}
}
| mit | 5129bb8c0774af54fb6b0ed03259b5bf | 22.686275 | 105 | 0.565397 | 4.774704 | false | false | false | false |
felix-dumit/EasySpotlight | Example/Tests/MockSearchableIndex.swift | 1 | 1440 | //
// MockSearchableIndex.swift
// EasySpotlight
//
// Created by Felix Dumit on 10/16/15.
// Copyright © 2015 CocoaPods. All rights reserved.
//
import CoreSpotlight
@testable import EasySpotlight
extension SpotlightConvertable {
var userActivityWhenOpened: NSUserActivity {
let activity = NSUserActivity(activityType: CSSearchableItemActionType)
activity.userInfo?[CSSearchableItemActivityIdentifier] = self.uniqueIdentifier
return activity
}
}
class MockSearchableIndex: CSSearchableIndex {
var indexedItems = [CSSearchableItem]()
override func indexSearchableItems(_ items: [CSSearchableItem], completionHandler: ((Error?) -> Void)? = nil) {
indexedItems.append(contentsOf: items)
completionHandler?(nil)
}
override func deleteSearchableItems(withDomainIdentifiers domainIdentifiers: [String],
completionHandler: ((Error?) -> Void)? = nil) {
indexedItems = indexedItems.filter {
!domainIdentifiers.contains($0.domainIdentifier ?? "")
}
completionHandler?(nil)
}
override func deleteSearchableItems(withIdentifiers identifiers: [String],
completionHandler: ((Error?) -> Void)? = nil) {
indexedItems = indexedItems.filter {
!identifiers.contains($0.uniqueIdentifier)
}
completionHandler?(nil)
}
}
| mit | 71566188fb8a069ee57ecf968079fecc | 30.977778 | 115 | 0.659486 | 5.102837 | false | false | false | false |
richardpiazza/MiseEnPlace | Sources/MiseEnPlace/Recipe.swift | 1 | 11300 | import Foundation
/// Represents a compilation of `Ingredient`s or other `Recipe`s.
/// A `Recipe` is one of the primary protocols for interacting with an
/// object graph utilizing the `MiseEnPlace` framework.
///
/// ## Required Conformance
///
/// ```swift
/// // References to the elements that make up this `Recipe`s formula.
/// var formulaElements: [FormulaElement] { get set }
///
/// // References to the elements that make up this `Recipe`s procedure.
/// var procedureElements: [ProcedureElement] { get set }
/// ```
///
/// ## Protocol Conformance
///
/// `Unique`
/// ```swift
/// var uuid: String { get set }
/// var creationDate: Date { get set }
/// var modificationDate: Date { get set }
/// ```
///
/// `Descriptive`
/// ```swift
/// var name: String? { get set }
/// var commentary: String? { get set }
/// var classification: String? { get set }
/// ```
///
/// `Multimedia`
/// ```swift
/// var imagePath: String? { get set }
/// ```
///
/// `Quantifiable`
/// ```swift
/// var amount: Double { get set }
/// var unit: MeasurementUnit { get set }
/// ```
///
/// ## Notes:
///
/// - The `Quantifiable` conformance on a `Recipe` will represent the
/// _portion_ measurement. i.e. What is the equivalent measurement for one (1)
/// portion of this `Recipe`?
///
public protocol Recipe: Unique, Descriptive, Multimedia, Quantifiable {
var formulaElements: [FormulaElement] { get set }
var procedureElements: [ProcedureElement] { get set }
}
public extension Recipe {
var portion: Quantification {
return Quantification(amount: amount, unit: unit)
}
}
// MARK: - Amount
public extension Recipe {
/// Calculates the total mass for this formula in a give unit.
func totalAmount(for unit: MeasurementUnit) -> Double {
var amount: Double = 0.0
let elements = self.formula
for element in elements {
if let value = try? element.amount(for: unit) {
amount += value
}
}
return amount
}
/// The total mass of this formula in the portions unit.
var totalQuantification: Quantification {
let total = self.totalAmount(for: self.unit)
return Quantification(amount: total, unit: self.unit)
}
}
// MARK: - Yield
public extension Recipe {
/// Calculates the total number of portions (yield).
var yield: Double {
return totalQuantification.amount / amount
}
/// A 'Fractioned String' output of the `yield`.
var yieldString: String {
return "\(yield.fractionedString) portions"
}
/// A combined string: Total Measurement amount, Yield
var yieldTranslation: String {
return "\(totalQuantification.componentsTranslation), \(yieldString)"
}
/// A combined string: Total Measurement amount, Yield
///
/// The `totalQuantification` is first _normalized_ using the current `unit` `MeasurementSystemMethod`.
var yieldTranslationNormalized: String {
do {
let translation = try totalQuantification.normalizedQuantification().componentsTranslation
return "\(translation), \(yieldString)"
} catch {
return yieldTranslation
}
}
}
// MARK: - Formula
public extension Recipe {
/// An ordered list of formula elements (MeasuredIngredient/MeasuredRecipe).
var formula: [FormulaElement] {
return formulaElements.sorted(by: { $0.sequence < $1.sequence })
}
/// Assigns the next sequence number to the formula element.
mutating func insertFormulaElement(_ element: FormulaElement) {
var formulaElement = element
formulaElement.sequence = formula.count
formulaElements.append(formulaElement)
}
internal mutating func updateSequence(_ element: FormulaElement, sequence: Int) {
var formulaElement = element
formulaElement.sequence = sequence
guard let index = formulaElements.firstIndex(where: { $0.id == formulaElement.id }) else {
return
}
formulaElements.remove(at: index)
formulaElements.insert(formulaElement, at: index)
}
/// Adjusts the sequence numbers of all elements following the specified element.
mutating func removeFormulaElement(_ element: FormulaElement) {
guard let index = formula.firstIndex(where: { $0.uuid == element.uuid }) else {
return
}
for (idx, element) in formula.enumerated() {
guard idx > index else {
continue
}
let newSequence = idx - 1
updateSequence(element, sequence: newSequence)
}
formulaElements.remove(at: index)
}
/// Adjusts the sequencing of elements affected by a move operation.
///
/// - returns: A range of indices that have been affected by this operation
@discardableResult
mutating func moveFormulaElement(_ element: FormulaElement, fromIndex: Int, toIndex: Int) -> [Int] {
var indices: [Int] = []
guard fromIndex != toIndex else {
return indices
}
let elements = self.formula
if toIndex < fromIndex {
for i in toIndex..<fromIndex {
indices.append(i)
let formulaElement = elements[i]
let newSequence = i + 1
updateSequence(formulaElement, sequence: newSequence)
}
} else {
for i in fromIndex.advanced(by: 1)...toIndex {
indices.append(i)
let formulaElement = elements[i]
let newSequence = i - 1
updateSequence(formulaElement, sequence: newSequence)
}
}
updateSequence(element, sequence: toIndex)
indices.append(fromIndex)
return indices
}
}
// MARK: - Procedure
public extension Recipe {
/// An ordered list of procedure elements.
var procedure: [ProcedureElement] {
return procedureElements.sorted(by: { $0.sequence < $1.sequence })
}
// Assigns the next sequence number to the formula element.
mutating func insertProcedureElement(_ element: ProcedureElement) {
var procedureElement = element
procedureElement.sequence = procedure.count
procedureElements.append(procedureElement)
}
internal mutating func updateSequence(_ element: ProcedureElement, sequence: Int) {
var e = element
e.sequence = sequence
guard let index = procedureElements.firstIndex(where: { $0.uuid == element.uuid }) else {
return
}
procedureElements.remove(at: index)
procedureElements.insert(e, at: index)
}
/// Adjusts the sequence numbers of all elements following the specified element.
mutating func removeProcedureElement(_ element: ProcedureElement) {
guard let index = procedure.firstIndex(where: { $0.uuid == element.uuid }) else {
return
}
for (idx, element) in procedure.enumerated() {
guard idx > index else {
continue
}
let newSequence = idx - 1
updateSequence(element, sequence: newSequence)
}
procedureElements.remove(at: index)
}
/// Adjusts the sequencing of elements affected by a move operation.
///
/// - returns: A range of indices that have been affected by this operation
@discardableResult
mutating func moveProcedureElement(_ element: ProcedureElement, fromIndex: Int, toIndex: Int) -> [Int] {
var indices: [Int] = []
guard fromIndex != toIndex else {
return indices
}
let elements = self.procedure
if toIndex < fromIndex {
for i in toIndex..<fromIndex {
indices.append(i)
let e = elements[i]
let newSequence = i + 1
updateSequence(e, sequence: newSequence)
}
} else {
for i in fromIndex.advanced(by: 1)...toIndex {
indices.append(i)
let e = elements[i]
let newSequence = i - 1
updateSequence(e, sequence: newSequence)
}
}
updateSequence(element, sequence: toIndex)
indices.append(fromIndex)
return indices
}
/// A concatenation of all procedure element commentaries.
var procedureSummary: String {
var text: String = ""
let elements = self.procedureElements
for element in elements {
guard let commentary = element.commentary else {
continue
}
if text == "" {
text.append(commentary)
} else {
#if canImport(ObjectiveC)
text.append(String(format: "\n%@", commentary))
#else
commentary.withCString {
text.append(String(format: "\n%s", $0))
}
#endif
}
}
return text
}
}
// MARK: - Scaling
public extension Recipe {
func scale(by multiplier: Double, measurementSystem: MeasurementSystem? = nil, measurementMethod: MeasurementMethod? = nil) throws -> [FormulaElement] {
let elements = self.formula
if multiplier == 1.0 && measurementSystem == nil && measurementMethod == nil {
return elements
} else if multiplier == 1.0 && measurementSystem == self.unit.measurementSystem && measurementMethod == self.unit.measurementMethod {
return elements
}
var formulaElements = [FormulaElement]()
try elements.forEach { (element) in
let measurement = try element.scale(by: multiplier, measurementSystem: measurementSystem, measurementMethod: measurementMethod)
var formulaElement = element
formulaElement.amount = measurement.amount
formulaElement.unit = measurement.unit
formulaElements.append(formulaElement)
}
return formulaElements
}
func scale(by multiplier: Double, measurementSystemMethod: MeasurementSystemMethod) throws -> [FormulaElement] {
switch measurementSystemMethod {
case .numericQuantity:
return try self.scale(by: multiplier, measurementSystem: .numeric, measurementMethod: .quantity)
case .usVolume:
return try self.scale(by: multiplier, measurementSystem: .us, measurementMethod: .volume)
case .usWeight:
return try self.scale(by: multiplier, measurementSystem: .us, measurementMethod: .weight)
case .metricVolume:
return try self.scale(by: multiplier, measurementSystem: .metric, measurementMethod: .volume)
case .metricWeight:
return try self.scale(by: multiplier, measurementSystem: .metric, measurementMethod: .weight)
}
}
}
| mit | ba3a54f2fa517c329cbcf61da65b8564 | 31.471264 | 156 | 0.592301 | 4.891775 | false | false | false | false |
wupingzj/YangRepoApple | QiuTuiJian/QiuTuiJian/Utils.swift | 1 | 856 | //
// Utils.swift
// QiuTuiJian
//
// Created by Ping on 19/09/2014.
// Copyright (c) 2014 Yang Ltd. All rights reserved.
//
import Foundation
import UIKit
let utils = Utils()
public class Utils {
private let osVersion = UIDevice.currentDevice().systemVersion
// Singleton
public class var sharedInstance : Utils {
return utils
}
func displaySystemInfo() {
let currentDevice = UIDevice.currentDevice()
println("systemVersion=\(currentDevice.systemVersion)")
println("systemName=\(currentDevice.systemName)")
println("model=\(currentDevice.model)")
}
func isIOS703() -> Bool {
return osVersion == "7.0.3"
}
func isIOS71() -> Bool {
return osVersion == "7.1"
}
func isIOS80() -> Bool {
return osVersion == "8.0"
}
} | gpl-2.0 | cc3b405f486bde308143359417bfad30 | 20.974359 | 66 | 0.601636 | 4.367347 | false | false | false | false |
getsocial-im/getsocial-ios-sdk | example/GetSocialDemo/Views/UIDesign.swift | 1 | 1695 | enum UIDesign {
enum Colors {
// label color
static let label: UIColor = {
if #available(iOS 13.0, *) {
return UIColor.label
}
return UIColor.black
}()
// label input
static let inputText: UIColor = {
if #available(iOS 13.0, *) {
return UIColor.darkText
}
return UIColor.black
}()
// view background color
static let viewBackground: UIColor = {
if #available(iOS 13.0, *) {
return UIColor.systemBackground
}
return UIColor.white
}()
}
}
extension UIStackView {
func addFormRow(elements: [UIView]) {
let row = UIStackView()
row.axis = .horizontal
row.alignment = .firstBaseline
elements.forEach {
row.addArrangedSubview($0)
}
NSLayoutConstraint.activate([
elements.first!.widthAnchor.constraint(equalToConstant: 120)
])
self.addArrangedSubview(row)
}
}
extension UIViewController {
func install(_ child: UIViewController, inside: UIView? = nil) {
addChild(child)
child.view.translatesAutoresizingMaskIntoConstraints = false
guard let viewEmbedInto = inside == nil ? self.view : inside else {
return
}
viewEmbedInto.addSubview(child.view)
NSLayoutConstraint.activate([
child.view.leadingAnchor.constraint(equalTo: viewEmbedInto.leadingAnchor),
child.view.trailingAnchor.constraint(equalTo: viewEmbedInto.trailingAnchor),
child.view.topAnchor.constraint(equalTo: viewEmbedInto.topAnchor),
child.view.bottomAnchor.constraint(equalTo: viewEmbedInto.bottomAnchor)
])
child.didMove(toParent: self)
}
}
| apache-2.0 | 4ccda35cc36aa70bda708123bb113555 | 25.904762 | 79 | 0.640118 | 4.32398 | false | false | false | false |
exis-io/swiftRiffleCocoapod | Pod/Classes/Persistence.swift | 1 | 3741 | //
// Persistence.swift
// Pods
//
// Created by damouse on 4/25/16.
//
//
import Foundation
public protocol Persistable {
func modelName() -> String
func getId() -> UInt64
static func modelName() -> String
static func getManager() -> ModelManager?
}
extension Model: Persistable {
public func getId() -> UInt64 {
return _xsid
}
public func modelName() -> String {
let fullNameArr = "\(self.dynamicType)".characters.split{$0 == "."}.map(String.init)
return fullNameArr[fullNameArr.count - 1]
}
public static func modelName() -> String {
return "\(self)"
}
public static func getManager() -> ModelManager? {
return Model.manager
}
}
// Core-based persistence
extension Model {
static var manager: ModelManager!
static func setConnection(app: AppDomain) {
manager = ModelManager(app: app.app)
}
static func ready() -> Bool {
return manager != nil
}
public class func count() -> OneDeferred<Int> {
let r = OneDeferred<Int>()
manager.callCore("Count", deferred: r, args: ["\(self)"])
return r
}
public func create() -> Deferred {
return Model.manager.callCore("Create", args: [modelName(), self.serialize()])
}
public func destroy() -> Deferred {
return Model.manager.callCore("Destroy", args: [modelName(), String(self._xsid)])
}
public class func find<T: CollectionType where T.Generator.Element: Model>(query: [String: Any]) -> OneDeferred<T>! {
let r = OneDeferred<T>()
// OSX Final
// let q = jsonRepack(query)!
var q: [String: Any] = [:]
for (k, v) in query { q[k] = switchTypes(v) }
manager.callCore("Find", deferred: r, args: [modelName(), q])
return r
}
public class func all<T: CollectionType where T.Generator.Element: Model>() -> OneDeferred<T>! {
return find([:])
}
public func save() -> Deferred {
return Model.manager.callCore("Save", args: [modelName(), self.serialize()])
}
}
// Allow some operations to be perfromed on collections of models
extension CollectionType where Generator.Element: Convertible, Generator.Element: Persistable {
public func save() -> Deferred {
let manager = Generator.Element.getManager()!
let name = Generator.Element.modelName()
let serialized = self.map { $0.serialize() }
return manager.callCore("SaveMany", args: [name, serialized])
}
public func destroy() -> Deferred {
let manager = Generator.Element.getManager()!
let name = Generator.Element.modelName()
let serialized = self.map { String($0.getId()) }
return manager.callCore("DestroyMany", args: [name, serialized])
}
public func create() -> Deferred {
let manager = Generator.Element.getManager()!
let name = Generator.Element.modelName()
let serialized = self.map { $0.serialize() }
return manager.callCore("CreateMany", args: [name, serialized])
}
}
// Allow models to be compared through their hidden id
extension Model: Equatable {}
public func ==(lhs: Model, rhs: Model) -> Bool {
return lhs._xsid == rhs._xsid
}
// Crust represnentation of the model manager
public class ModelManager: CoreClass {
init(app: CoreApp) {
super.init()
sendCore("InitModels", address: address, object: app.address, args: [], synchronous: false)
}
}
// guard let m = manager else { Riffle.warn("Cannot access model object persistence without a connection! Instantiate an AppDomain first!"); return nil }
| mit | 014918c79bb8bcfe3e7ad945953de457 | 26.507353 | 153 | 0.611601 | 4.246311 | false | false | false | false |
tdgunes/NetKit | NetKit.swift | 1 | 27394 |
// var nkit = NetKit() // (async=true) optional
// var nkit = NetKit(baseURL:”http://google.com/”)
// HTTP Method
// nkit.request(type:.POST,
// nkit.addHeader(“Content-Type, “application/json”)
// nkit.post(url:“/api/associated/”, headers: ["Content-Type":"application/json"], data:: // optional
// nkit.put
// nkit.delete
// nkit.get
// HTTP_511_NETWORK_AUTHENTICATION_REQUIRED = 511
enum HTTPMethod: String {
case POST = "POST"
case DELETE = "DELETE"
case GET = "GET"
case PUT = "PUT"
}
enum HTTPStatus: Int {
case Continue = 100
case SwitchingProtocols = 101
case Processing = 102
// Success
case OK = 200
case Created = 201
case Accepted = 202
case NonAuthoritativeInformation = 203
case NoContent = 204
case ResetContent = 205
case PartialContent = 206
case MultiStatus = 207
case AlreadyReported = 208
case IMUsed = 226
// Redirections
case MultipleChoices = 300
case MovedPermanently = 301
case Found = 302
case SeeOther = 303
case NotModified = 304
case UseProxy = 305
case SwitchProxy = 306
case TemporaryRedirect = 307
case PermanentRedirect = 308
// Client Errors
case BadRequest = 400
case Unauthorized = 401
case PaymentRequired = 402
case Forbidden = 403
case NotFound = 404
case MethodNotAllowed = 405
case NotAcceptable = 406
case ProxyAuthenticationRequired = 407
case RequestTimeout = 408
case Conflict = 409
case Gone = 410
case LengthRequired = 411
case PreconditionFailed = 412
case RequestEntityTooLarge = 413
case RequestURITooLong = 414
case UnsupportedMediaType = 415
case RequestedRangeNotSatisfiable = 416
case ExpectationFailed = 417
case ImATeapot = 418
case AuthenticationTimeout = 419
case UnprocessableEntity = 422
case Locked = 423
case FailedDependency = 424
case UpgradeRequired = 426
case PreconditionRequired = 428
case TooManyRequests = 429
case RequestHeaderFieldsTooLarge = 431
case LoginTimeout = 440
case NoResponse = 444
case RetryWith = 449
case UnavailableForLegalReasons = 451
case RequestHeaderTooLarge = 494
case CertError = 495
case NoCert = 496
case HTTPToHTTPS = 497
case TokenExpired = 498
case ClientClosedRequest = 499
// Server Errors
case InternalServerError = 500
case NotImplemented = 501
case BadGateway = 502
case ServiceUnavailable = 503
case GatewayTimeout = 504
case HTTPVersionNotSupported = 505
case VariantAlsoNegotiates = 506
case InsufficientStorage = 507
case LoopDetected = 508
case BandwidthLimitExceeded = 509
case NotExtended = 510
case NetworkAuthenticationRequired = 511
case NetworkTimeoutError = 599
}
enum NKError: Int {
case MalformedURL = 0
case HasNSError = 1
}
enum NKContentType: String {
//common aplication content types
case JSON = "application/json"
case XML = "application/xml"
case ZIP = "application/zip"
case GZIP = "application/gzip"
case PDF = "application/pdf"
//common image content types
case JPEG = "image/jpeg"
case PNG = "image/png"
case TIFF = "image/tiff"
case BMP = "image/bmp"
case GIF = "image/gif"
//common audio content types
case MP4Audio = "audio/mp4"
case OGG = "audio/ogg"
case FLAC = "audio/flac"
case WEBMAudio = "audio/webm"
//common text content types
case HTML = "text/html"
case JAVASCRIPT = "text/javascript"
case PLAIN = "text/plain"
case RTF = "text/rtf"
case XMLText = "text/xml"
case CSV = "text/csv"
//common video content types
case AVI = "video/avi"
case MPEG = "video/mpeg"
case MP4Video = "video/mp4"
case QuickTime = "video/quicktime"
case WEBMVideo = "video/webm"
}
protocol NKDelegate {
func didFailed(nkerror:NKError, nserror:NSError?)
func didSucceed(response:NKResponse)
func progress(percent:Float)
}
typealias CompletionHandler = (NKResponse)->()
typealias ErrorHandler = (NKError, NSError?)->()
typealias Progress = (percent:Float)->()
class NKResponse {
var json: JSON?
var status: HTTPStatus?
var data: NSMutableData?
var string: String?
}
class NetKit: HTTPLayerDelegate {
var baseURL: String
var timeoutInterval = 20.0 //seconds
var delegate: NKDelegate?
init(baseURL: String) {
self.baseURL = baseURL
}
init(){
self.baseURL = ""
}
func request(type: HTTPMethod, url: String?=nil, data: AnyObject? = nil, headers: [String:String]?=nil, completionHandler: CompletionHandler? = nil, errorHandler: ErrorHandler? = nil,progress: Progress? = nil) {
var fullURL = self.getFullURL(url)
switch type {
case .POST:
self.post(data: data, url:url, headers:headers, completionHandler: completionHandler, errorHandler: errorHandler, progress: progress)
break
case .PUT:
self.put(data: data, url:url, headers:headers, completionHandler: completionHandler, errorHandler: errorHandler, progress: progress)
break
case .GET:
self.get(url: url, headers:headers, completionHandler: completionHandler, errorHandler: errorHandler, progress: progress)
break
case .DELETE:
self.delete(url: url, headers:headers, completionHandler: completionHandler, errorHandler: errorHandler, progress: progress)
break
}
}
func put(data: AnyObject? = nil, url: String?=nil, headers: [String:String]?=nil, completionHandler: CompletionHandler? = nil, errorHandler: ErrorHandler? = nil,progress: Progress? = nil) {
var fullURL = self.getFullURL(url)
if let request = self.generateURLRequest(fullURL, method: HTTPMethod.POST) {
self.setHeaders(request, headers)
if let concreteData: AnyObject = data {
if let type = self.detectDataType(concreteData) {
self.setContentType(request, type)
}
request.HTTPBody = concreteData.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)
}
var httpLayer = HTTPLayer(completionHandler, errorHandler, progress)
httpLayer.delegate = self
httpLayer.request(request)
}
}
func get(url: String?=nil, headers: [String:String]?=nil, completionHandler: CompletionHandler? = nil, errorHandler: ErrorHandler? = nil,progress: Progress? = nil) {
var fullURL = self.getFullURL(url)
if let request = self.generateURLRequest(fullURL, method: HTTPMethod.GET) {
self.setHeaders(request, headers)
var httpLayer = HTTPLayer(completionHandler, errorHandler, progress)
httpLayer.delegate = self
httpLayer.request(request)
}
}
func post(data: AnyObject? = nil, url: String?=nil, headers: [String:String]?=nil, completionHandler: CompletionHandler? = nil, errorHandler: ErrorHandler? = nil,progress: Progress? = nil) { //contentType, postData
var fullURL = self.getFullURL(url)
println("FullURL=\(fullURL)")
if let request = self.generateURLRequest(fullURL, method: HTTPMethod.POST) {
// self.setHeaders(request, headers)
// if let concreteData: AnyObject = data {
// if let type = self.detectDataType(concreteData) {
// self.setContentType(request, type)
// }
if let json = data! as? JSON {
let text = json.toString(pretty: true) as String
println("BODY=\(text)")
let data = text.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)! as NSData
request.HTTPBody = data
request.setValue("application/json", forHTTPHeaderField:"Content-Type")
}
// else {
// request.HTTPBody = concreteData.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)
// }
// }
var httpLayer = HTTPLayer(completionHandler, errorHandler, progress)
httpLayer.delegate = self
httpLayer.request(request)
}
}
func delete(url: String?=nil, headers: [String:String]?=nil, completionHandler: CompletionHandler? = nil, errorHandler: ErrorHandler? = nil, progress: Progress? = nil) {
var fullURL = self.getFullURL(url)
if let request = self.generateURLRequest(fullURL, method: HTTPMethod.DELETE) {
self.setHeaders(request, headers)
var httpLayer = HTTPLayer(completionHandler, errorHandler, progress)
httpLayer.delegate = self
httpLayer.request(request)
}
}
// MARK: HTTPLayerDelegate functions
func requestDidFinish(response:NKResponse) {
self.delegate?.didSucceed(response)
}
func requestFailWithError(error:NSError) {
self.delegate?.didFailed(.HasNSError, nserror:error)
}
func progress(percent: Float) {
self.delegate?.progress(percent)
}
private func getFullURL(url: String?) -> String {
if let concreteURL = url {
return self.baseURL + concreteURL
}
return self.baseURL
}
private func setHeaders(request:NSMutableURLRequest, _ headers: [String:String]? ) {
if let concreteHeaders = headers {
for (key,value) in concreteHeaders {
request.setValue(value, forHTTPHeaderField: key)
}
}
}
private func setContentType(request: NSMutableURLRequest, _ type: NKContentType) {
println("Set content type: \(type.rawValue)")
request.setValue(type.rawValue, forHTTPHeaderField:"Content-Type")
}
private func detectDataType(data: AnyObject) -> NKContentType? {
if let json = data as? JSON {
return NKContentType.JSON
}
return nil
}
private func generateURLRequest(absoluteURL: String, method: HTTPMethod) -> NSMutableURLRequest? {
if let url = NSURL(string: absoluteURL) {
var request = NSMutableURLRequest(URL: url)
request.timeoutInterval = timeoutInterval
request.HTTPMethod = method.rawValue
return request
}
self.delegate?.didFailed(.MalformedURL, nserror:nil)
return nil
}
}
//
// Logger.swift
// GeoPolicy - Socivy
//
// Created by Taha Doğan Güneş on 10/06/15.
// Copyright (c) 2015 Taha Doğan Güneş. All rights reserved.
//
import Foundation
private let _LoggerInstance = Logger()
class Logger {
let DEBUG:Bool = true
func log(object:AnyObject, message:String){
if DEBUG {
println("[\(object)] \(message)")
}
}
class var sharedInstance: Logger {
return _LoggerInstance
}
}
//
// LowLevelLayer.swift
// GeoPolicy - Socivy
//
// Created by Taha Doğan Güneş on 10/06/15.
// Copyright (c) 2015 Taha Doğan Güneş. All rights reserved.
//
protocol HTTPLayerDelegate {
func requestFailWithError(error:NSError)
func requestDidFinish(response:NKResponse)
func progress(percent:Float)
}
class HTTPLayer: NSObject, NSURLConnectionDelegate, NSURLConnectionDataDelegate {
var responseData : NSMutableData = NSMutableData()
var delegate: HTTPLayerDelegate?
var completionHandler: CompletionHandler?
var errorHandler: ErrorHandler?
var progress: Progress?
var status: HTTPStatus?
var expectedDownloadSize: Int?
init(_ completionHandler: CompletionHandler?, _ errorHandler: ErrorHandler?, _ progress: Progress?) {
self.completionHandler = completionHandler
self.errorHandler = errorHandler
self.progress = progress
}
func request(urlRequest:NSMutableURLRequest){
urlRequest.setValue("", forHTTPHeaderField: "Accept-Encoding")
let conn = NSURLConnection(request:urlRequest, delegate: self, startImmediately: true)
}
func connection(connection: NSURLConnection, didReceiveResponse response: NSURLResponse) {
responseData = NSMutableData()
let httpResponse = response as! NSHTTPURLResponse
status = HTTPStatus(rawValue: httpResponse.statusCode)
NSLog("%@", httpResponse.allHeaderFields)
if status == .OK {
self.expectedDownloadSize = Int(httpResponse.expectedContentLength)
println("NKit: Expected Download Size: \(self.expectedDownloadSize)")
}
}
func connection(connection: NSURLConnection, didReceiveData data: NSData) {
responseData.appendData(data)
if let expectedSize = self.expectedDownloadSize {
println("NKit: responseData length \(self.responseData.length)")
let percent = Float(self.responseData.length) / Float(expectedSize)
self.delegate?.progress(percent)
if let handler = self.progress {
handler(percent: percent)
}
}
}
func connectionDidFinishLoading(connection: NSURLConnection) {
var response = NKResponse()
response.status = self.status
response.data = responseData
if let string = NSString(data: responseData, encoding: NSUTF8StringEncoding) {
response.string = string as String
let json = JSON.loads(response.string!)
if !json.isError {
response.json = json
}
}
self.delegate?.requestDidFinish(response)
if let handler = self.completionHandler {
handler(response)
}
}
func connection(connection: NSURLConnection, didFailWithError error: NSError) {
self.delegate?.requestFailWithError(error)
if let handler = self.errorHandler {
handler(.HasNSError, error)
}
}
}
//
// NetworkLibrary.swift
// GeoPolicy - Socivy
//
// Created by Taha Doğan Güneş on 10/06/15.
// Copyright (c) 2015 Taha Doğan Güneş. All rights reserved.
//
//
// JSON.swift
// GeoPolicy
//
// Created by Taha Doğan Güneş on 10/06/15.
// Copyright (c) 2015 Taha Doğan Güneş. All rights reserved.
//
//
// APITools.swift
// OzU Carpool
//
// Created by Taha Doğan Güneş on 08/10/14.
// Copyright (c) 2014 TDG. All rights reserved.
//
import Foundation
import UIKit
//
// json.swift
// json
//
// Created by Dan Kogai on 7/15/14.
// Copyright (c) 2014 Dan Kogai. All rights reserved.
/// init
public class JSON {
private let _value:AnyObject
/// pass the object that was returned from
/// NSJSONSerialization
public init(_ obj:AnyObject) { self._value = obj }
/// pass the JSON object for another instance
public init(_ json:JSON){ self._value = json._value }
}
/// class properties
extension JSON {
public typealias NSNull = Foundation.NSNull
public typealias NSError = Foundation.NSError
public class var null:NSNull { return NSNull() }
/// constructs JSON object from string
public convenience init(string:String) {
var err:NSError?
let enc:NSStringEncoding = NSUTF8StringEncoding
var obj:AnyObject? = NSJSONSerialization.JSONObjectWithData(
string.dataUsingEncoding(enc)!, options:nil, error:&err
)
self.init(err != nil ? err! : obj!)
}
/// parses string to the JSON object
/// same as JSON(string:String)
public class func parse(string:String)->JSON {
return JSON(string:string)
}
public class func loads(string:String)->JSON {
return JSON(string:string)
}
/// constructs JSON object from the content of NSURL
public convenience init(nsurl:NSURL) {
var enc:NSStringEncoding = NSUTF8StringEncoding
var err:NSError?
let str:String? =
NSString(
contentsOfURL:nsurl, usedEncoding:&enc, error:&err
) as String?
if err != nil { self.init(err!) }
else { self.init(string:str!) }
}
/// fetch the JSON string from NSURL and parse it
/// same as JSON(nsurl:NSURL)
public class func fromNSURL(nsurl:NSURL) -> JSON {
return JSON(nsurl:nsurl)
}
/// constructs JSON object from the content of URL
public convenience init(url:String) {
if let nsurl = NSURL(string:url) as NSURL? {
self.init(nsurl:nsurl)
} else {
self.init(NSError(
domain:"JSONErrorDomain",
code:400,
userInfo:[NSLocalizedDescriptionKey: "malformed URL"]
)
)
}
}
/// fetch the JSON string from URL in the string
public class func fromURL(url:String) -> JSON {
return JSON(url:url)
}
/// does what JSON.stringify in ES5 does.
/// when the 2nd argument is set to true it pretty prints
public class func stringify(obj:AnyObject, pretty:Bool=false) -> String! {
if !NSJSONSerialization.isValidJSONObject(obj) {
JSON(NSError(
domain:"JSONErrorDomain",
code:422,
userInfo:[NSLocalizedDescriptionKey: "not an JSON object"]
))
return nil
}
return JSON(obj).toString(pretty:pretty)
}
}
/// instance properties
extension JSON {
/// access the element like array
public subscript(idx:Int) -> JSON {
switch _value {
case let err as NSError:
return self
case let ary as NSArray:
if 0 <= idx && idx < ary.count {
return JSON(ary[idx])
}
return JSON(NSError(
domain:"JSONErrorDomain", code:404, userInfo:[
NSLocalizedDescriptionKey:
"[\(idx)] is out of range"
]))
default:
return JSON(NSError(
domain:"JSONErrorDomain", code:500, userInfo:[
NSLocalizedDescriptionKey: "not an array"
]))
}
}
/// access the element like dictionary
public subscript(key:String)->JSON {
switch _value {
case let err as NSError:
return self
case let dic as NSDictionary:
if let val:AnyObject = dic[key] { return JSON(val) }
return JSON(NSError(
domain:"JSONErrorDomain", code:404, userInfo:[
NSLocalizedDescriptionKey:
"[\"\(key)\"] not found"
]))
default:
return JSON(NSError(
domain:"JSONErrorDomain", code:500, userInfo:[
NSLocalizedDescriptionKey: "not an object"
]))
}
}
/// access json data object
public var data:AnyObject? {
return self.isError ? nil : self._value
}
/// Gives the type name as string.
/// e.g. if it returns "Double"
/// .asDouble returns Double
public var type:String {
switch _value {
case is NSError: return "NSError"
case is NSNull: return "NSNull"
case let o as NSNumber:
switch String.fromCString(o.objCType)! {
case "c", "C": return "Bool"
case "q", "l", "i", "s": return "Int"
case "Q", "L", "I", "S": return "UInt"
default: return "Double"
}
case is NSString: return "String"
case is NSArray: return "Array"
case is NSDictionary: return "Dictionary"
default: return "NSError"
}
}
/// check if self is NSError
public var isError: Bool { return _value is NSError }
/// check if self is NSNull
public var isNull: Bool { return _value is NSNull }
/// check if self is Bool
public var isBool: Bool { return type == "Bool" }
/// check if self is Int
public var isInt: Bool { return type == "Int" }
/// check if self is UInt
public var isUInt: Bool { return type == "UInt" }
/// check if self is Double
public var isDouble: Bool { return type == "Double" }
/// check if self is any type of number
public var isNumber: Bool {
if let o = _value as? NSNumber {
let t = String.fromCString(o.objCType)!
return t != "c" && t != "C"
}
return false
}
/// check if self is String
public var isString: Bool { return _value is NSString }
/// check if self is Array
public var isArray: Bool { return _value is NSArray }
/// check if self is Dictionary
public var isDictionary: Bool { return _value is NSDictionary }
/// check if self is a valid leaf node.
public var isLeaf: Bool {
return !(isArray || isDictionary || isError)
}
/// gives NSError if it holds the error. nil otherwise
public var asError:NSError? {
return _value as? NSError
}
/// gives NSNull if self holds it. nil otherwise
public var asNull:NSNull? {
return _value is NSNull ? JSON.null : nil
}
/// gives Bool if self holds it. nil otherwise
public var asBool:Bool? {
switch _value {
case let o as NSNumber:
switch String.fromCString(o.objCType)! {
case "c", "C": return Bool(o.boolValue)
default:
return nil
}
default: return nil
}
}
/// gives Int if self holds it. nil otherwise
public var asInt:Int? {
switch _value {
case let o as NSNumber:
switch String.fromCString(o.objCType)! {
case "c", "C":
return nil
default:
return Int(o.longLongValue)
}
default: return nil
}
}
/// gives Double if self holds it. nil otherwise
public var asDouble:Double? {
switch _value {
case let o as NSNumber:
switch String.fromCString(o.objCType)! {
case "c", "C":
return nil
default:
return Double(o.doubleValue)
}
default: return nil
}
}
// an alias to asDouble
public var asNumber:Double? { return asDouble }
/// gives String if self holds it. nil otherwise
public var asString:String? {
switch _value {
case let o as NSString:
return o as String
default: return nil
}
}
/// if self holds NSArray, gives a [JSON]
/// with elements therein. nil otherwise
public var asArray:[JSON]? {
switch _value {
case let o as NSArray:
var result = [JSON]()
for v:AnyObject in o { result.append(JSON(v)) }
return result
default:
return nil
}
}
public var asStringArray:[String]? {
if let array = self.asArray{
var result:[String] = []
for i in array {
if let item = i.asString{
result.append(item)
}
else{
return nil
}
}
return result
}
return nil
}
/// if self holds NSDictionary, gives a [String:JSON]
/// with elements therein. nil otherwise
public var asDictionary:[String:JSON]? {
switch _value {
case let o as NSDictionary:
var result = [String:JSON]()
for (k:AnyObject, v:AnyObject) in o {
result[k as! String] = JSON(v)
}
return result
default: return nil
}
}
/// Yields date from string
public var asDate:NSDate? {
if let dateString = _value as? NSString {
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZZZZ"
return dateFormatter.dateFromString(dateString as String)
}
return nil
}
/// gives the number of elements if an array or a dictionary.
/// you can use this to check if you can iterate.
public var length:Int {
switch _value {
case let o as NSArray: return o.count
case let o as NSDictionary: return o.count
default: return 0
}
}
}
extension JSON : SequenceType {
public func generate()->GeneratorOf<(AnyObject,JSON)> {
switch _value {
case let o as NSArray:
var i = -1
return GeneratorOf<(AnyObject, JSON)> {
if ++i == o.count { return nil }
return (i, JSON(o[i]))
}
case let o as NSDictionary:
var ks = o.allKeys.reverse()
return GeneratorOf<(AnyObject, JSON)> {
if ks.isEmpty { return nil }
let k = ks.removeLast() as! String
return (k, JSON(o.valueForKey(k)!))
}
default:
return GeneratorOf<(AnyObject, JSON)>{ nil }
}
}
public func mutableCopyOfTheObject() -> AnyObject {
return _value.mutableCopy()
}
}
extension JSON : Printable {
/// stringifies self.
/// if pretty:true it pretty prints
public func dataUsingEncoding(encoding:NSStringEncoding, allowLossyConversion: Bool) -> NSData? {
let text = self.toString(pretty: false)
return text.dataUsingEncoding(encoding, allowLossyConversion: allowLossyConversion)
}
public func toString(pretty:Bool=false)->String {
switch _value {
case is NSError: return "\(_value)"
case is NSNull: return "null"
case let o as NSNumber:
switch String.fromCString(o.objCType)! {
case "c", "C":
return o.boolValue.description
case "q", "l", "i", "s":
return o.longLongValue.description
case "Q", "L", "I", "S":
return o.unsignedLongLongValue.description
default:
switch o.doubleValue {
case 0.0/0.0: return "0.0/0.0" // NaN
case -1.0/0.0: return "-1.0/0.0" // -infinity
case +1.0/0.0: return "+1.0/0.0" // infinity
default:
return o.doubleValue.description
}
}
case let o as NSString:
return o.debugDescription
default:
let opts = pretty
? NSJSONWritingOptions.PrettyPrinted : nil
if let data = NSJSONSerialization.dataWithJSONObject(
_value, options:opts, error:nil
) as NSData? {
if let nsstring = NSString(
data:data, encoding:NSUTF8StringEncoding
) as NSString? {
return nsstring as String
}
}
return "YOU ARE NOT SUPPOSED TO SEE THIS!"
}
}
public var description:String { return toString() }
}
| mit | 5dd14e060dc2bb22421a91164425098c | 30.954439 | 218 | 0.592147 | 4.573315 | false | false | false | false |
CoolCodeFactory/Antidote | AntidoteArchitectureExample/UserFlowCoordinator.swift | 1 | 14366 | //
// UserFlowCoordinator.swift
// AntidoteArchitectureExample
//
// Created by Dmitriy Utmanov on 16/09/16.
// Copyright © 2016 Dmitry Utmanov. All rights reserved.
//
import UIKit
class UserFlowCoordinator: CoordinatorProtocol {
var childCoordinators: [CoordinatorProtocol] = []
weak var navigationController: NavigationViewController!
var closeHandler: () -> () = { fatalError() }
let viewControllersFactory = UserViewControllersFactory()
func start(animated: Bool) {
fatalError()
}
@objc func end(_ sender: UIBarButtonItem) {
fatalError()
}
func finish(animated: Bool) {
fatalError()
}
fileprivate func presentUserViewController(withName name: String) {
fatalError()
}
}
class UserModalFlowCoordinator: UserFlowCoordinator, ModalCoordinatorProtocol {
weak var presentingViewController: UIViewController!
required init(presentingViewController: UIViewController) {
self.presentingViewController = presentingViewController
}
override func start(animated: Bool) {
let viewController = viewControllersFactory.usersTableViewController()
viewController.navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(end(_:)))
viewController.selectUserHandler = { [unowned self] name in
self.presentUserViewController(withName: name)
}
let navVC = viewControllersFactory.navigationController()
navVC.setViewControllers([viewController], animated: false)
presentingViewController.present(navVC, animated: true, completion: nil)
navigationController = navVC
}
override func finish(animated: Bool) {
removeAllChildCoordinators()
navigationController.dismiss(animated: animated, completion: nil)
let alertController = UIAlertController(title: "Finished!", message: "\(String(describing: self)) did finish", preferredStyle: UIAlertControllerStyle.alert)
let defaultAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: nil)
alertController.addAction(defaultAction)
presentingViewController.present(alertController, animated: true, completion: nil)
}
@objc override func end(_ sender: UIBarButtonItem) {
closeHandler()
}
fileprivate override func presentUserViewController(withName name: String) {
let viewController = viewControllersFactory.userViewController(withName: name)
navigationController?.pushViewController(viewController, animated: true)
}
}
class UserNavigationFlowCoordinator: UserFlowCoordinator, NavigationCoordinatorProtocol {
weak var presentingNavigationController: NavigationViewController!
required init(presentingNavigationController: NavigationViewController) {
self.presentingNavigationController = presentingNavigationController
}
override func start(animated: Bool) {
let viewController = viewControllersFactory.usersTableViewController()
viewController.controllerCloseHandler = { [unowned self] in
self.closeHandler()
}
viewController.selectUserHandler = { [unowned self] name in
self.presentUserViewController(withName: name)
}
presentingNavigationController.pushViewController(viewController, animated: animated)
}
override func finish(animated: Bool) {
removeAllChildCoordinators()
let alertController = UIAlertController(title: "Finished!", message: "\(String(describing: self)) did finish", preferredStyle: UIAlertControllerStyle.alert)
let defaultAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: nil)
alertController.addAction(defaultAction)
presentingNavigationController.present(alertController, animated: true, completion: nil)
}
@objc override func end(_ sender: UIBarButtonItem) {
closeHandler()
}
fileprivate override func presentUserViewController(withName name: String) {
let viewController = viewControllersFactory.userViewController(withName: name)
presentingNavigationController?.pushViewController(viewController, animated: true)
}
}
class UserMasterDetailFlowCoordinator: UserFlowCoordinator, MasterDetailCoordinatorProtocol {
weak var splitViewController: UISplitViewController!
required init(splitViewController: UISplitViewController) {
self.splitViewController = splitViewController
}
override func start(animated: Bool) {
let viewController = viewControllersFactory.usersTableViewController()
viewController.navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(end(_:)))
viewController.selectUserHandler = { [unowned self] name in
self.presentUserViewController(withName: name)
}
let navVC = viewControllersFactory.navigationController()
navVC.setViewControllers([viewController], animated: false)
splitViewController.viewControllers = [navVC]
}
override func finish(animated: Bool) {
removeAllChildCoordinators()
let alertController = UIAlertController(title: "Finished!", message: "\(String(describing: self)) did finish", preferredStyle: UIAlertControllerStyle.alert)
let defaultAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: nil)
alertController.addAction(defaultAction)
splitViewController.presentingViewController?.present(alertController, animated: true, completion: nil)
}
@objc override func end(_ sender: UIBarButtonItem) {
closeHandler()
}
fileprivate override func presentUserViewController(withName name: String) {
let viewController = viewControllersFactory.userViewController(withName: name)
let navVC = viewControllersFactory.navigationController()
navVC.setViewControllers([viewController], animated: false)
splitViewController.showDetailViewController(navVC, sender: nil)
}
}
class UserPageBasedFlowCoordinator: UserFlowCoordinator, PageBasedCoordinatorProtocol {
weak var pageViewController: PageBasedViewController!
required init(pageViewController: PageBasedViewController) {
self.pageViewController = pageViewController
}
override func start(animated: Bool) {
let viewController = viewControllersFactory.usersTableViewController()
pageViewController.navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(end(_:)))
viewController.selectUserHandler = { [unowned self] name in
self.presentUserViewController(withName: name)
}
if var viewControllers = pageViewController.viewControllers {
viewControllers.append(viewController)
pageViewController.setViewControllers(viewControllers)
} else {
pageViewController.setViewControllers([viewController])
}
}
override func finish(animated: Bool) {
removeAllChildCoordinators()
let alertController = UIAlertController(title: "Finished!", message: "\(String(describing: self)) did finish", preferredStyle: UIAlertControllerStyle.alert)
let defaultAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: nil)
alertController.addAction(defaultAction)
pageViewController.presentingViewController?.present(alertController, animated: true, completion: nil)
}
@objc override func end(_ sender: UIBarButtonItem) {
closeHandler()
}
fileprivate override func presentUserViewController(withName name: String) {
let viewController = viewControllersFactory.userViewController(withName: name)
viewController.navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(end(_:)))
let viewControllers = pageViewController.viewControllers!
var filteredViewControllers = viewControllers.filter({ (viewController) -> Bool in
return !(viewController is UserViewController)
})
filteredViewControllers.append(viewController)
pageViewController.setViewControllers(filteredViewControllers)
let alertController = UIAlertController(title: "Second page appeared", message: "UserViewController opened in the second page", preferredStyle: UIAlertControllerStyle.alert)
let defaultAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: nil)
alertController.addAction(defaultAction)
pageViewController.present(alertController, animated: true, completion: nil)
}
}
class UserTabbedFlowCoordinator: UserFlowCoordinator, TabbedCoordinatorProtocol {
weak var tabBarController: UITabBarController!
required init(tabBarController: UITabBarController) {
self.tabBarController = tabBarController
}
override func start(animated: Bool) {
let viewController = viewControllersFactory.usersTableViewController()
viewController.navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(end(_:)))
viewController.selectUserHandler = { [unowned self] name in
self.presentUserViewController(withName: name)
}
let navVC = viewControllersFactory.navigationController()
navVC.setViewControllers([viewController], animated: false)
if var viewControllers = tabBarController.viewControllers {
viewControllers.append(navVC)
tabBarController.setViewControllers(viewControllers, animated: false)
} else {
tabBarController.setViewControllers([navVC], animated: false)
}
}
override func finish(animated: Bool) {
removeAllChildCoordinators()
let alertController = UIAlertController(title: "Finished!", message: "\(String(describing: self)) did finish", preferredStyle: UIAlertControllerStyle.alert)
let defaultAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: nil)
alertController.addAction(defaultAction)
tabBarController.presentingViewController?.present(alertController, animated: true, completion: nil)
}
@objc override func end(_ sender: UIBarButtonItem) {
closeHandler()
}
fileprivate override func presentUserViewController(withName name: String) {
let viewController = viewControllersFactory.userViewController(withName: name)
viewController.navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(end(_:)))
let navVC = viewControllersFactory.navigationController()
navVC.setViewControllers([viewController], animated: false)
let viewControllers = tabBarController.viewControllers!
var filteredViewControllers = viewControllers.filter({ (viewController) -> Bool in
guard let navVC = viewController as? NavigationViewController else { return true }
return !(navVC.viewControllers.first is UserViewController)
})
filteredViewControllers.append(navVC)
tabBarController.setViewControllers(filteredViewControllers, animated: false)
let alertController = UIAlertController(title: "Second tab appeared", message: "UserViewController opened in the second tab", preferredStyle: UIAlertControllerStyle.alert)
let defaultAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: nil)
alertController.addAction(defaultAction)
tabBarController.present(alertController, animated: true, completion: nil)
}
}
class UserContainerFlowCoordinator: UserFlowCoordinator, ModalCoordinatorProtocol {
weak var presentingViewController: UIViewController!
required init(presentingViewController: UIViewController) {
self.presentingViewController = presentingViewController
}
override func start(animated: Bool) {
let viewController = viewControllersFactory.userContainerViewController()
viewController.navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(end(_:)))
viewController.usersViewControllerBuilder = { [unowned self, weak viewController] in
let usersTableViewController = self.viewControllersFactory.usersTableViewController()
usersTableViewController.selectUserHandler = { [weak viewController] name in
viewController?.updateUserViewController(name)
}
return usersTableViewController
}
viewController.userViewControllerBuilder = { [unowned self] name in
let userViewController = self.viewControllersFactory.userViewController(withName: name)
return userViewController
}
let navVC = viewControllersFactory.navigationController()
navVC.setViewControllers([viewController], animated: false)
presentingViewController.present(navVC, animated: true, completion: nil)
navigationController = navVC
}
@objc override func end(_ sender: UIBarButtonItem) {
closeHandler()
}
override func finish(animated: Bool) {
removeAllChildCoordinators()
navigationController.dismiss(animated: animated, completion: nil)
let alertController = UIAlertController(title: "Finished!", message: "\(String(describing: self)) did finish", preferredStyle: UIAlertControllerStyle.alert)
let defaultAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: nil)
alertController.addAction(defaultAction)
presentingViewController.present(alertController, animated: true, completion: nil)
}
fileprivate override func presentUserViewController(withName name: String) {
}
}
| mit | cbe48926a20eac305b1edb4383744389 | 41.752976 | 181 | 0.716533 | 6.112766 | false | false | false | false |
mercadopago/px-ios | MercadoPagoSDK/MercadoPagoSDK/UI/PXResult/New UI/PixCode/Views/InstructionReferenceView.swift | 1 | 1961 | import UIKit
final class InstructionReferenceView: UIView {
// MARK: - Private properties
private let titleLabel: UILabel = {
let label = UILabel()
label.font = UIFont.ml_lightSystemFont(ofSize: 16)
label.textAlignment = .left
return label
}()
private let infoLabel: UILabel = {
let label = UILabel()
label.font = UIFont.ml_boldSystemFont(ofSize: 16)
label.textAlignment = .left
label.numberOfLines = 0
return label
}()
private let secondaryInfoStack: UIStackView = {
let stack = UIStackView()
stack.axis = .vertical
stack.spacing = 8
return stack
}()
// MARK: - Initialization
init(reference: PXInstructionReference) {
super.init(frame: .zero)
setupInfos(with: reference)
setupViewConfiguration()
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - Private mmethods
private func setupInfos(with reference: PXInstructionReference) {
titleLabel.text = reference.label
infoLabel.text = reference.getFullReferenceValue()
}
}
extension InstructionReferenceView: ViewConfiguration {
func buildHierarchy() {
addSubviews(views: [titleLabel, infoLabel])
}
func setupConstraints() {
NSLayoutConstraint.activate([
titleLabel.topAnchor.constraint(equalTo: topAnchor),
titleLabel.leadingAnchor.constraint(equalTo: leadingAnchor),
titleLabel.trailingAnchor.constraint(equalTo: trailingAnchor),
infoLabel.topAnchor.constraint(equalTo: titleLabel.bottomAnchor, constant: 8),
infoLabel.leadingAnchor.constraint(equalTo: titleLabel.leadingAnchor),
infoLabel.trailingAnchor.constraint(equalTo: titleLabel.trailingAnchor),
infoLabel.bottomAnchor.constraint(equalTo: bottomAnchor)
])
}
}
| mit | 3e9240cfcbbd690308d00246429efc77 | 30.629032 | 90 | 0.656808 | 5.120104 | false | false | false | false |
mercadopago/px-ios | MercadoPagoSDK/MercadoPagoSDK/Flows/OneTap/UI/PXCreditsViewModel.swift | 1 | 745 | import Foundation
struct PXCreditsViewModel {
let displayInfo: PXDisplayInfoDto
let needsTermsAndConditions: Bool
init(_ withModel: PXOneTapCreditsDto, needsTermsAndConditions: Bool = true) {
self.displayInfo = withModel.displayInfo
self.needsTermsAndConditions = needsTermsAndConditions
}
}
extension PXCreditsViewModel {
func getCardColors() -> [CGColor] {
let defaultColor: CGColor = UIColor.gray.cgColor
guard let gradients = displayInfo.gradientColors else { return [defaultColor, defaultColor] }
var arrayColors: [CGColor] = [CGColor]()
for color in gradients {
arrayColors.append(color.hexToUIColor().cgColor)
}
return arrayColors
}
}
| mit | a728cac6648bfc62f3ba86ffe4dd94af | 31.391304 | 101 | 0.696644 | 4.434524 | false | false | false | false |
clarenceji/Clarence-Ji | Clarence Ji/CJTableView3.swift | 1 | 3594 | //
// CJTableView3.swift
// Clarence Ji
//
// Created by Clarence Ji on 4/16/15.
// Copyright (c) 2015 Clarence Ji. All rights reserved.
//
import UIKit
import MessageUI
class CJTableView3: UITableViewController, UIViewControllerTransitioningDelegate, MFMailComposeViewControllerDelegate {
override func viewDidLoad() {
super.viewDidLoad()
tableView.estimatedRowHeight = 68.0
tableView.rowHeight = UITableViewAutomaticDimension
tableView.tableFooterView = UIView(frame: CGRect.zero)
self.navigationController?.hidesBarsOnSwipe = false
}
override func viewDidAppear(_ animated: Bool) {
navigationController!.setNavigationBarHidden(false, animated: true)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
// Return the number of sections.
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// Return the number of rows in the section.
return 4
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = Bundle.main.loadNibNamed("CJTableView3_Cell", owner: self, options: nil)?[0] as! CJTableView3_Cell
cell.setLabels(indexPath.row)
cell.tableView = self
switch indexPath.row {
case 2, 3:
cell.selectionStyle = .gray
cell.accessoryType = .disclosureIndicator
default:
break
}
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.cellForRow(at: indexPath)?.isSelected = false
switch indexPath.row {
case 2:
self.sendEmail()
case 3:
UIApplication.shared.openURL(URL(string: "http://clarenceji.net")!)
default:
break
}
}
func sendEmail() {
let emailViewController = configuredMailComposeViewController()
if MFMailComposeViewController.canSendMail() {
self.present(emailViewController, animated: true, completion: nil)
} else {
self.showSendMailErrorAlert()
}
}
func configuredMailComposeViewController() -> MFMailComposeViewController {
let mailComposerVC = MFMailComposeViewController()
mailComposerVC.mailComposeDelegate = self // Extremely important to set the --mailComposeDelegate-- property, NOT the --delegate-- property
mailComposerVC.setToRecipients(["[email protected]"])
mailComposerVC.setSubject("Message from Clarence.Ji App")
mailComposerVC.setMessageBody("", isHTML: false)
return mailComposerVC
}
func showSendMailErrorAlert() {
let sendMailErrorAlert = UIAlertController(title: "Cannot Send Email", message: "Please check your email settings and try again.", preferredStyle: .alert)
sendMailErrorAlert.addAction(UIAlertAction(title: "OK", style: .cancel, handler: nil))
self.present(sendMailErrorAlert, animated: true, completion: nil)
}
// MARK: MFMailComposeViewControllerDelegate Method
func mailComposeController(_ controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?) {
controller.dismiss(animated: true, completion: nil)
}
}
| gpl-3.0 | f75f275036b992969264994402cc8b12 | 33.893204 | 162 | 0.667223 | 5.487023 | false | false | false | false |
argon/mas | MasKitTests/ExternalCommands/OpenSystemCommandSpec.swift | 1 | 763 | //
// OpenSystemCommandSpec.swift
// MasKitTests
//
// Created by Ben Chatelain on 2/24/20.
// Copyright © 2020 mas-cli. All rights reserved.
//
@testable import MasKit
import Nimble
import Quick
class OpenSystemCommandSpec: QuickSpec {
override func spec() {
describe("open system command") {
context("binary path") {
it("defaults to the macOS open command") {
let cmd = OpenSystemCommand()
expect(cmd.binaryPath) == "/usr/bin/open"
}
it("can be overridden") {
let cmd = OpenSystemCommand(binaryPath: "/dev/null")
expect(cmd.binaryPath) == "/dev/null"
}
}
}
}
}
| mit | cd6b01a4fbce03d15b685313524dec26 | 25.275862 | 72 | 0.528871 | 4.305085 | false | true | false | false |
leschlogl/Programming-Contests | Hackerrank/Arrays/arraysDs.swift | 1 | 939 | import Foundation
// Complete the reverseArray function below.
func reverseArray(a: [Int]) -> [Int] {
return a.reversed()
}
let stdout = ProcessInfo.processInfo.environment["OUTPUT_PATH"]!
FileManager.default.createFile(atPath: stdout, contents: nil, attributes: nil)
let fileHandle = FileHandle(forWritingAtPath: stdout)!
guard let arrCount = Int((readLine()?.trimmingCharacters(in: .whitespacesAndNewlines))!)
else { fatalError("Bad input") }
guard let arrTemp = readLine() else { fatalError("Bad input") }
let arr: [Int] = arrTemp.split(separator: " ").map {
if let arrItem = Int($0.trimmingCharacters(in: .whitespacesAndNewlines)) {
return arrItem
} else { fatalError("Bad input") }
}
guard arr.count == arrCount else { fatalError("Bad input") }
let res = reverseArray(a: arr)
fileHandle.write(res.map{ String($0) }.joined(separator: " ").data(using: .utf8)!)
fileHandle.write("\n".data(using: .utf8)!)
| mit | 5e4b5156490d02427dc3c776d3f06656 | 32.535714 | 88 | 0.70607 | 3.78629 | false | false | false | false |
Appudo/Appudo.github.io | static/dashs/showcase/c/s/6/19.swift | 1 | 1212 | import libappudo
import libappudo_run
var users : [Int: String] = [Int: String]()
func onConnect(ev : WebSocketEvent) {
let s : Socket = ev.target
let data = ev.data as? String ?? "noname"
if(users[Int(s.value)] != nil) {
_ = ws.send(txt:"\u{7}e,")
s.close()
return
}
if(users.count >= 100) {
_ = ws.send(txt:"\u{7}f,")
s.close()
return
}
ev.set(_monitor:true)
for (id, name) in users {
_ = ws.send(txt:"\u{7}a," + String(describing:id) + "," + name, s)
}
users[Int(s.value)] = data
_ = ws.bc(txt:"\u{7}a," + String(describing:s.value) + "," + data)
}
func onDisconnect(ev : WebSocketEvent) {
let s : Socket = ev.target
_ = ws.bc(txt:"\u{7}r," + String(describing:s.value))
users[Int(s.value)] = nil
}
func onMessage(ev : WebSocketEvent) {
let s : Socket = ev.target
if(ev.isText) {
let data = ev.data as! String;
if(data.characters[data.startIndex] == "\u{7}") {
s.close()
return
}
_ = ws.bc(txt:String(describing:s.value) + ", " + data, ev.target)
} else {
s.close()
}
}
| apache-2.0 | ab1a7ee98d1031d7e8a50cc60d269827 | 22.307692 | 74 | 0.50165 | 3.091837 | false | false | false | false |
steveholt55/Football-College-Trivia-iOS | FootballCollegeTrivia/Model/College.swift | 1 | 3337 | //
// Copyright © 2014-2016 Brandon Jenniges. All rights reserved.
//
import SwiftyJSON
class College: Equatable {
let name: String
let tier: Int
struct CollegeArrays {
static var allColleges:[College]?
static var tierOneColleges:[College]?
static var tierTwoColleges:[College]?
static var tierThreeColleges:[College]?
}
init(json: JSON) {
self.name = json["college"].stringValue
self.tier = json["tier"].intValue
}
// MARK: - JSON loading
static func loadCollegesArray() -> [College] {
let contents: NSString?
do {
contents = try NSString(contentsOfFile: NSBundle.mainBundle().pathForResource("all_colleges", ofType: "txt")!, encoding: NSUTF8StringEncoding)
if let data = contents?.dataUsingEncoding(NSUTF8StringEncoding) {
let json = JSON(data: data)
let colleges = json["colleges"]
var collegesArray = [College]()
for (index: _, subJson: JSON) in colleges {
collegesArray.append(College(json: JSON))
}
return collegesArray
}
} catch _ {
print("error trying load colleges")
}
return [College]()
}
// MARK: - Getters
static func getAllColleges() -> [College] {
if let allColleges = CollegeArrays.allColleges {
return allColleges
}
CollegeArrays.allColleges = loadCollegesArray()
return CollegeArrays.allColleges!
}
static func getTierOneColleges() -> [College] {
if let tierOneColleges = CollegeArrays.tierOneColleges {
return tierOneColleges
}
let colleges = getCollegesForTier(1)
CollegeArrays.tierOneColleges = colleges
return CollegeArrays.tierOneColleges!
}
static func getTierTwoColleges() -> [College] {
if let tierTwoColleges = CollegeArrays.tierTwoColleges {
return tierTwoColleges
}
let colleges = getCollegesForTier(2)
CollegeArrays.tierTwoColleges = colleges
return CollegeArrays.tierTwoColleges!
}
static func getTierThreeColleges() -> [College] {
if let tierThreeColleges = CollegeArrays.tierThreeColleges {
return tierThreeColleges
}
let colleges = getCollegesForTier(3)
CollegeArrays.tierThreeColleges = colleges
return CollegeArrays.tierThreeColleges!
}
// MARK: - Helper methods
static func getCollegesForTier(tier : Int) -> [College] {
let colleges = getAllColleges().filter { (college: College) -> Bool in
return college.tier == tier
}
return colleges
}
static func getCurrentArray(tier: Int) -> [College] {
switch tier {
case 1:
return getTierOneColleges()
case 2:
return getTierTwoColleges()
case 3:
return getTierThreeColleges()
default:
return getTierOneColleges()
}
}
}
// MARK: Equatable
func ==(lhs: College, rhs: College) -> Bool {
return lhs.name == rhs.name && lhs.tier == rhs.tier
}
| mit | 3a07de6fb71c7d7e23b28950c80e4155 | 27.758621 | 154 | 0.578537 | 4.483871 | false | false | false | false |
sugar2010/SwiftOptimizer | swix/oneD/oneD-operators.swift | 2 | 6640 | //
// oneD-functions.swift
// swix
//
// Created by Scott Sievert on 7/9/14.
// Copyright (c) 2014 com.scott. All rights reserved.
//
import Foundation
import Accelerate
func make_operator(lhs:matrix, operator:String, rhs:matrix) -> matrix{
assert(lhs.n == rhs.n, "Sizes must match!")
var array = zeros(lhs.n) // lhs[i], rhs[i]
var arg_b = zeros(lhs.n)
var arg_c = zeros(lhs.n)
// see [1] on how to integrate Swift and accelerate
// [1]:https://github.com/haginile/SwiftAccelerate
var result = zeros(lhs.n)
copy(lhs, result)
var N = lhs.n
if operator=="+"
{cblas_daxpy(N.cint, 1.0.cdouble, !rhs, 1.cint, !result, 1.cint);}
else if operator=="-"
{cblas_daxpy(N.cint, -1.0.cdouble, !rhs, 1.cint, !result, 1.cint);}
else if operator=="*"
{vDSP_vmulD(!lhs, 1, !rhs, 1, !result, 1, vDSP_Length(lhs.grid.count))}
else if operator=="/"
{vDSP_vdivD(!rhs, 1, !lhs, 1, !result, 1, vDSP_Length(lhs.grid.count))}
else if operator=="<" || operator==">" || operator==">=" || operator=="<="{
result = zeros(lhs.n)
CVWrapper.compare(!lhs, with: !rhs, using: operator.nsstring, into: !result, ofLength: lhs.n.cint)
// since opencv uses images which use 8-bit values
result /= 255
}
else {assert(false, "Operator not recongized!")}
return result
}
func make_operator(lhs:matrix, operator:String, rhs:Double) -> matrix{
var array = zeros(lhs.n)
var right = [rhs]
if operator == "%"
{mod_objc(!lhs, rhs, !array, lhs.n.cint);
} else if operator == "*"
{mul_scalar_objc(!lhs, rhs.cdouble, !array, lhs.n.cint)}
else if operator == "+"
{vDSP_vsaddD(!lhs, 1, &right, !array, 1, vDSP_Length(lhs.grid.count))}
else if operator=="/"
{vDSP_vsdivD(!lhs, 1, &right, !array, 1, vDSP_Length(lhs.grid.count))}
else if operator=="-"
{array = make_operator(lhs, "-", ones(lhs.n)*rhs)}
else if operator=="<" || operator==">" || operator=="<=" || operator==">="{
CVWrapper.compare(!lhs, withDouble:rhs.cdouble, using:operator.nsstring, into:!array, ofLength:lhs.n.cint)
array /= 255
}
else {assert(false, "Operator not recongnized! Error with the speedup?")}
return array
}
func make_operator(lhs:Double, operator:String, rhs:matrix) -> matrix{
var array = zeros(rhs.n) // lhs[i], rhs[i]
var l = ones(rhs.n) * lhs
if operator == "*"
{array = make_operator(rhs, "*", lhs)}
else if operator == "+"{
array = make_operator(rhs, "+", lhs)}
else if operator=="-"
{array = -1 * make_operator(rhs, "-", lhs)}
else if operator=="/"{
array = make_operator(l, "/", rhs)}
else if operator=="<"{
array = make_operator(rhs, ">", lhs)}
else if operator==">"{
array = make_operator(rhs, "<", lhs)}
else if operator=="<="{
array = make_operator(rhs, ">=", lhs)}
else if operator==">="{
array = make_operator(rhs, "<=", lhs)}
else {assert(false, "Operator not reconginzed")}
return array
}
// EQUALITY
operator infix ~== {associativity none precedence 140}
func ~== (lhs: matrix, rhs: matrix) -> Bool{
assert(lhs.n == rhs.n, "`+` only works on arrays of equal size")
if max(abs(lhs - rhs)) > 1e-6{
return false
} else{
return true
}
}
func ~== (lhs: matrix, rhs: matrix) -> matrix{
// sees where two matrices are about equal, for use with argwhere
return make_operator(lhs, "~==", rhs)
}
// NICE ARITHMETIC
@assignment func += (inout x: matrix, right: Double){
x = x + right
}
@assignment func *= (inout x: matrix, right: Double){
x = x * right
}
@assignment func -= (inout x: matrix, right: Double){
x = x - right
}
@assignment func /= (inout x: matrix, right: Double){
x = x / right
}
// MOD
operator infix % {associativity none precedence 140}
func % (lhs: matrix, rhs: Double) -> matrix{
return make_operator(lhs, "%", rhs)}
// PLUS
operator infix + {associativity none precedence 140}
func + (lhs: matrix, rhs: matrix) -> matrix{
return make_operator(lhs, "+", rhs)}
func + (lhs: Double, rhs: matrix) -> matrix{
return make_operator(lhs, "+", rhs)}
func + (lhs: matrix, rhs: Double) -> matrix{
return make_operator(lhs, "+", rhs)}
// MINUS
operator infix - {associativity none precedence 140}
func - (lhs: matrix, rhs: matrix) -> matrix{
return make_operator(lhs, "-", rhs)}
func - (lhs: Double, rhs: matrix) -> matrix{
return make_operator(lhs, "-", rhs)}
func - (lhs: matrix, rhs: Double) -> matrix{
return make_operator(lhs, "-", rhs)}
// TIMES
operator infix * {associativity none precedence 140}
func * (lhs: matrix, rhs: matrix) -> matrix{
return make_operator(lhs, "*", rhs)}
func * (lhs: Double, rhs: matrix) -> matrix{
return make_operator(lhs, "*", rhs)}
func * (lhs: matrix, rhs: Double) -> matrix{
return make_operator(lhs, "*", rhs)}
// DIVIDE
operator infix / {associativity none precedence 140}
func / (lhs: matrix, rhs: matrix) -> matrix{
return make_operator(lhs, "/", rhs)
}
func / (lhs: Double, rhs: matrix) -> matrix{
return make_operator(lhs, "/", rhs)}
func / (lhs: matrix, rhs: Double) -> matrix{
return make_operator(lhs, "/", rhs)}
// LESS THAN
operator infix < {associativity none precedence 140}
func < (lhs: matrix, rhs: Double) -> matrix{
return make_operator(lhs, "<", rhs)}
func < (lhs: matrix, rhs: matrix) -> matrix{
return make_operator(lhs, "<", rhs)}
func < (lhs: Double, rhs: matrix) -> matrix{
return make_operator(lhs, "<", rhs)}
// GREATER THAN
operator infix > {associativity none precedence 140}
func > (lhs: matrix, rhs: Double) -> matrix{
return make_operator(lhs, ">", rhs)}
func > (lhs: matrix, rhs: matrix) -> matrix{
return make_operator(lhs, ">", rhs)}
func > (lhs: Double, rhs: matrix) -> matrix{
return make_operator(lhs, ">", rhs)}
// GREATER THAN OR EQUAL
operator infix >= {associativity none precedence 140}
func >= (lhs: matrix, rhs: Double) -> matrix{
return make_operator(lhs, ">=", rhs)}
func >= (lhs: matrix, rhs: matrix) -> matrix{
return make_operator(lhs, ">=", rhs)}
func >= (lhs: Double, rhs: matrix) -> matrix{
return make_operator(lhs, ">=", rhs)}
// LESS THAN OR EQUAL
operator infix <= {associativity none precedence 140}
func <= (lhs: matrix, rhs: Double) -> matrix{
return make_operator(lhs, "<=", rhs)}
func <= (lhs: matrix, rhs: matrix) -> matrix{
return make_operator(lhs, "<=", rhs)}
func <= (lhs: Double, rhs: matrix) -> matrix{
return make_operator(lhs, "<=", rhs)}
| mit | 509df751a8f88d61ed3cc52ec58e146c | 30.619048 | 114 | 0.604066 | 3.356926 | false | false | false | false |
zhiquan911/CHSlideSwitchView | Example/CHSlideSwitchView/HeaderViewNIBViewController.swift | 1 | 2252 | //
// HeaderViewNIBViewController.swift
// CHSlideSwitchView
//
// Created by Chance on 2017/6/9.
// Copyright © 2017年 CocoaPods. All rights reserved.
//
import UIKit
import CHSlideSwitchView
class HeaderViewNIBViewController: UIViewController {
@IBOutlet var slideSwitchView: CHSlideSwitchView!
var colors = [
UIColor.green,
UIColor.black,
UIColor.blue
]
lazy var datas: [CHSlideItem] = {
var items = [CHSlideItem]()
for (i, color) in self.colors.enumerated() {
let item = CHSlideItem(title: "hello", content: CHSlideItemType.viewController({
() -> UIViewController in
let story = UIStoryboard.init(name: "Main", bundle: nil)
let vc = story.instantiateViewController(withIdentifier: "DemoNIBViewController") as! DemoNIBViewController
return vc
}))
items.append(item)
}
return items
}()
override func viewDidLoad() {
super.viewDidLoad()
self.slideSwitchView.delegate = self
self.slideSwitchView.headerView?.selectedStyle = .line(color: UIColor.red, height: 2.5)
self.slideSwitchView.slideItems = self.datas
}
@IBAction func handleUpdateTabPress(sender: AnyObject?) {
self.slideSwitchView.headerView?.updateTab(at: 1, block: {
(view, item) -> CHSlideItem in
let btn = view as! UIButton
item.title = "janme"
btn.setTitle("janme", for: .normal)
return item
})
}
}
extension HeaderViewNIBViewController: CHSlideSwitchViewDelegate {
/// 点击顶部tab
///
/// - Parameters:
/// - view: 组件对象
/// - atIndex: 点击位置
func slideSwitchView(view: CHSlideSwitchView, didSelected atIndex: Int) {
NSLog("didSelected : \(atIndex)")
}
/// 滑动左右边界时传递手势
///
/// - Parameters:
/// - view: 组件对象
/// - direction: 方向, true:左,false:右
/// - panEdge: 手势
func slideSwitchView(view: CHSlideSwitchView, direction: Bool, panEdge: UIPanGestureRecognizer) {
}
}
| mit | 25582cb5d94735f4dbd58fa469f1266e | 26.1875 | 123 | 0.591724 | 4.332669 | false | false | false | false |
richardbuckle/Laurine | Example/Pods/Warp/Source/WRPExtensions.swift | 1 | 7435 | //
// WRPExtensions.swift
//
// Copyright (c) 2016 Jiri Trecak (http://jiritrecak.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.
//
// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- ---
//MARK: - Imports
import Foundation
// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- ---
// MARK: - Extension - NSDictionary
extension NSMutableDictionary {
/**
* Set an object for the property identified by a given key path to a given value.
*
* @param object The object for the property identified by _keyPath_.
* @param keyPath A key path of the form _relationship.property_ (with one or more relationships): for example “department.name” or “department.manager.lastName.”
*/
func setObject(object : AnyObject!, forKeyPath : String) {
self.setObject(object, onObject : self, forKeyPath: forKeyPath, createIntermediates: true, replaceIntermediates: true);
}
/**
* Set an object for the property identified by a given key path to a given value, with optional parameters to control creation and replacement of intermediate objects.
*
* @param object The object for the property identified by _keyPath_.
* @param keyPath A key path of the form _relationship.property_ (with one or more relationships): for example “department.name” or “department.manager.lastName.”
* @param createIntermediates Intermediate dictionaries defined within the key path that do not currently exist in the receiver are created.
* @param replaceIntermediates Intermediate objects encountered in the key path that are not a direct subclass of `NSDictionary` are replaced.
*/
func setObject(object : AnyObject, onObject : AnyObject, forKeyPath : String, createIntermediates: Bool, replaceIntermediates: Bool) {
// Path delimiter = .
let pathDelimiter : String = "."
// There is no keypath, just assign object
if forKeyPath.rangeOfString(pathDelimiter) == nil {
onObject.setObject(object, forKey: forKeyPath);
}
// Create path components separated by delimiter (. by default) and get key for root object
let pathComponents : Array<String> = forKeyPath.componentsSeparatedByString(pathDelimiter);
let rootKey : String = pathComponents[0];
let replacementDictionary : NSMutableDictionary = NSMutableDictionary();
// Store current state for further replacement
var previousObject : AnyObject? = onObject;
var previousReplacement : NSMutableDictionary = replacementDictionary;
var reachedDictionaryLeaf : Bool = false;
// Traverse through path from root to deepest level
for path : String in pathComponents {
let currentObject : AnyObject? = reachedDictionaryLeaf ? nil : previousObject?.objectForKey(path);
// Check if object already exists. If not, create new level, if allowed, or end
if currentObject == nil {
reachedDictionaryLeaf = true;
if createIntermediates {
let newNode : NSMutableDictionary = NSMutableDictionary();
previousReplacement.setObject(newNode, forKey: path);
previousReplacement = newNode;
} else {
return;
}
// If it does and it is dictionary, create mutable copy and assign new node there
} else if currentObject is NSDictionary {
let newNode : NSMutableDictionary = NSMutableDictionary(dictionary: currentObject as! [NSObject : AnyObject]);
previousReplacement.setObject(newNode, forKey: path);
previousReplacement = newNode;
// It exists but it is not NSDictionary, so we replace it, if allowed, or end
} else {
reachedDictionaryLeaf = true;
if replaceIntermediates {
let newNode : NSMutableDictionary = NSMutableDictionary();
previousReplacement.setObject(newNode, forKey: path);
previousReplacement = newNode;
} else {
return;
}
}
// Replace previous object with the new one
previousObject = currentObject;
}
// Replace root object with newly created n-level dictionary
replacementDictionary.setValue(object, forKeyPath: forKeyPath);
onObject.setObject(replacementDictionary.objectForKey(rootKey), forKey: rootKey);
}
}
extension NSRange {
init(location:Int, length:Int) {
self.location = location
self.length = length
}
init(_ location:Int, _ length:Int) {
self.location = location
self.length = length
}
init(range:Range <Int>) {
self.location = range.startIndex
self.length = range.endIndex - range.startIndex
}
init(_ range:Range <Int>) {
self.location = range.startIndex
self.length = range.endIndex - range.startIndex
}
var startIndex:Int { get { return location } }
var endIndex:Int { get { return location + length } }
var asRange:Range<Int> { get { return location..<location + length } }
var isEmpty:Bool { get { return length == 0 } }
func contains(index:Int) -> Bool {
return index >= location && index < endIndex
}
func clamp(index:Int) -> Int {
return max(self.startIndex, min(self.endIndex - 1, index))
}
func intersects(range:NSRange) -> Bool {
return NSIntersectionRange(self, range).isEmpty == false
}
func intersection(range:NSRange) -> NSRange {
return NSIntersectionRange(self, range)
}
func union(range:NSRange) -> NSRange {
return NSUnionRange(self, range)
}
}
| mit | e103854bc264590330368d47b9ec061d | 36.852041 | 182 | 0.601429 | 5.395636 | false | false | false | false |
jimmyliao/learnSwift | NKParking/NKParking/IMFLoggerExtension.swift | 1 | 5727 | /*
* Licensed Materials - Property of IBM
* (C) Copyright IBM Corp. 2006, 2013. All Rights Reserved.
* US Government Users Restricted Rights - Use, duplication or
* disclosure restricted by GSA ADP Schedule Contract with IBM Corp.
*/
import Foundation
extension IMFLogger {
//Log methods with no metadata
func logTraceWithMessages(message:String, _ args: CVarArgType...) {
logWithLevel(.Trace, message: message, args:getVaList(args), userInfo:Dictionary<String, String>())
}
func logDebugWithMessages(message:String, _ args: CVarArgType...) {
logWithLevel(.Debug, message: message, args:getVaList(args), userInfo:Dictionary<String, String>())
}
func logInfoWithMessages(message:String, _ args: CVarArgType...) {
logWithLevel(.Info, message: message, args:getVaList(args), userInfo:Dictionary<String, String>())
}
func logWarnWithMessages(message:String, _ args: CVarArgType...) {
logWithLevel(.Warn, message: message, args:getVaList(args), userInfo:Dictionary<String, String>())
}
func logErrorWithMessages(message:String, _ args: CVarArgType...) {
logWithLevel(.Error, message: message, args:getVaList(args), userInfo:Dictionary<String, String>())
}
func logFatalWithMessages(message:String, _ args: CVarArgType...) {
logWithLevel(.Fatal, message: message, args:getVaList(args), userInfo:Dictionary<String, String>())
}
func logAnalyticsWithMessages(message:String, _ args: CVarArgType...) {
logWithLevel(.Analytics, message: message, args:getVaList(args), userInfo:Dictionary<String, String>())
}
//Log methods with metadata
func logTraceWithUserInfo(userInfo:Dictionary<String, String>, message:String, _ args: CVarArgType...) {
logWithLevel(.Trace, message: message, args:getVaList(args), userInfo:userInfo)
}
func logDebugWithUserInfo(userInfo:Dictionary<String, String>, message:String, _ args: CVarArgType...) {
logWithLevel(.Debug, message: message, args:getVaList(args), userInfo:userInfo)
}
func logInfoWithUserInfo(userInfo:Dictionary<String, String>, message:String, _ args: CVarArgType...) {
logWithLevel(.Warn, message: message, args:getVaList(args), userInfo:userInfo)
}
func logWarnWithUserInfo(userInfo:Dictionary<String, String>, message:String, _ args: CVarArgType...) {
logWithLevel(.Trace, message: message, args:getVaList(args), userInfo:userInfo)
}
func logErrorWithUserInfo(userInfo:Dictionary<String, String>, message:String, _ args: CVarArgType...) {
logWithLevel(.Error, message: message, args:getVaList(args), userInfo:userInfo)
}
func logFatalWithUserInfo(userInfo:Dictionary<String, String>, message:String, _ args: CVarArgType...) {
logWithLevel(.Fatal, message: message, args:getVaList(args), userInfo:userInfo)
}
func logAnalyticsWithUserInfo(userInfo:Dictionary<String, String>, message:String, _ args: CVarArgType...) {
logWithLevel(.Analytics, message: message, args:getVaList(args), userInfo:userInfo)
}
}
//Swift IMFLogger Macro Alternatives
private func _metadataDictionary(file:String, fn:String, line:Int) -> Dictionary<String, String> {
return [
KEY_METADATA_METHOD : fn,
KEY_METADATA_FILE : file.lastPathComponent,
KEY_METADATA_LINE : String(line),
KEY_METADATA_SOURCE: SOURCE_SWIFT
];
}
public func IMFLogTrace(message:String, package:String = IMF_NAME, file: String = __FILE__, fn: String = __FUNCTION__, line: Int = __LINE__, #args: CVarArgType...) {
IMFLogger(forName:package).logWithLevel(IMFLogLevel.Trace, message: message, args:getVaList(args), userInfo: _metadataDictionary(file, fn, line));
}
public func IMFLogDebug(message:String, package:String = IMF_NAME, file: String = __FILE__, fn: String = __FUNCTION__, line: Int = __LINE__, #args: CVarArgType...) {
IMFLogger(forName:package).logWithLevel(IMFLogLevel.Debug, message: message, args:getVaList(args), userInfo: _metadataDictionary(file, fn, line));
}
public func IMFLogInfo(message:String, package:String = IMF_NAME, file: String = __FILE__, fn: String = __FUNCTION__, line: Int = __LINE__, #args: CVarArgType...) {
IMFLogger(forName:package).logWithLevel(IMFLogLevel.Info, message: message, args:getVaList(args), userInfo: _metadataDictionary(file, fn, line));
}
public func IMFLogWarn(message:String, package:String = IMF_NAME, file: String = __FILE__, fn: String = __FUNCTION__, line: Int = __LINE__, #args: CVarArgType...) {
IMFLogger(forName:package).logWithLevel(IMFLogLevel.Warn, message: message, args:getVaList(args), userInfo: _metadataDictionary(file, fn, line));
}
public func IMFLogError(message:String, package:String = IMF_NAME, file: String = __FILE__, fn: String = __FUNCTION__, line: Int = __LINE__, #args: CVarArgType...) {
IMFLogger(forName:package).logWithLevel(IMFLogLevel.Error, message: message, args:getVaList(args), userInfo: _metadataDictionary(file, fn, line));
}
public func IMFLogFatal(message:String, package:String = IMF_NAME, file: String = __FILE__, fn: String = __FUNCTION__, line: Int = __LINE__, #args: CVarArgType...) {
IMFLogger(forName:package).logWithLevel(IMFLogLevel.Fatal, message: message, args:getVaList(args), userInfo: _metadataDictionary(file, fn, line));
}
public func IMFLogAnalytics(message:String, package:String = IMF_NAME, file: String = __FILE__, fn: String = __FUNCTION__, line: Int = __LINE__, #args: CVarArgType...) {
IMFLogger(forName:package).logWithLevel(IMFLogLevel.Fatal, message: message, args:getVaList(args), userInfo: _metadataDictionary(file, fn, line));
}
| mit | 95b10f2d1fbfd9b400a9d5eda2b6f0a4 | 51.063636 | 169 | 0.700891 | 4.004895 | false | false | false | false |
Swinject/SwinjectMVVMExample | Carthage/Checkouts/ReactiveSwift/Sources/SignalProducer.swift | 2 | 75584 | import Dispatch
import Foundation
import Result
/// A SignalProducer creates Signals that can produce values of type `Value`
/// and/or fail with errors of type `Error`. If no failure should be possible,
/// `NoError` can be specified for `Error`.
///
/// SignalProducers can be used to represent operations or tasks, like network
/// requests, where each invocation of `start()` will create a new underlying
/// operation. This ensures that consumers will receive the results, versus a
/// plain Signal, where the results might be sent before any observers are
/// attached.
///
/// Because of the behavior of `start()`, different Signals created from the
/// producer may see a different version of Events. The Events may arrive in a
/// different order between Signals, or the stream might be completely
/// different!
public struct SignalProducer<Value, Error: Swift.Error> {
public typealias ProducedSignal = Signal<Value, Error>
private let startHandler: (Signal<Value, Error>.Observer, CompositeDisposable) -> Void
/// Initializes a `SignalProducer` that will emit the same events as the
/// given signal.
///
/// If the Disposable returned from `start()` is disposed or a terminating
/// event is sent to the observer, the given signal will be disposed.
///
/// - parameters:
/// - signal: A signal to observe after starting the producer.
public init<S: SignalProtocol>(signal: S) where S.Value == Value, S.Error == Error {
self.init { observer, disposable in
disposable += signal.observe(observer)
}
}
/// Initializes a SignalProducer that will invoke the given closure once for
/// each invocation of `start()`.
///
/// The events that the closure puts into the given observer will become
/// the events sent by the started `Signal` to its observers.
///
/// - note: If the `Disposable` returned from `start()` is disposed or a
/// terminating event is sent to the observer, the given
/// `CompositeDisposable` will be disposed, at which point work
/// should be interrupted and any temporary resources cleaned up.
///
/// - parameters:
/// - startHandler: A closure that accepts observer and a disposable.
public init(_ startHandler: @escaping (Signal<Value, Error>.Observer, CompositeDisposable) -> Void) {
self.startHandler = startHandler
}
/// Creates a producer for a `Signal` that will immediately send one value
/// then complete.
///
/// - parameters:
/// - value: A value that should be sent by the `Signal` in a `value`
/// event.
public init(value: Value) {
self.init { observer, disposable in
observer.send(value: value)
observer.sendCompleted()
}
}
/// Creates a producer for a `Signal` that will immediately fail with the
/// given error.
///
/// - parameters:
/// - error: An error that should be sent by the `Signal` in a `failed`
/// event.
public init(error: Error) {
self.init { observer, disposable in
observer.send(error: error)
}
}
/// Creates a producer for a Signal that will immediately send one value
/// then complete, or immediately fail, depending on the given Result.
///
/// - parameters:
/// - result: A `Result` instance that will send either `value` event if
/// `result` is `success`ful or `failed` event if `result` is a
/// `failure`.
public init(result: Result<Value, Error>) {
switch result {
case let .success(value):
self.init(value: value)
case let .failure(error):
self.init(error: error)
}
}
/// Creates a producer for a Signal that will immediately send the values
/// from the given sequence, then complete.
///
/// - parameters:
/// - values: A sequence of values that a `Signal` will send as separate
/// `value` events and then complete.
public init<S: Sequence>(values: S) where S.Iterator.Element == Value {
self.init { observer, disposable in
for value in values {
observer.send(value: value)
if disposable.isDisposed {
break
}
}
observer.sendCompleted()
}
}
/// Creates a producer for a Signal that will immediately send the values
/// from the given sequence, then complete.
///
/// - parameters:
/// - first: First value for the `Signal` to send.
/// - second: Second value for the `Signal` to send.
/// - tail: Rest of the values to be sent by the `Signal`.
public init(values first: Value, _ second: Value, _ tail: Value...) {
self.init(values: [ first, second ] + tail)
}
/// A producer for a Signal that will immediately complete without sending
/// any values.
public static var empty: SignalProducer {
return self.init { observer, disposable in
observer.sendCompleted()
}
}
/// A producer for a Signal that never sends any events to its observers.
public static var never: SignalProducer {
return self.init { _ in return }
}
/// Create a `SignalProducer` that will attempt the given operation once for
/// each invocation of `start()`.
///
/// Upon success, the started signal will send the resulting value then
/// complete. Upon failure, the started signal will fail with the error that
/// occurred.
///
/// - parameters:
/// - operation: A closure that returns instance of `Result`.
///
/// - returns: A `SignalProducer` that will forward `success`ful `result` as
/// `value` event and then complete or `failed` event if `result`
/// is a `failure`.
public static func attempt(_ operation: @escaping () -> Result<Value, Error>) -> SignalProducer {
return self.init { observer, disposable in
operation().analysis(ifSuccess: { value in
observer.send(value: value)
observer.sendCompleted()
}, ifFailure: { error in
observer.send(error: error)
})
}
}
/// Create a Signal from the producer, pass it into the given closure,
/// then start sending events on the Signal when the closure has returned.
///
/// The closure will also receive a disposable which can be used to
/// interrupt the work associated with the signal and immediately send an
/// `interrupted` event.
///
/// - parameters:
/// - setUp: A closure that accepts a `signal` and `interrupter`.
public func startWithSignal(_ setup: (_ signal: Signal<Value, Error>, _ interrupter: Disposable) -> Void) {
let (signal, observer) = Signal<Value, Error>.pipe()
// Disposes of the work associated with the SignalProducer and any
// upstream producers.
let producerDisposable = CompositeDisposable()
// Directly disposed of when `start()` or `startWithSignal()` is
// disposed.
let cancelDisposable = ActionDisposable {
observer.sendInterrupted()
producerDisposable.dispose()
}
setup(signal, cancelDisposable)
if cancelDisposable.isDisposed {
return
}
let wrapperObserver: Signal<Value, Error>.Observer = Observer { event in
observer.action(event)
if event.isTerminating {
// Dispose only after notifying the Signal, so disposal
// logic is consistently the last thing to run.
producerDisposable.dispose()
}
}
startHandler(wrapperObserver, producerDisposable)
}
}
public protocol SignalProducerProtocol {
/// The type of values being sent on the producer
associatedtype Value
/// The type of error that can occur on the producer. If errors aren't possible
/// then `NoError` can be used.
associatedtype Error: Swift.Error
/// Extracts a signal producer from the receiver.
var producer: SignalProducer<Value, Error> { get }
/// Initialize a signal
init(_ startHandler: @escaping (Signal<Value, Error>.Observer, CompositeDisposable) -> Void)
/// Creates a Signal from the producer, passes it into the given closure,
/// then starts sending events on the Signal when the closure has returned.
func startWithSignal(_ setup: (_ signal: Signal<Value, Error>, _ interrupter: Disposable) -> Void)
}
extension SignalProducer: SignalProducerProtocol {
public var producer: SignalProducer {
return self
}
}
extension SignalProducerProtocol {
/// Create a Signal from the producer, then attach the given observer to
/// the `Signal` as an observer.
///
/// - parameters:
/// - observer: An observer to attach to produced signal.
///
/// - returns: A `Disposable` which can be used to interrupt the work
/// associated with the signal and immediately send an
/// `interrupted` event.
@discardableResult
public func start(_ observer: Signal<Value, Error>.Observer = .init()) -> Disposable {
var disposable: Disposable!
startWithSignal { signal, innerDisposable in
signal.observe(observer)
disposable = innerDisposable
}
return disposable
}
/// Convenience override for start(_:) to allow trailing-closure style
/// invocations.
///
/// - parameters:
/// - observerAction: A closure that accepts `Event` sent by the produced
/// signal.
///
/// - returns: A `Disposable` which can be used to interrupt the work
/// associated with the signal and immediately send an
/// `interrupted` event.
@discardableResult
public func start(_ observerAction: @escaping Signal<Value, Error>.Observer.Action) -> Disposable {
return start(Observer(observerAction))
}
/// Create a Signal from the producer, then add an observer to the `Signal`,
/// which will invoke the given callback when `value` or `failed` events are
/// received.
///
/// - parameters:
/// - result: A closure that accepts a `result` that contains a `.success`
/// case for `value` events or `.failure` case for `failed` event.
///
/// - returns: A Disposable which can be used to interrupt the work
/// associated with the Signal, and prevent any future callbacks
/// from being invoked.
@discardableResult
public func startWithResult(_ result: @escaping (Result<Value, Error>) -> Void) -> Disposable {
return start(
Observer(
value: { result(.success($0)) },
failed: { result(.failure($0)) }
)
)
}
/// Create a Signal from the producer, then add exactly one observer to the
/// Signal, which will invoke the given callback when a `completed` event is
/// received.
///
/// - parameters:
/// - completed: A closure that will be envoked when produced signal sends
/// `completed` event.
///
/// - returns: A `Disposable` which can be used to interrupt the work
/// associated with the signal.
@discardableResult
public func startWithCompleted(_ completed: @escaping () -> Void) -> Disposable {
return start(Observer(completed: completed))
}
/// Creates a Signal from the producer, then adds exactly one observer to
/// the Signal, which will invoke the given callback when a `failed` event
/// is received.
///
/// - parameters:
/// - failed: A closure that accepts an error object.
///
/// - returns: A `Disposable` which can be used to interrupt the work
/// associated with the signal.
@discardableResult
public func startWithFailed(_ failed: @escaping (Error) -> Void) -> Disposable {
return start(Observer(failed: failed))
}
/// Creates a Signal from the producer, then adds exactly one observer to
/// the Signal, which will invoke the given callback when an `interrupted`
/// event is received.
///
/// - parameters:
/// - interrupted: A closure that is invoked when `interrupted` event is
/// received.
///
/// - returns: A `Disposable` which can be used to interrupt the work
/// associated with the signal.
@discardableResult
public func startWithInterrupted(_ interrupted: @escaping () -> Void) -> Disposable {
return start(Observer(interrupted: interrupted))
}
}
extension SignalProducerProtocol where Error == NoError {
/// Create a Signal from the producer, then add exactly one observer to
/// the Signal, which will invoke the given callback when `value` events are
/// received.
///
/// - parameters:
/// - value: A closure that accepts a value carried by `value` event.
///
/// - returns: A `Disposable` which can be used to interrupt the work
/// associated with the Signal, and prevent any future callbacks
/// from being invoked.
@discardableResult
public func startWithValues(_ value: @escaping (Value) -> Void) -> Disposable {
return start(Observer(value: value))
}
}
extension SignalProducerProtocol {
/// Lift an unary Signal operator to operate upon SignalProducers instead.
///
/// In other words, this will create a new `SignalProducer` which will apply
/// the given `Signal` operator to _every_ created `Signal`, just as if the
/// operator had been applied to each `Signal` yielded from `start()`.
///
/// - parameters:
/// - transform: An unary operator to lift.
///
/// - returns: A signal producer that applies signal's operator to every
/// created signal.
public func lift<U, F>(_ transform: @escaping (Signal<Value, Error>) -> Signal<U, F>) -> SignalProducer<U, F> {
return SignalProducer { observer, outerDisposable in
self.startWithSignal { signal, innerDisposable in
outerDisposable += innerDisposable
transform(signal).observe(observer)
}
}
}
/// Lift a binary Signal operator to operate upon SignalProducers instead.
///
/// In other words, this will create a new `SignalProducer` which will apply
/// the given `Signal` operator to _every_ `Signal` created from the two
/// producers, just as if the operator had been applied to each `Signal`
/// yielded from `start()`.
///
/// - note: starting the returned producer will start the receiver of the
/// operator, which may not be adviseable for some operators.
///
/// - parameters:
/// - transform: A binary operator to lift.
///
/// - returns: A binary operator that operates on two signal producers.
public func lift<U, F, V, G>(_ transform: @escaping (Signal<Value, Error>) -> (Signal<U, F>) -> Signal<V, G>) -> (SignalProducer<U, F>) -> SignalProducer<V, G> {
return liftRight(transform)
}
/// Right-associative lifting of a binary signal operator over producers.
/// That is, the argument producer will be started before the receiver. When
/// both producers are synchronous this order can be important depending on
/// the operator to generate correct results.
private func liftRight<U, F, V, G>(_ transform: @escaping (Signal<Value, Error>) -> (Signal<U, F>) -> Signal<V, G>) -> (SignalProducer<U, F>) -> SignalProducer<V, G> {
return { otherProducer in
return SignalProducer { observer, outerDisposable in
self.startWithSignal { signal, disposable in
outerDisposable.add(disposable)
otherProducer.startWithSignal { otherSignal, otherDisposable in
outerDisposable += otherDisposable
transform(signal)(otherSignal).observe(observer)
}
}
}
}
}
/// Left-associative lifting of a binary signal operator over producers.
/// That is, the receiver will be started before the argument producer. When
/// both producers are synchronous this order can be important depending on
/// the operator to generate correct results.
private func liftLeft<U, F, V, G>(_ transform: @escaping (Signal<Value, Error>) -> (Signal<U, F>) -> Signal<V, G>) -> (SignalProducer<U, F>) -> SignalProducer<V, G> {
return { otherProducer in
return SignalProducer { observer, outerDisposable in
otherProducer.startWithSignal { otherSignal, otherDisposable in
outerDisposable += otherDisposable
self.startWithSignal { signal, disposable in
outerDisposable.add(disposable)
transform(signal)(otherSignal).observe(observer)
}
}
}
}
}
/// Lift a binary Signal operator to operate upon a Signal and a
/// SignalProducer instead.
///
/// In other words, this will create a new `SignalProducer` which will apply
/// the given `Signal` operator to _every_ `Signal` created from the two
/// producers, just as if the operator had been applied to each `Signal`
/// yielded from `start()`.
///
/// - parameters:
/// - transform: A binary operator to lift.
///
/// - returns: A binary operator that works on `Signal` and returns
/// `SignalProducer`.
public func lift<U, F, V, G>(_ transform: @escaping (Signal<Value, Error>) -> (Signal<U, F>) -> Signal<V, G>) -> (Signal<U, F>) -> SignalProducer<V, G> {
return { otherSignal in
return SignalProducer { observer, outerDisposable in
let (wrapperSignal, otherSignalObserver) = Signal<U, F>.pipe()
// Avoid memory leak caused by the direct use of the given
// signal.
//
// See https://github.com/ReactiveCocoa/ReactiveCocoa/pull/2758
// for the details.
outerDisposable += ActionDisposable {
otherSignalObserver.sendInterrupted()
}
outerDisposable += otherSignal.observe(otherSignalObserver)
self.startWithSignal { signal, disposable in
outerDisposable += disposable
outerDisposable += transform(signal)(wrapperSignal).observe(observer)
}
}
}
}
/// Map each value in the producer to a new value.
///
/// - parameters:
/// - transform: A closure that accepts a value and returns a different
/// value.
///
/// - returns: A signal producer that, when started, will send a mapped
/// value of `self.`
public func map<U>(_ transform: @escaping (Value) -> U) -> SignalProducer<U, Error> {
return lift { $0.map(transform) }
}
/// Map errors in the producer to a new error.
///
/// - parameters:
/// - transform: A closure that accepts an error object and returns a
/// different error.
///
/// - returns: A producer that emits errors of new type.
public func mapError<F>(_ transform: @escaping (Error) -> F) -> SignalProducer<Value, F> {
return lift { $0.mapError(transform) }
}
/// Preserve only the values of the producer that pass the given predicate.
///
/// - parameters:
/// - predicate: A closure that accepts value and returns `Bool` denoting
/// whether value has passed the test.
///
/// - returns: A producer that, when started, will send only the values
/// passing the given predicate.
public func filter(_ predicate: @escaping (Value) -> Bool) -> SignalProducer<Value, Error> {
return lift { $0.filter(predicate) }
}
/// Yield the first `count` values from the input producer.
///
/// - precondition: `count` must be non-negative number.
///
/// - parameters:
/// - count: A number of values to take from the signal.
///
/// - returns: A producer that, when started, will yield the first `count`
/// values from `self`.
public func take(first count: Int) -> SignalProducer<Value, Error> {
return lift { $0.take(first: count) }
}
/// Yield an array of values when `self` completes.
///
/// - note: When `self` completes without collecting any value, it will send
/// an empty array of values.
///
/// - returns: A producer that, when started, will yield an array of values
/// when `self` completes.
public func collect() -> SignalProducer<[Value], Error> {
return lift { $0.collect() }
}
/// Yield an array of values until it reaches a certain count.
///
/// - precondition: `count` should be greater than zero.
///
/// - note: When the count is reached the array is sent and the signal
/// starts over yielding a new array of values.
///
/// - note: When `self` completes any remaining values will be sent, the
/// last array may not have `count` values. Alternatively, if were
/// not collected any values will sent an empty array of values.
///
/// - returns: A producer that, when started, collects at most `count`
/// values from `self`, forwards them as a single array and
/// completes.
public func collect(count: Int) -> SignalProducer<[Value], Error> {
precondition(count > 0)
return lift { $0.collect(count: count) }
}
/// Yield an array of values based on a predicate which matches the values
/// collected.
///
/// - note: When `self` completes any remaining values will be sent, the
/// last array may not match `predicate`. Alternatively, if were not
/// collected any values will sent an empty array of values.
///
/// ````
/// let (producer, observer) = SignalProducer<Int, NoError>.buffer(1)
///
/// producer
/// .collect { values in values.reduce(0, combine: +) == 8 }
/// .startWithValues { print($0) }
///
/// observer.send(value: 1)
/// observer.send(value: 3)
/// observer.send(value: 4)
/// observer.send(value: 7)
/// observer.send(value: 1)
/// observer.send(value: 5)
/// observer.send(value: 6)
/// observer.sendCompleted()
///
/// // Output:
/// // [1, 3, 4]
/// // [7, 1]
/// // [5, 6]
/// ````
///
/// - parameters:
/// - predicate: Predicate to match when values should be sent (returning
/// `true`) or alternatively when they should be collected
/// (where it should return `false`). The most recent value
/// (`value`) is included in `values` and will be the end of
/// the current array of values if the predicate returns
/// `true`.
///
/// - returns: A producer that, when started, collects values passing the
/// predicate and, when `self` completes, forwards them as a
/// single array and complets.
public func collect(_ predicate: @escaping (_ values: [Value]) -> Bool) -> SignalProducer<[Value], Error> {
return lift { $0.collect(predicate) }
}
/// Yield an array of values based on a predicate which matches the values
/// collected and the next value.
///
/// - note: When `self` completes any remaining values will be sent, the
/// last array may not match `predicate`. Alternatively, if no
/// values were collected an empty array will be sent.
///
/// ````
/// let (producer, observer) = SignalProducer<Int, NoError>.buffer(1)
///
/// producer
/// .collect { values, value in value == 7 }
/// .startWithValues { print($0) }
///
/// observer.send(value: 1)
/// observer.send(value: 1)
/// observer.send(value: 7)
/// observer.send(value: 7)
/// observer.send(value: 5)
/// observer.send(value: 6)
/// observer.sendCompleted()
///
/// // Output:
/// // [1, 1]
/// // [7]
/// // [7, 5, 6]
/// ````
///
/// - parameters:
/// - predicate: Predicate to match when values should be sent (returning
/// `true`) or alternatively when they should be collected
/// (where it should return `false`). The most recent value
/// (`vaule`) is not included in `values` and will be the
/// start of the next array of values if the predicate
/// returns `true`.
///
/// - returns: A signal that will yield an array of values based on a
/// predicate which matches the values collected and the next
/// value.
public func collect(_ predicate: @escaping (_ values: [Value], _ value: Value) -> Bool) -> SignalProducer<[Value], Error> {
return lift { $0.collect(predicate) }
}
/// Forward all events onto the given scheduler, instead of whichever
/// scheduler they originally arrived upon.
///
/// - parameters:
/// - scheduler: A scheduler to deliver events on.
///
/// - returns: A producer that, when started, will yield `self` values on
/// provided scheduler.
public func observe(on scheduler: SchedulerProtocol) -> SignalProducer<Value, Error> {
return lift { $0.observe(on: scheduler) }
}
/// Combine the latest value of the receiver with the latest value from the
/// given producer.
///
/// - note: The returned producer will not send a value until both inputs
/// have sent at least one value each.
///
/// - note: If either producer is interrupted, the returned producer will
/// also be interrupted.
///
/// - parameters:
/// - other: A producer to combine `self`'s value with.
///
/// - returns: A producer that, when started, will yield a tuple containing
/// values of `self` and given producer.
public func combineLatest<U>(with other: SignalProducer<U, Error>) -> SignalProducer<(Value, U), Error> {
return liftLeft(Signal.combineLatest)(other)
}
/// Combine the latest value of the receiver with the latest value from
/// the given signal.
///
/// - note: The returned producer will not send a value until both inputs
/// have sent at least one value each.
///
/// - note: If either input is interrupted, the returned producer will also
/// be interrupted.
///
/// - parameters:
/// - other: A signal to combine `self`'s value with.
///
/// - returns: A producer that, when started, will yield a tuple containing
/// values of `self` and given signal.
public func combineLatest<U>(with other: Signal<U, Error>) -> SignalProducer<(Value, U), Error> {
return lift(Signal.combineLatest(with:))(other)
}
/// Delay `value` and `completed` events by the given interval, forwarding
/// them on the given scheduler.
///
/// - note: `failed` and `interrupted` events are always scheduled
/// immediately.
///
/// - parameters:
/// - interval: Interval to delay `value` and `completed` events by.
/// - scheduler: A scheduler to deliver delayed events on.
///
/// - returns: A producer that, when started, will delay `value` and
/// `completed` events and will yield them on given scheduler.
public func delay(_ interval: TimeInterval, on scheduler: DateSchedulerProtocol) -> SignalProducer<Value, Error> {
return lift { $0.delay(interval, on: scheduler) }
}
/// Skip the first `count` values, then forward everything afterward.
///
/// - parameters:
/// - count: A number of values to skip.
///
/// - returns: A producer that, when started, will skip the first `count`
/// values, then forward everything afterward.
public func skip(first count: Int) -> SignalProducer<Value, Error> {
return lift { $0.skip(first: count) }
}
/// Treats all Events from the input producer as plain values, allowing them
/// to be manipulated just like any other value.
///
/// In other words, this brings Events “into the monad.”
///
/// - note: When a Completed or Failed event is received, the resulting
/// producer will send the Event itself and then complete. When an
/// `interrupted` event is received, the resulting producer will
/// send the `Event` itself and then interrupt.
///
/// - returns: A producer that sends events as its values.
public func materialize() -> SignalProducer<Event<Value, Error>, NoError> {
return lift { $0.materialize() }
}
/// Forward the latest value from `self` with the value from `sampler` as a
/// tuple, only when `sampler` sends a `value` event.
///
/// - note: If `sampler` fires before a value has been observed on `self`,
/// nothing happens.
///
/// - parameters:
/// - sampler: A producer that will trigger the delivery of `value` event
/// from `self`.
///
/// - returns: A producer that will send values from `self` and `sampler`,
/// sampled (possibly multiple times) by `sampler`, then complete
/// once both input producers have completed, or interrupt if
/// either input producer is interrupted.
public func sample<T>(with sampler: SignalProducer<T, NoError>) -> SignalProducer<(Value, T), Error> {
return liftLeft(Signal.sample(with:))(sampler)
}
/// Forward the latest value from `self` with the value from `sampler` as a
/// tuple, only when `sampler` sends a `value` event.
///
/// - note: If `sampler` fires before a value has been observed on `self`,
/// nothing happens.
///
/// - parameters:
/// - sampler: A signal that will trigger the delivery of `value` event
/// from `self`.
///
/// - returns: A producer that, when started, will send values from `self`
/// and `sampler`, sampled (possibly multiple times) by
/// `sampler`, then complete once both input producers have
/// completed, or interrupt if either input producer is
/// interrupted.
public func sample<T>(with sampler: Signal<T, NoError>) -> SignalProducer<(Value, T), Error> {
return lift(Signal.sample(with:))(sampler)
}
/// Forward the latest value from `self` whenever `sampler` sends a `value`
/// event.
///
/// - note: If `sampler` fires before a value has been observed on `self`,
/// nothing happens.
///
/// - parameters:
/// - sampler: A producer that will trigger the delivery of `value` event
/// from `self`.
///
/// - returns: A producer that, when started, will send values from `self`,
/// sampled (possibly multiple times) by `sampler`, then complete
/// once both input producers have completed, or interrupt if
/// either input producer is interrupted.
public func sample(on sampler: SignalProducer<(), NoError>) -> SignalProducer<Value, Error> {
return liftLeft(Signal.sample(on:))(sampler)
}
/// Forward the latest value from `self` whenever `sampler` sends a `value`
/// event.
///
/// - note: If `sampler` fires before a value has been observed on `self`,
/// nothing happens.
///
/// - parameters:
/// - trigger: A signal whose `value` or `completed` events will start the
/// deliver of events on `self`.
///
/// - returns: A producer that will send values from `self`, sampled
/// (possibly multiple times) by `sampler`, then complete once
/// both inputs have completed, or interrupt if either input is
/// interrupted.
public func sample(on sampler: Signal<(), NoError>) -> SignalProducer<Value, Error> {
return lift(Signal.sample(on:))(sampler)
}
/// Forwards events from `self` until `lifetime` ends, at which point the
/// returned producer will complete.
///
/// - parameters:
/// - lifetime: A lifetime whose `ended` signal will cause the returned
/// producer to complete.
///
/// - returns: A producer that will deliver events until `lifetime` ends.
public func take(during lifetime: Lifetime) -> SignalProducer<Value, Error> {
return take(until: lifetime.ended)
}
/// Forward events from `self` until `trigger` sends a `value` or `completed`
/// event, at which point the returned producer will complete.
///
/// - parameters:
/// - trigger: A producer whose `value` or `completed` events will stop the
/// delivery of `value` events from `self`.
///
/// - returns: A producer that will deliver events until `trigger` sends
/// `value` or `completed` events.
public func take(until trigger: SignalProducer<(), NoError>) -> SignalProducer<Value, Error> {
// This should be the implementation of this method:
// return liftRight(Signal.takeUntil)(trigger)
//
// However, due to a Swift miscompilation (with `-O`) we need to inline
// `liftRight` here.
//
// See https://github.com/ReactiveCocoa/ReactiveCocoa/issues/2751 for
// more details.
//
// This can be reverted once tests with -O work correctly.
return SignalProducer { observer, outerDisposable in
self.startWithSignal { signal, disposable in
outerDisposable.add(disposable)
trigger.startWithSignal { triggerSignal, triggerDisposable in
outerDisposable += triggerDisposable
signal.take(until: triggerSignal).observe(observer)
}
}
}
}
/// Forward events from `self` until `trigger` sends a `value` or
/// `completed` event, at which point the returned producer will complete.
///
/// - parameters:
/// - trigger: A signal whose `value` or `completed` events will stop the
/// delivery of `value` events from `self`.
///
/// - returns: A producer that will deliver events until `trigger` sends
/// `value` or `completed` events.
public func take(until trigger: Signal<(), NoError>) -> SignalProducer<Value, Error> {
return lift(Signal.take(until:))(trigger)
}
/// Do not forward any values from `self` until `trigger` sends a `value`
/// or `completed`, at which point the returned producer behaves exactly
/// like `producer`.
///
/// - parameters:
/// - trigger: A producer whose `value` or `completed` events will start
/// the deliver of events on `self`.
///
/// - returns: A producer that will deliver events once the `trigger` sends
/// `value` or `completed` events.
public func skip(until trigger: SignalProducer<(), NoError>) -> SignalProducer<Value, Error> {
return liftRight(Signal.skip(until:))(trigger)
}
/// Do not forward any values from `self` until `trigger` sends a `value`
/// or `completed`, at which point the returned signal behaves exactly like
/// `signal`.
///
/// - parameters:
/// - trigger: A signal whose `value` or `completed` events will start the
/// deliver of events on `self`.
///
/// - returns: A producer that will deliver events once the `trigger` sends
/// `value` or `completed` events.
public func skip(until trigger: Signal<(), NoError>) -> SignalProducer<Value, Error> {
return lift(Signal.skip(until:))(trigger)
}
/// Forward events from `self` with history: values of the returned producer
/// are a tuple whose first member is the previous value and whose second
/// member is the current value. `initial` is supplied as the first member
/// when `self` sends its first value.
///
/// - parameters:
/// - initial: A value that will be combined with the first value sent by
/// `self`.
///
/// - returns: A producer that sends tuples that contain previous and
/// current sent values of `self`.
public func combinePrevious(_ initial: Value) -> SignalProducer<(Value, Value), Error> {
return lift { $0.combinePrevious(initial) }
}
/// Send only the final value and then immediately completes.
///
/// - parameters:
/// - initial: Initial value for the accumulator.
/// - combine: A closure that accepts accumulator and sent value of
/// `self`.
///
/// - returns: A producer that sends accumulated value after `self`
/// completes.
public func reduce<U>(_ initial: U, _ combine: @escaping (U, Value) -> U) -> SignalProducer<U, Error> {
return lift { $0.reduce(initial, combine) }
}
/// Aggregate `self`'s values into a single combined value. When `self`
/// emits its first value, `combine` is invoked with `initial` as the first
/// argument and that emitted value as the second argument. The result is
/// emitted from the producer returned from `scan`. That result is then
/// passed to `combine` as the first argument when the next value is
/// emitted, and so on.
///
/// - parameters:
/// - initial: Initial value for the accumulator.
/// - combine: A closure that accepts accumulator and sent value of
/// `self`.
///
/// - returns: A producer that sends accumulated value each time `self`
/// emits own value.
public func scan<U>(_ initial: U, _ combine: @escaping (U, Value) -> U) -> SignalProducer<U, Error> {
return lift { $0.scan(initial, combine) }
}
/// Forward only those values from `self` which do not pass `isRepeat` with
/// respect to the previous value.
///
/// - note: The first value is always forwarded.
///
/// - returns: A producer that does not send two equal values sequentially.
public func skipRepeats(_ isRepeat: @escaping (Value, Value) -> Bool) -> SignalProducer<Value, Error> {
return lift { $0.skipRepeats(isRepeat) }
}
/// Do not forward any values from `self` until `predicate` returns false,
/// at which point the returned producer behaves exactly like `self`.
///
/// - parameters:
/// - predicate: A closure that accepts a value and returns whether `self`
/// should still not forward that value to a `producer`.
///
/// - returns: A producer that sends only forwarded values from `self`.
public func skip(while predicate: @escaping (Value) -> Bool) -> SignalProducer<Value, Error> {
return lift { $0.skip(while: predicate) }
}
/// Forward events from `self` until `replacement` begins sending events.
///
/// - parameters:
/// - replacement: A producer to wait to wait for values from and start
/// sending them as a replacement to `self`'s values.
///
/// - returns: A producer which passes through `value`, `failed`, and
/// `interrupted` events from `self` until `replacement` sends an
/// event, at which point the returned producer will send that
/// event and switch to passing through events from `replacement`
/// instead, regardless of whether `self` has sent events
/// already.
public func take(untilReplacement signal: SignalProducer<Value, Error>) -> SignalProducer<Value, Error> {
return liftRight(Signal.take(untilReplacement:))(signal)
}
/// Forwards events from `self` until `replacement` begins sending events.
///
/// - parameters:
/// - replacement: A signal to wait to wait for values from and start
/// sending them as a replacement to `self`'s values.
///
/// - returns: A producer which passes through `value`, `failed`, and
/// `interrupted` events from `self` until `replacement` sends an
/// event, at which point the returned producer will send that
/// event and switch to passing through events from `replacement`
/// instead, regardless of whether `self` has sent events
/// already.
public func take(untilReplacement signal: Signal<Value, Error>) -> SignalProducer<Value, Error> {
return lift(Signal.take(untilReplacement:))(signal)
}
/// Wait until `self` completes and then forward the final `count` values
/// on the returned producer.
///
/// - parameters:
/// - count: Number of last events to send after `self` completes.
///
/// - returns: A producer that receives up to `count` values from `self`
/// after `self` completes.
public func take(last count: Int) -> SignalProducer<Value, Error> {
return lift { $0.take(last: count) }
}
/// Forward any values from `self` until `predicate` returns false, at which
/// point the returned producer will complete.
///
/// - parameters:
/// - predicate: A closure that accepts value and returns `Bool` value
/// whether `self` should forward it to `signal` and continue
/// sending other events.
///
/// - returns: A producer that sends events until the values sent by `self`
/// pass the given `predicate`.
public func take(while predicate: @escaping (Value) -> Bool) -> SignalProducer<Value, Error> {
return lift { $0.take(while: predicate) }
}
/// Zip elements of two producers into pairs. The elements of any Nth pair
/// are the Nth elements of the two input producers.
///
/// - parameters:
/// - other: A producer to zip values with.
///
/// - returns: A producer that sends tuples of `self` and `otherProducer`.
public func zip<U>(with other: SignalProducer<U, Error>) -> SignalProducer<(Value, U), Error> {
return liftLeft(Signal.zip(with:))(other)
}
/// Zip elements of this producer and a signal into pairs. The elements of
/// any Nth pair are the Nth elements of the two.
///
/// - parameters:
/// - other: A signal to zip values with.
///
/// - returns: A producer that sends tuples of `self` and `otherSignal`.
public func zip<U>(with other: Signal<U, Error>) -> SignalProducer<(Value, U), Error> {
return lift(Signal.zip(with:))(other)
}
/// Apply `operation` to values from `self` with `success`ful results
/// forwarded on the returned producer and `failure`s sent as `failed`
/// events.
///
/// - parameters:
/// - operation: A closure that accepts a value and returns a `Result`.
///
/// - returns: A producer that receives `success`ful `Result` as `value`
/// event and `failure` as `failed` event.
public func attempt(operation: @escaping (Value) -> Result<(), Error>) -> SignalProducer<Value, Error> {
return lift { $0.attempt(operation) }
}
/// Apply `operation` to values from `self` with `success`ful results
/// mapped on the returned producer and `failure`s sent as `failed` events.
///
/// - parameters:
/// - operation: A closure that accepts a value and returns a result of
/// a mapped value as `success`.
///
/// - returns: A producer that sends mapped values from `self` if returned
/// `Result` is `success`ful, `failed` events otherwise.
public func attemptMap<U>(_ operation: @escaping (Value) -> Result<U, Error>) -> SignalProducer<U, Error> {
return lift { $0.attemptMap(operation) }
}
/// Throttle values sent by the receiver, so that at least `interval`
/// seconds pass between each, then forwards them on the given scheduler.
///
/// - note: If multiple values are received before the interval has elapsed,
/// the latest value is the one that will be passed on.
///
/// - norw: If `self` terminates while a value is being throttled, that
/// value will be discarded and the returned producer will terminate
/// immediately.
///
/// - parameters:
/// - interval: Number of seconds to wait between sent values.
/// - scheduler: A scheduler to deliver events on.
///
/// - returns: A producer that sends values at least `interval` seconds
/// appart on a given scheduler.
public func throttle(_ interval: TimeInterval, on scheduler: DateSchedulerProtocol) -> SignalProducer<Value, Error> {
return lift { $0.throttle(interval, on: scheduler) }
}
/// Debounce values sent by the receiver, such that at least `interval`
/// seconds pass after the receiver has last sent a value, then
/// forward the latest value on the given scheduler.
///
/// - note: If multiple values are received before the interval has elapsed,
/// the latest value is the one that will be passed on.
///
/// - note: If `self` terminates while a value is being debounced,
/// that value will be discarded and the returned producer will
/// terminate immediately.
///
/// - parameters:
/// - interval: A number of seconds to wait before sending a value.
/// - scheduler: A scheduler to send values on.
///
/// - returns: A producer that sends values that are sent from `self` at
/// least `interval` seconds apart.
public func debounce(_ interval: TimeInterval, on scheduler: DateSchedulerProtocol) -> SignalProducer<Value, Error> {
return lift { $0.debounce(interval, on: scheduler) }
}
/// Forward events from `self` until `interval`. Then if producer isn't
/// completed yet, fails with `error` on `scheduler`.
///
/// - note: If the interval is 0, the timeout will be scheduled immediately.
/// The producer must complete synchronously (or on a faster
/// scheduler) to avoid the timeout.
///
/// - parameters:
/// - interval: Number of seconds to wait for `self` to complete.
/// - error: Error to send with `failed` event if `self` is not completed
/// when `interval` passes.
/// - scheduler: A scheduler to deliver error on.
///
/// - returns: A producer that sends events for at most `interval` seconds,
/// then, if not `completed` - sends `error` with `failed` event
/// on `scheduler`.
public func timeout(after interval: TimeInterval, raising error: Error, on scheduler: DateSchedulerProtocol) -> SignalProducer<Value, Error> {
return lift { $0.timeout(after: interval, raising: error, on: scheduler) }
}
}
extension SignalProducerProtocol where Value: OptionalProtocol {
/// Unwraps non-`nil` values and forwards them on the returned signal, `nil`
/// values are dropped.
///
/// - returns: A producer that sends only non-nil values.
public func skipNil() -> SignalProducer<Value.Wrapped, Error> {
return lift { $0.skipNil() }
}
}
extension SignalProducerProtocol where Value: EventProtocol, Error == NoError {
/// The inverse of materialize(), this will translate a producer of `Event`
/// _values_ into a producer of those events themselves.
///
/// - returns: A producer that sends values carried by `self` events.
public func dematerialize() -> SignalProducer<Value.Value, Value.Error> {
return lift { $0.dematerialize() }
}
}
extension SignalProducerProtocol where Error == NoError {
/// Promote a producer that does not generate failures into one that can.
///
/// - note: This does not actually cause failers to be generated for the
/// given producer, but makes it easier to combine with other
/// producers that may fail; for example, with operators like
/// `combineLatestWith`, `zipWith`, `flatten`, etc.
///
/// - parameters:
/// - _ An `ErrorType`.
///
/// - returns: A producer that has an instantiatable `ErrorType`.
public func promoteErrors<F: Swift.Error>(_: F.Type) -> SignalProducer<Value, F> {
return lift { $0.promoteErrors(F.self) }
}
/// Forward events from `self` until `interval`. Then if producer isn't
/// completed yet, fails with `error` on `scheduler`.
///
/// - note: If the interval is 0, the timeout will be scheduled immediately.
/// The producer must complete synchronously (or on a faster
/// scheduler) to avoid the timeout.
///
/// - parameters:
/// - interval: Number of seconds to wait for `self` to complete.
/// - error: Error to send with `failed` event if `self` is not completed
/// when `interval` passes.
/// - scheudler: A scheduler to deliver error on.
///
/// - returns: A producer that sends events for at most `interval` seconds,
/// then, if not `completed` - sends `error` with `failed` event
/// on `scheduler`.
public func timeout<NewError: Swift.Error>(
after interval: TimeInterval,
raising error: NewError,
on scheduler: DateSchedulerProtocol
) -> SignalProducer<Value, NewError> {
return lift { $0.timeout(after: interval, raising: error, on: scheduler) }
}
/// Wait for completion of `self`, *then* forward all events from
/// `replacement`.
///
/// - note: All values sent from `self` are ignored.
///
/// - parameters:
/// - replacement: A producer to start when `self` completes.
///
/// - returns: A producer that sends events from `self` and then from
/// `replacement` when `self` completes.
public func then<U, NewError: Swift.Error>(_ replacement: SignalProducer<U, NewError>) -> SignalProducer<U, NewError> {
return self
.promoteErrors(NewError.self)
.then(replacement)
}
}
extension SignalProducerProtocol where Value: Equatable {
/// Forward only those values from `self` which are not duplicates of the
/// immedately preceding value.
///
/// - note: The first value is always forwarded.
///
/// - returns: A producer that does not send two equal values sequentially.
public func skipRepeats() -> SignalProducer<Value, Error> {
return lift { $0.skipRepeats() }
}
}
extension SignalProducerProtocol {
/// Forward only those values from `self` that have unique identities across
/// the set of all values that have been seen.
///
/// - note: This causes the identities to be retained to check for
/// uniqueness.
///
/// - parameters:
/// - transform: A closure that accepts a value and returns identity
/// value.
///
/// - returns: A producer that sends unique values during its lifetime.
public func uniqueValues<Identity: Hashable>(_ transform: @escaping (Value) -> Identity) -> SignalProducer<Value, Error> {
return lift { $0.uniqueValues(transform) }
}
}
extension SignalProducerProtocol where Value: Hashable {
/// Forward only those values from `self` that are unique across the set of
/// all values that have been seen.
///
/// - note: This causes the values to be retained to check for uniqueness.
/// Providing a function that returns a unique value for each sent
/// value can help you reduce the memory footprint.
///
/// - returns: A producer that sends unique values during its lifetime.
public func uniqueValues() -> SignalProducer<Value, Error> {
return lift { $0.uniqueValues() }
}
}
extension SignalProducerProtocol {
/// Injects side effects to be performed upon the specified producer events.
///
/// - note: In a composed producer, `starting` is invoked in the reverse
/// direction of the flow of events.
///
/// - parameters:
/// - starting: A closure that is invoked before the producer is started.
/// - started: A closure that is invoked after the producer is started.
/// - event: A closure that accepts an event and is invoked on every
/// received event.
/// - value: A closure that accepts a value from `value` event.
/// - failed: A closure that accepts error object and is invoked for
/// `failed` event.
/// - completed: A closure that is invoked for `completed` event.
/// - interrupted: A closure that is invoked for `interrupted` event.
/// - terminated: A closure that is invoked for any terminating event.
/// - disposed: A closure added as disposable when signal completes.
///
/// - returns: A producer with attached side-effects for given event cases.
public func on(
starting: (() -> Void)? = nil,
started: (() -> Void)? = nil,
event: ((Event<Value, Error>) -> Void)? = nil,
value: ((Value) -> Void)? = nil,
failed: ((Error) -> Void)? = nil,
completed: (() -> Void)? = nil,
interrupted: (() -> Void)? = nil,
terminated: (() -> Void)? = nil,
disposed: (() -> Void)? = nil
) -> SignalProducer<Value, Error> {
return SignalProducer { observer, compositeDisposable in
starting?()
defer { started?() }
self.startWithSignal { signal, disposable in
compositeDisposable += disposable
compositeDisposable += signal
.on(
event: event,
failed: failed,
completed: completed,
interrupted: interrupted,
terminated: terminated,
disposed: disposed,
value: value
)
.observe(observer)
}
}
}
/// Start the returned producer on the given `Scheduler`.
///
/// - note: This implies that any side effects embedded in the producer will
/// be performed on the given scheduler as well.
///
/// - note: Events may still be sent upon other schedulers — this merely
/// affects where the `start()` method is run.
///
/// - parameters:
/// - scheduler: A scheduler to deliver events on.
///
/// - returns: A producer that will deliver events on given `scheduler` when
/// started.
public func start(on scheduler: SchedulerProtocol) -> SignalProducer<Value, Error> {
return SignalProducer { observer, compositeDisposable in
compositeDisposable += scheduler.schedule {
self.startWithSignal { signal, signalDisposable in
compositeDisposable += signalDisposable
signal.observe(observer)
}
}
}
}
}
extension SignalProducerProtocol {
/// Combines the values of all the given producers, in the manner described by
/// `combineLatestWith`.
public static func combineLatest<B>(_ a: SignalProducer<Value, Error>, _ b: SignalProducer<B, Error>) -> SignalProducer<(Value, B), Error> {
return a.combineLatest(with: b)
}
/// Combines the values of all the given producers, in the manner described by
/// `combineLatestWith`.
public static func combineLatest<B, C>(_ a: SignalProducer<Value, Error>, _ b: SignalProducer<B, Error>, _ c: SignalProducer<C, Error>) -> SignalProducer<(Value, B, C), Error> {
return combineLatest(a, b)
.combineLatest(with: c)
.map(repack)
}
/// Combines the values of all the given producers, in the manner described by
/// `combineLatestWith`.
public static func combineLatest<B, C, D>(_ a: SignalProducer<Value, Error>, _ b: SignalProducer<B, Error>, _ c: SignalProducer<C, Error>, _ d: SignalProducer<D, Error>) -> SignalProducer<(Value, B, C, D), Error> {
return combineLatest(a, b, c)
.combineLatest(with: d)
.map(repack)
}
/// Combines the values of all the given producers, in the manner described by
/// `combineLatestWith`.
public static func combineLatest<B, C, D, E>(_ a: SignalProducer<Value, Error>, _ b: SignalProducer<B, Error>, _ c: SignalProducer<C, Error>, _ d: SignalProducer<D, Error>, _ e: SignalProducer<E, Error>) -> SignalProducer<(Value, B, C, D, E), Error> {
return combineLatest(a, b, c, d)
.combineLatest(with: e)
.map(repack)
}
/// Combines the values of all the given producers, in the manner described by
/// `combineLatestWith`.
public static func combineLatest<B, C, D, E, F>(_ a: SignalProducer<Value, Error>, _ b: SignalProducer<B, Error>, _ c: SignalProducer<C, Error>, _ d: SignalProducer<D, Error>, _ e: SignalProducer<E, Error>, _ f: SignalProducer<F, Error>) -> SignalProducer<(Value, B, C, D, E, F), Error> {
return combineLatest(a, b, c, d, e)
.combineLatest(with: f)
.map(repack)
}
/// Combines the values of all the given producers, in the manner described by
/// `combineLatestWith`.
public static func combineLatest<B, C, D, E, F, G>(_ a: SignalProducer<Value, Error>, _ b: SignalProducer<B, Error>, _ c: SignalProducer<C, Error>, _ d: SignalProducer<D, Error>, _ e: SignalProducer<E, Error>, _ f: SignalProducer<F, Error>, _ g: SignalProducer<G, Error>) -> SignalProducer<(Value, B, C, D, E, F, G), Error> {
return combineLatest(a, b, c, d, e, f)
.combineLatest(with: g)
.map(repack)
}
/// Combines the values of all the given producers, in the manner described by
/// `combineLatestWith`.
public static func combineLatest<B, C, D, E, F, G, H>(_ a: SignalProducer<Value, Error>, _ b: SignalProducer<B, Error>, _ c: SignalProducer<C, Error>, _ d: SignalProducer<D, Error>, _ e: SignalProducer<E, Error>, _ f: SignalProducer<F, Error>, _ g: SignalProducer<G, Error>, _ h: SignalProducer<H, Error>) -> SignalProducer<(Value, B, C, D, E, F, G, H), Error> {
return combineLatest(a, b, c, d, e, f, g)
.combineLatest(with: h)
.map(repack)
}
/// Combines the values of all the given producers, in the manner described by
/// `combineLatestWith`.
public static func combineLatest<B, C, D, E, F, G, H, I>(_ a: SignalProducer<Value, Error>, _ b: SignalProducer<B, Error>, _ c: SignalProducer<C, Error>, _ d: SignalProducer<D, Error>, _ e: SignalProducer<E, Error>, _ f: SignalProducer<F, Error>, _ g: SignalProducer<G, Error>, _ h: SignalProducer<H, Error>, _ i: SignalProducer<I, Error>) -> SignalProducer<(Value, B, C, D, E, F, G, H, I), Error> {
return combineLatest(a, b, c, d, e, f, g, h)
.combineLatest(with: i)
.map(repack)
}
/// Combines the values of all the given producers, in the manner described by
/// `combineLatestWith`.
public static func combineLatest<B, C, D, E, F, G, H, I, J>(_ a: SignalProducer<Value, Error>, _ b: SignalProducer<B, Error>, _ c: SignalProducer<C, Error>, _ d: SignalProducer<D, Error>, _ e: SignalProducer<E, Error>, _ f: SignalProducer<F, Error>, _ g: SignalProducer<G, Error>, _ h: SignalProducer<H, Error>, _ i: SignalProducer<I, Error>, _ j: SignalProducer<J, Error>) -> SignalProducer<(Value, B, C, D, E, F, G, H, I, J), Error> {
return combineLatest(a, b, c, d, e, f, g, h, i)
.combineLatest(with: j)
.map(repack)
}
/// Combines the values of all the given producers, in the manner described by
/// `combineLatestWith`. Will return an empty `SignalProducer` if the sequence is empty.
public static func combineLatest<S: Sequence>(_ producers: S) -> SignalProducer<[Value], Error>
where S.Iterator.Element == SignalProducer<Value, Error>
{
var generator = producers.makeIterator()
if let first = generator.next() {
let initial = first.map { [$0] }
return IteratorSequence(generator).reduce(initial) { producer, next in
producer.combineLatest(with: next).map { $0.0 + [$0.1] }
}
}
return .empty
}
/// Zips the values of all the given producers, in the manner described by
/// `zipWith`.
public static func zip<B>(_ a: SignalProducer<Value, Error>, _ b: SignalProducer<B, Error>) -> SignalProducer<(Value, B), Error> {
return a.zip(with: b)
}
/// Zips the values of all the given producers, in the manner described by
/// `zipWith`.
public static func zip<B, C>(_ a: SignalProducer<Value, Error>, _ b: SignalProducer<B, Error>, _ c: SignalProducer<C, Error>) -> SignalProducer<(Value, B, C), Error> {
return zip(a, b)
.zip(with: c)
.map(repack)
}
/// Zips the values of all the given producers, in the manner described by
/// `zipWith`.
public static func zip<B, C, D>(_ a: SignalProducer<Value, Error>, _ b: SignalProducer<B, Error>, _ c: SignalProducer<C, Error>, _ d: SignalProducer<D, Error>) -> SignalProducer<(Value, B, C, D), Error> {
return zip(a, b, c)
.zip(with: d)
.map(repack)
}
/// Zips the values of all the given producers, in the manner described by
/// `zipWith`.
public static func zip<B, C, D, E>(_ a: SignalProducer<Value, Error>, _ b: SignalProducer<B, Error>, _ c: SignalProducer<C, Error>, _ d: SignalProducer<D, Error>, _ e: SignalProducer<E, Error>) -> SignalProducer<(Value, B, C, D, E), Error> {
return zip(a, b, c, d)
.zip(with: e)
.map(repack)
}
/// Zips the values of all the given producers, in the manner described by
/// `zipWith`.
public static func zip<B, C, D, E, F>(_ a: SignalProducer<Value, Error>, _ b: SignalProducer<B, Error>, _ c: SignalProducer<C, Error>, _ d: SignalProducer<D, Error>, _ e: SignalProducer<E, Error>, _ f: SignalProducer<F, Error>) -> SignalProducer<(Value, B, C, D, E, F), Error> {
return zip(a, b, c, d, e)
.zip(with: f)
.map(repack)
}
/// Zips the values of all the given producers, in the manner described by
/// `zipWith`.
public static func zip<B, C, D, E, F, G>(_ a: SignalProducer<Value, Error>, _ b: SignalProducer<B, Error>, _ c: SignalProducer<C, Error>, _ d: SignalProducer<D, Error>, _ e: SignalProducer<E, Error>, _ f: SignalProducer<F, Error>, _ g: SignalProducer<G, Error>) -> SignalProducer<(Value, B, C, D, E, F, G), Error> {
return zip(a, b, c, d, e, f)
.zip(with: g)
.map(repack)
}
/// Zips the values of all the given producers, in the manner described by
/// `zipWith`.
public static func zip<B, C, D, E, F, G, H>(_ a: SignalProducer<Value, Error>, _ b: SignalProducer<B, Error>, _ c: SignalProducer<C, Error>, _ d: SignalProducer<D, Error>, _ e: SignalProducer<E, Error>, _ f: SignalProducer<F, Error>, _ g: SignalProducer<G, Error>, _ h: SignalProducer<H, Error>) -> SignalProducer<(Value, B, C, D, E, F, G, H), Error> {
return zip(a, b, c, d, e, f, g)
.zip(with: h)
.map(repack)
}
/// Zips the values of all the given producers, in the manner described by
/// `zipWith`.
public static func zip<B, C, D, E, F, G, H, I>(_ a: SignalProducer<Value, Error>, _ b: SignalProducer<B, Error>, _ c: SignalProducer<C, Error>, _ d: SignalProducer<D, Error>, _ e: SignalProducer<E, Error>, _ f: SignalProducer<F, Error>, _ g: SignalProducer<G, Error>, _ h: SignalProducer<H, Error>, _ i: SignalProducer<I, Error>) -> SignalProducer<(Value, B, C, D, E, F, G, H, I), Error> {
return zip(a, b, c, d, e, f, g, h)
.zip(with: i)
.map(repack)
}
/// Zips the values of all the given producers, in the manner described by
/// `zipWith`.
public static func zip<B, C, D, E, F, G, H, I, J>(_ a: SignalProducer<Value, Error>, _ b: SignalProducer<B, Error>, _ c: SignalProducer<C, Error>, _ d: SignalProducer<D, Error>, _ e: SignalProducer<E, Error>, _ f: SignalProducer<F, Error>, _ g: SignalProducer<G, Error>, _ h: SignalProducer<H, Error>, _ i: SignalProducer<I, Error>, _ j: SignalProducer<J, Error>) -> SignalProducer<(Value, B, C, D, E, F, G, H, I, J), Error> {
return zip(a, b, c, d, e, f, g, h, i)
.zip(with: j)
.map(repack)
}
/// Zips the values of all the given producers, in the manner described by
/// `zipWith`. Will return an empty `SignalProducer` if the sequence is empty.
public static func zip<S: Sequence>(_ producers: S) -> SignalProducer<[Value], Error>
where S.Iterator.Element == SignalProducer<Value, Error>
{
var generator = producers.makeIterator()
if let first = generator.next() {
let initial = first.map { [$0] }
return IteratorSequence(generator).reduce(initial) { producer, next in
producer.zip(with: next).map { $0.0 + [$0.1] }
}
}
return .empty
}
}
extension SignalProducerProtocol {
/// Repeat `self` a total of `count` times. In other words, start producer
/// `count` number of times, each one after previously started producer
/// completes.
///
/// - note: Repeating `1` time results in an equivalent signal producer.
///
/// - note: Repeating `0` times results in a producer that instantly
/// completes.
///
/// - parameters:
/// - count: Number of repetitions.
///
/// - returns: A signal producer start sequentially starts `self` after
/// previously started producer completes.
public func times(_ count: Int) -> SignalProducer<Value, Error> {
precondition(count >= 0)
if count == 0 {
return .empty
} else if count == 1 {
return producer
}
return SignalProducer { observer, disposable in
let serialDisposable = SerialDisposable()
disposable += serialDisposable
func iterate(_ current: Int) {
self.startWithSignal { signal, signalDisposable in
serialDisposable.innerDisposable = signalDisposable
signal.observe { event in
if case .completed = event {
let remainingTimes = current - 1
if remainingTimes > 0 {
iterate(remainingTimes)
} else {
observer.sendCompleted()
}
} else {
observer.action(event)
}
}
}
}
iterate(count)
}
}
/// Ignore failures up to `count` times.
///
/// - precondition: `count` must be non-negative integer.
///
/// - parameters:
/// - count: Number of retries.
///
/// - returns: A signal producer that restarts up to `count` times.
public func retry(upTo count: Int) -> SignalProducer<Value, Error> {
precondition(count >= 0)
if count == 0 {
return producer
} else {
return flatMapError { _ in
self.retry(upTo: count - 1)
}
}
}
/// Wait for completion of `self`, *then* forward all events from
/// `replacement`. Any failure or interruption sent from `self` is
/// forwarded immediately, in which case `replacement` will not be started,
/// and none of its events will be be forwarded.
///
/// - note: All values sent from `self` are ignored.
///
/// - parameters:
/// - replacement: A producer to start when `self` completes.
///
/// - returns: A producer that sends events from `self` and then from
/// `replacement` when `self` completes.
public func then<U>(_ replacement: SignalProducer<U, Error>) -> SignalProducer<U, Error> {
return SignalProducer<U, Error> { observer, observerDisposable in
self.startWithSignal { signal, signalDisposable in
observerDisposable += signalDisposable
signal.observe { event in
switch event {
case let .failed(error):
observer.send(error: error)
case .completed:
observerDisposable += replacement.start(observer)
case .interrupted:
observer.sendInterrupted()
case .value:
break
}
}
}
}
}
/// Wait for completion of `self`, *then* forward all events from
/// `replacement`. Any failure or interruption sent from `self` is
/// forwarded immediately, in which case `replacement` will not be started,
/// and none of its events will be be forwarded.
///
/// - note: All values sent from `self` are ignored.
///
/// - parameters:
/// - replacement: A producer to start when `self` completes.
///
/// - returns: A producer that sends events from `self` and then from
/// `replacement` when `self` completes.
public func then<U>(_ replacement: SignalProducer<U, NoError>) -> SignalProducer<U, Error> {
return self.then(replacement.promoteErrors(Error.self))
}
/// Start the producer, then block, waiting for the first value.
///
/// When a single value or error is sent, the returned `Result` will
/// represent those cases. However, when no values are sent, `nil` will be
/// returned.
///
/// - returns: Result when single `value` or `failed` event is received.
/// `nil` when no events are received.
public func first() -> Result<Value, Error>? {
return take(first: 1).single()
}
/// Start the producer, then block, waiting for events: `value` and
/// `completed`.
///
/// When a single value or error is sent, the returned `Result` will
/// represent those cases. However, when no values are sent, or when more
/// than one value is sent, `nil` will be returned.
///
/// - returns: Result when single `value` or `failed` event is received.
/// `nil` when 0 or more than 1 events are received.
public func single() -> Result<Value, Error>? {
let semaphore = DispatchSemaphore(value: 0)
var result: Result<Value, Error>?
take(first: 2).start { event in
switch event {
case let .value(value):
if result != nil {
// Move into failure state after recieving another value.
result = nil
return
}
result = .success(value)
case let .failed(error):
result = .failure(error)
semaphore.signal()
case .completed, .interrupted:
semaphore.signal()
}
}
semaphore.wait()
return result
}
/// Start the producer, then block, waiting for the last value.
///
/// When a single value or error is sent, the returned `Result` will
/// represent those cases. However, when no values are sent, `nil` will be
/// returned.
///
/// - returns: Result when single `value` or `failed` event is received.
/// `nil` when no events are received.
public func last() -> Result<Value, Error>? {
return take(last: 1).single()
}
/// Starts the producer, then blocks, waiting for completion.
///
/// When a completion or error is sent, the returned `Result` will represent
/// those cases.
///
/// - returns: Result when single `completion` or `failed` event is
/// received.
public func wait() -> Result<(), Error> {
return then(SignalProducer<(), Error>(value: ())).last() ?? .success(())
}
/// Creates a new `SignalProducer` that will multicast values emitted by
/// the underlying producer, up to `capacity`.
/// This means that all clients of this `SignalProducer` will see the same
/// version of the emitted values/errors.
///
/// The underlying `SignalProducer` will not be started until `self` is
/// started for the first time. When subscribing to this producer, all
/// previous values (up to `capacity`) will be emitted, followed by any new
/// values.
///
/// If you find yourself needing *the current value* (the last buffered
/// value) you should consider using `PropertyType` instead, which, unlike
/// this operator, will guarantee at compile time that there's always a
/// buffered value. This operator is not recommended in most cases, as it
/// will introduce an implicit relationship between the original client and
/// the rest, so consider alternatives like `PropertyType`, or representing
/// your stream using a `Signal` instead.
///
/// This operator is only recommended when you absolutely need to introduce
/// a layer of caching in front of another `SignalProducer`.
///
/// - precondtion: `capacity` must be non-negative integer.
///
/// - parameters:
/// - capcity: Number of values to hold.
///
/// - returns: A caching producer that will hold up to last `capacity`
/// values.
public func replayLazily(upTo capacity: Int) -> SignalProducer<Value, Error> {
precondition(capacity >= 0, "Invalid capacity: \(capacity)")
// This will go "out of scope" when the returned `SignalProducer` goes
// out of scope. This lets us know when we're supposed to dispose the
// underlying producer. This is necessary because `struct`s don't have
// `deinit`.
let lifetimeToken = Lifetime.Token()
let lifetime = Lifetime(lifetimeToken)
let state = Atomic(ReplayState<Value, Error>(upTo: capacity))
let start: Atomic<(() -> Void)?> = Atomic {
// Start the underlying producer.
self
.take(during: lifetime)
.start { event in
let observers: Bag<Signal<Value, Error>.Observer>? = state.modify { state in
defer { state.enqueue(event) }
return state.observers
}
observers?.forEach { $0.action(event) }
}
}
return SignalProducer { observer, disposable in
// Don't dispose of the original producer until all observers
// have terminated.
disposable += { _ = lifetimeToken }
while true {
var result: Result<RemovalToken?, ReplayError<Value>>!
state.modify {
result = $0.observe(observer)
}
switch result! {
case let .success(token):
if let token = token {
disposable += {
state.modify {
$0.removeObserver(using: token)
}
}
}
// Start the underlying producer if it has never been started.
start.swap(nil)?()
// Terminate the replay loop.
return
case let .failure(error):
error.values.forEach(observer.send(value:))
}
}
}
}
}
/// Represents a recoverable error of an observer not being ready for an
/// attachment to a `ReplayState`, and the observer should replay the supplied
/// values before attempting to observe again.
private struct ReplayError<Value>: Error {
/// The values that should be replayed by the observer.
let values: [Value]
}
private struct ReplayState<Value, Error: Swift.Error> {
let capacity: Int
/// All cached values.
var values: [Value] = []
/// A termination event emitted by the underlying producer.
///
/// This will be nil if termination has not occurred.
var terminationEvent: Event<Value, Error>?
/// The observers currently attached to the caching producer, or `nil` if the
/// caching producer was terminated.
var observers: Bag<Signal<Value, Error>.Observer>? = Bag()
/// The set of in-flight replay buffers.
var replayBuffers: [ObjectIdentifier: [Value]] = [:]
/// Initialize the replay state.
///
/// - parameters:
/// - capacity: The maximum amount of values which can be cached by the
/// replay state.
init(upTo capacity: Int) {
self.capacity = capacity
}
/// Attempt to observe the replay state.
///
/// - warning: Repeatedly observing the replay state with the same observer
/// should be avoided.
///
/// - parameters:
/// - observer: The observer to be registered.
///
/// - returns:
/// If the observer is successfully attached, a `Result.success` with the
/// corresponding removal token would be returned. Otherwise, a
/// `Result.failure` with a `ReplayError` would be returned.
mutating func observe(_ observer: Signal<Value, Error>.Observer) -> Result<RemovalToken?, ReplayError<Value>> {
// Since the only use case is `replayLazily`, which always creates a unique
// `Observer` for every produced signal, we can use the ObjectIdentifier of
// the `Observer` to track them directly.
let id = ObjectIdentifier(observer)
switch replayBuffers[id] {
case .none where !values.isEmpty:
// No in-flight replay buffers was found, but the `ReplayState` has one or
// more cached values in the `ReplayState`. The observer should replay
// them before attempting to observe again.
replayBuffers[id] = []
return .failure(ReplayError(values: values))
case let .some(buffer) where !buffer.isEmpty:
// An in-flight replay buffer was found with one or more buffered values.
// The observer should replay them before attempting to observe again.
defer { replayBuffers[id] = [] }
return .failure(ReplayError(values: buffer))
case let .some(buffer) where buffer.isEmpty:
// Since an in-flight but empty replay buffer was found, the observer is
// ready to be attached to the `ReplayState`.
replayBuffers.removeValue(forKey: id)
default:
// No values has to be replayed. The observer is ready to be attached to
// the `ReplayState`.
break
}
if let event = terminationEvent {
observer.action(event)
}
return .success(observers?.insert(observer))
}
/// Enqueue the supplied event to the replay state.
///
/// - parameter:
/// - event: The event to be cached.
mutating func enqueue(_ event: Event<Value, Error>) {
switch event {
case let .value(value):
for key in replayBuffers.keys {
replayBuffers[key]!.append(value)
}
switch capacity {
case 0:
// With a capacity of zero, `state.values` can never be filled.
break
case 1:
values = [value]
default:
values.append(value)
let overflow = values.count - capacity
if overflow > 0 {
values.removeFirst(overflow)
}
}
case .completed, .failed, .interrupted:
// Disconnect all observers and prevent future attachments.
terminationEvent = event
observers = nil
}
}
/// Remove the observer represented by the supplied token.
///
/// - parameters:
/// - token: The token of the observer to be removed.
mutating func removeObserver(using token: RemovalToken) {
observers?.remove(using: token)
}
}
/// Create a repeating timer of the given interval, with a reasonable default
/// leeway, sending updates on the given scheduler.
///
/// - note: This timer will never complete naturally, so all invocations of
/// `start()` must be disposed to avoid leaks.
///
/// - precondition: Interval must be non-negative number.
///
/// - parameters:
/// - interval: An interval between invocations.
/// - scheduler: A scheduler to deliver events on.
///
/// - returns: A producer that sends `NSDate` values every `interval` seconds.
public func timer(interval: TimeInterval, on scheduler: DateSchedulerProtocol) -> SignalProducer<Date, NoError> {
// Apple's "Power Efficiency Guide for Mac Apps" recommends a leeway of
// at least 10% of the timer interval.
return timer(interval: interval, on: scheduler, leeway: interval * 0.1)
}
/// Creates a repeating timer of the given interval, sending updates on the
/// given scheduler.
///
/// - note: This timer will never complete naturally, so all invocations of
/// `start()` must be disposed to avoid leaks.
///
/// - precondition: Interval must be non-negative number.
///
/// - precondition: Leeway must be non-negative number.
///
/// - parameters:
/// - interval: An interval between invocations.
/// - scheduler: A scheduler to deliver events on.
/// - leeway: Interval leeway. Apple's "Power Efficiency Guide for Mac Apps"
/// recommends a leeway of at least 10% of the timer interval.
///
/// - returns: A producer that sends `NSDate` values every `interval` seconds.
public func timer(interval: TimeInterval, on scheduler: DateSchedulerProtocol, leeway: TimeInterval) -> SignalProducer<Date, NoError> {
precondition(interval >= 0)
precondition(leeway >= 0)
return SignalProducer { observer, compositeDisposable in
compositeDisposable += scheduler.schedule(after: scheduler.currentDate.addingTimeInterval(interval),
interval: interval,
leeway: leeway,
action: { observer.send(value: scheduler.currentDate) })
}
}
| mit | 2fe4081a07dedd06feae0198ed2022a8 | 37.877572 | 437 | 0.661608 | 3.788371 | false | false | false | false |
evering7/iSpeak8 | iSpeak8/Helper_Log.swift | 1 | 4559 | //
// Helper_Log.swift
// iSpeak8
//
// Created by JianFei Li on 14/08/2017.
// Copyright © 2017 JianFei Li. All rights reserved.
//
import Foundation
import UIKit
import CoreData
//import CoreStore
let logStringList = LogStringList_TS(queueLabel: "logStringList")
let sema_printLog = DispatchSemaphore(value: 1)
let logLine_Header = String.random(length: 5)
var logLine_Number: UInt = 1
class LogStringList_TS: NSObject {
private var logStringList_Unsafe: [String] = []
private var accessQueue: DispatchQueue? = nil
private let elementCountUpperLimit = 10
init(queueLabel: String ){
let labelStr = queueLabel + " com.blogspot.cnshoe.iSpeak7.logStringList" + UUID().uuidString
super.init()
self.accessQueue = DispatchQueue(label: labelStr,
qos: .default,
attributes: .concurrent,
autoreleaseFrequency: .inherit,
target: nil)
} // init(queueLabel: String ) // 2017.8.10 eve
deinit {
print("deinitialized. class " +
String(describing: type(of: self)) +
" label \(String(describing: self.accessQueue?.label)) ")
// type(of: LogS
// super.deinit()
}
public func appendWithPossiblePop(strInfo: String) { // atomic, writing
guard let q = self.accessQueue else {
fatalError("fail to unwrap accessQueue")
// return
}
q.async{
self.logStringList_Unsafe.append(strInfo)
if self.logStringList_Unsafe.count > self.elementCountUpperLimit {
self.logStringList_Unsafe.remove(at: 0)
}
}
} // public func appendWithPossiblePop(strInfo: String) 2017.8.10 eve
public func getFullStringFromList() -> String { // atomic, reading,
guard let q = self.accessQueue else {
sayFatal("fail to unwrap accessQueue")
return ""
}
var strFull = ""
// let sema = DispatchSemaphore(value: 0)
// sema.wait()
q.sync{
for str in self.logStringList_Unsafe {
strFull += str + "\r\n\r\n"
}
// sema.signal()
}
// sema.wait()
return strFull
} // public func getFullStringFromList() -> String // 2017.8.10 eve
} // class LogStringList: NSObject
func getLogFilePath() -> String {
let filePath = NSHomeDirectory() + "/Documents/JFLogFile.log"
// print("global log file path = \(filePath)")
return filePath
} // func getLogFilePath() -> String 2017 July 10th
func printLog <T> (_ message: T,
file: String = #file,
method: String = #function,
line: Int = #line
)
{
// todo: Add prefix and number.
sema_printLog.wait()
// todo: add item number
let strShowTime = Date().toString()
// let app = application()
// var strShow = "\(currentDate.hour()):\(currentDate.minute()):\(currentDate.second()) "
let strShowInfo = logLine_Header + " " + String(format: "%05d", logLine_Number) +
" T:\(Thread.current)" +
" F:\((file as NSString).lastPathComponent).\(method): " +
"\(line) \(message)"
logLine_Number += 1
NSLog("%@", strShowInfo)
let strShow = strShowTime + strShowInfo
logStringList.appendWithPossiblePop(strInfo: strShow)
// 2017-08-14 18:45:16.365716+0800 iSpeak8[12993:4044265] Returning local object of class NSString
UIPasteboard.general.string = logStringList.getFullStringFromList()
// 1 Show in the command console
//if (logLevel.rawValue & LogLevel.debugConsole.rawValue) == LogLevel.debugConsole.rawValue {
// debugPrint(strShow)
//}
// 2 Output to log file
//if (logLevel.rawValue & LogLevel.outputToFile.rawValue) == LogLevel.outputToFile.rawValue {
let logFile = getLogFilePath()
// use semaphore to lock the file, so that no collision
// app.preferenceData.sema_appendToLogFile.wait()
// It is atomically written, so don't need to semaphore it.
appendWriteToFile(content: strShow, filePath: logFile)
sema_printLog.signal()
// app.preferenceData.sema_appendToLogFile.signal()
//}
} // print log 2017 July 10th
| mit | 4304a8ce580ef4bde04a509877132717 | 29.18543 | 102 | 0.57613 | 4.349237 | false | false | false | false |
PayPal-Opportunity-Hack-Chennai-2015/No-Food-Waste | ios/NoFoodWaster/NoFoodWaster/ServiceManager.swift | 2 | 7115 | //
// ServiceManager.swift
// NoFoodWaste
//
// Created by Ravi Shankar on 28/11/15.
// Copyright © 2015 Ravi Shankar. All rights reserved.
//
import Foundation
protocol ServiceManagerDelegate {
func downloadDonateComplete(donate: Donate)
func downloadConsumerComplete(consumer: Consumer)
}
class ServiceManager {
var delegate: ServiceManagerDelegate?
let baseURL = "http://192.168.117.235:8080"
func createUser(name: String, phone: String, isVolunteer: Bool) {
let urlString = baseURL + "/user/create"
let data = ["username":name,"mobileNumber":phone,"isVolunteer":isVolunteer,"deviceId":phone,"deviceToken":phone]
let request = buildRequest(urlString)
buildRawData(data, request: request)
processRequest(request)
}
func donateFood(mobile:String, status:String, foodType:String, quantity:String,
latitude: Double, longitude: Double, address: String) {
let urlString = baseURL + "/donate/create"
let data = ["donorMobile":mobile,"donationStatus":"open","foodType":foodType,"quantity":quantity,"latitude":latitude,"longitude": longitude, "address":address]
let request = buildRequest(urlString)
buildRawData(data, request: request)
processRequest(request)
}
func getDonateList() {
let urlString = baseURL + "/donate/distance"
let request = buildRequest(urlString,isPost: false)
processDonateRequest(request)
}
func getConsumerList() {
let urlString = baseURL + "/consumer"
let request = buildRequest(urlString,isPost: false)
processConsumerRequest(request)
}
func buildRequest(urlString: String, isPost:Bool = true) -> NSMutableURLRequest{
let url = NSURL(string: urlString)
let request = NSMutableURLRequest(URL: url!)
if isPost {
request.HTTPMethod = "POST"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
} else {
request.HTTPMethod = "GET"
}
return request
}
func processRequest(request: NSMutableURLRequest) {
NSURLSession.sharedSession() .dataTaskWithRequest(request, completionHandler: { (data: NSData?, response:NSURLResponse?, error: NSError?) -> Void in
if error != nil {
print(error?.localizedDescription)
return
}
do {
if let results: NSDictionary = try NSJSONSerialization .JSONObjectWithData(data!, options: NSJSONReadingOptions.AllowFragments ) as? NSDictionary {
print(results)
}
} catch let error as NSError {
print(error.localizedDescription)
}
}).resume()
}
func processConsumerRequest(request: NSMutableURLRequest) {
NSURLSession.sharedSession() .dataTaskWithRequest(request, completionHandler: { (data: NSData?, response:NSURLResponse?, error: NSError?) -> Void in
if error != nil {
print(error?.localizedDescription)
return
}
do {
if let results: NSArray = try NSJSONSerialization .JSONObjectWithData(data!, options: NSJSONReadingOptions.AllowFragments ) as? NSArray {
print(results)
for item in results {
let name = item["cosumerName"] as! String
let address = item["address"] as! String
let latitude = item["latitude"] as! String
let longitude = item["longitude"] as! String
let active = item["active"] as! String
let consumer = Consumer(name: name,address:address, latitude:
latitude, longitude: longitude, active: active)
self.delegate?.downloadConsumerComplete(consumer)
}
}
} catch let error as NSError {
print(error.localizedDescription)
}
}).resume()
}
func processDonateRequest(request: NSMutableURLRequest) {
NSURLSession.sharedSession() .dataTaskWithRequest(request, completionHandler: { (data: NSData?, response:NSURLResponse?, error: NSError?) -> Void in
if error != nil {
print(error?.localizedDescription)
return
}
do {
if let results: NSArray = try NSJSONSerialization .JSONObjectWithData(data!, options: NSJSONReadingOptions.AllowFragments ) as? NSArray {
print(results)
for item in results {
let dict = item as! NSDictionary
let id = dict["id"] as! Int
let serves = dict["quantity"] as! String
let foodType = dict["foodType"] as! String
let latitude = dict["latitude"] as! String
let longitude = dict["longitude"] as! String
let mobile = dict["donorMobile"] as! String
let status = dict["donationStatus"] as! String
let address = dict["address"] as! String
let distance = dict["distance"] as! String
let trimmedAddress = (address as NSString).stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())
let donate = Donate(identifer: id, donorMobile: mobile,foodType:
foodType,serves:serves,address:trimmedAddress,latitude:latitude,
longitude:longitude,status: status, distance: distance)
self.delegate?.downloadDonateComplete(donate)
}
}
} catch let error as NSError {
print(error.localizedDescription)
}
}).resume()
}
func buildRawData(data:NSDictionary, request: NSMutableURLRequest) {
do {
request.HTTPBody = try NSJSONSerialization.dataWithJSONObject(data, options: .PrettyPrinted)
} catch {
//handle error. Probably return or mark function as throws
print(error)
return
}
}
} | apache-2.0 | 7f8a82b846a8decd2cf714f40908f75c | 35.675258 | 167 | 0.528114 | 5.99326 | false | false | false | false |
naeemshaikh90/Reading-List | SwiftBook/Methods.playground/Contents.swift | 1 | 3014 | //: Playground - noun: a place where people can play
import UIKit
import CoreFoundation
// Methods
// Two types Instance Methods and Type Methods
// Instance Methods
class Counter {
var count = 0
func increment() {
count += 1
}
func increment(by amount: Int) {
count += amount
}
func reset() {
count = 0
}
}
let counter = Counter()
counter.increment()
print(counter.count)
counter.increment(by: 5)
print(counter.count)
counter.reset()
print(counter.count)
// Instance Methods
// The self Property
struct Point {
var x = 0.0, y = 0.0
func isItToTheRightOf(x: Double) -> Bool {
return self.x > x
}
}
let somePoint = Point(x: 4.0, y: 10.0)
print(somePoint.isItToTheRightOf(x: 1.0))
// The self Property
// Modifying Value Types from Within Instance Methods
struct Point {
var x: Double = 0.0
var y: Double = 0.0
mutating func moveBy(x deltaX: Double, y deltaY: Double) {
x += deltaX
y += deltaY
}
}
var somePoint = Point(x: 15.0, y: 15.0)
print(somePoint)
somePoint.moveBy(x: 5.0, y: 7.0)
print(somePoint)
// Modifying Value Types from Within Instance Methods
// Assigning to self Within a Mutating Method
struct Point {
var x = 0.0, y = 0.0
mutating func moveBy(x deltaX: Double, y deltaY: Double) {
self = Point(x: x + deltaX, y: y + deltaY)
}
}
var somePoint = Point(x: 12.0, y:13.0)
print(somePoint)
somePoint.moveBy(x: 3, y: 2)
print(somePoint)
enum TriStateSwitch {
case off, low, high
mutating func next() {
switch self {
case .off:
self = .low
case .low:
self = .high
case .high:
self = .off
}
}
}
var ovenLight = TriStateSwitch.low
for i in 0..<9{
ovenLight.next()
print(ovenLight)
}
// Assigning to self Within a Mutating Method
// Type Methods
struct LevelTracker {
static var highestLevelUnlocked = 1
var currentLevel = 1
static func unlock(_ level: Int) {
if level > highestLevelUnlocked {
highestLevelUnlocked = level
}
}
static func isUnlocked(_ level: Int) -> Bool {
return level <= highestLevelUnlocked
}
@discardableResult
mutating func advance(to level: Int) -> Bool {
if LevelTracker.isUnlocked(level) {
currentLevel = level
return true
} else {
return false
}
}
}
class Player {
var tracker = LevelTracker()
let playerName: String
func complete(level: Int) {
LevelTracker.unlock(level + 1)
tracker.advance(to: level + 1)
}
init(name: String) {
playerName = name
}
}
var player = Player(name: "John Doe")
player.complete(level: 4)
dump(LevelTracker.highestLevelUnlocked)
player = Player(name: "Barak Obama")
if player.tracker.advance(to: 6) {
print("Level is Unlocked")
} else {
print("Level is locked")
}
// Type Methods
| mit | 15a1ca0cce3791b14c1d441434b06a49 | 18.075949 | 62 | 0.603517 | 3.635706 | false | false | false | false |
siegesmund/SwiftDDP | Sources/DDPClient.swift | 1 | 22662 | //
//
// A DDP Client written in Swift
//
// Copyright (c) 2016 Peter Siegesmund <[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.
//
// This software uses CryptoSwift: https://github.com/krzyzanowskim/CryptoSwift/
//
import Foundation
import SwiftWebSocket
import XCGLogger
let log = XCGLogger(identifier: "DDP")
public typealias DDPMethodCallback = (_ result:Any?, _ error:DDPError?) -> ()
public typealias DDPConnectedCallback = (_ session:String) -> ()
public typealias DDPCallback = () -> ()
/**
DDPDelegate provides an interface to react to user events
*/
public protocol SwiftDDPDelegate {
func ddpUserDidLogin(_ user:String)
func ddpUserDidLogout(_ user:String)
}
/**
DDPClient is the base class for communicating with a server using the DDP protocol
*/
open class DDPClient: NSObject {
// included for storing login id and token
internal let userData = UserDefaults.standard
let background: OperationQueue = {
let queue = OperationQueue()
queue.name = "DDP Background Data Queue"
queue.qualityOfService = .background
return queue
}()
// Callbacks execute in the order they're received
internal let callbackQueue: OperationQueue = {
let queue = OperationQueue()
queue.name = "DDP Callback Queue"
queue.maxConcurrentOperationCount = 1
queue.qualityOfService = .userInitiated
return queue
}()
// Document messages are processed in the order that they are received,
// separately from callbacks
internal let documentQueue: OperationQueue = {
let queue = OperationQueue()
queue.name = "DDP Background Queue"
queue.maxConcurrentOperationCount = 1
queue.qualityOfService = .background
return queue
}()
// Hearbeats get a special queue so that they're not blocked by
// other operations, causing the connection to close
internal let heartbeat: OperationQueue = {
let queue = OperationQueue()
queue.name = "DDP Heartbeat Queue"
queue.qualityOfService = .utility
return queue
}()
let userBackground: OperationQueue = {
let queue = OperationQueue()
queue.name = "DDP High Priority Background Queue"
queue.qualityOfService = .userInitiated
return queue
}()
let userMainQueue: OperationQueue = {
let queue = OperationQueue.main
queue.name = "DDP High Priorty Main Queue"
queue.qualityOfService = .userInitiated
return queue
}()
fileprivate var socket:WebSocket!{
didSet{ socket.allowSelfSignedSSL = self.allowSelfSignedSSL }
}
fileprivate var server:(ping:Date?, pong:Date?) = (nil, nil)
internal var resultCallbacks:[String:Completion] = [:]
internal var subCallbacks:[String:Completion] = [:]
internal var unsubCallbacks:[String:Completion] = [:]
open var url:String!
fileprivate var subscriptions = [String:(id:String, name:String, ready:Bool)]()
internal var events = DDPEvents()
internal var connection:(ddp:Bool, session:String?) = (false, nil)
open var delegate:SwiftDDPDelegate?
// MARK: Settings
/**
Boolean value that determines whether the
*/
open var allowSelfSignedSSL:Bool = false {
didSet{
guard let currentSocket = socket else { return }
currentSocket.allowSelfSignedSSL = allowSelfSignedSSL
}
}
/**
Sets the log level. The default value is .None.
Possible values: .Verbose, .Debug, .Info, .Warning, .Error, .Severe, .None
*/
open var logLevel = XCGLogger.Level.none {
didSet {
log.setup(level: logLevel, showLogIdentifier: true, showFunctionName: true, showThreadName: true, showLevel: true, showFileNames: false, showLineNumbers: true, showDate: false, writeToFile: nil, fileLevel: .none)
}
}
internal override init() {
super.init()
}
/**
Creates a random String id
*/
open func getId() -> String {
let numbers = Set<Character>(["0","1","2","3","4","5","6","7","8","9"])
let uuid = UUID().uuidString.replacingOccurrences(of: "-", with: "")
var id = ""
for character in uuid.characters {
if (!numbers.contains(character) && (round(Float(arc4random()) / Float(UINT32_MAX)) == 1)) {
id += String(character).lowercased()
} else {
id += String(character)
}
}
return id
}
/**
Makes a DDP connection to the server
- parameter url: The String url to connect to, ex. "wss://todos.meteor.com/websocket"
- parameter callback: A closure that takes a String argument with the value of the websocket session token
*/
open func connect(_ url:String, callback:DDPConnectedCallback?) {
self.url = url
// capture the thread context in which the function is called
let executionQueue = OperationQueue.current
socket = WebSocket(url)
//Create backoff
let backOff:DDPExponentialBackoff = DDPExponentialBackoff()
socket.event.close = {code, reason, clean in
//Use backoff to slow reconnection retries
backOff.createBackoff({
log.info("Web socket connection closed with code \(code). Clean: \(clean). \(reason)")
let event = self.socket.event
self.socket = WebSocket(url)
self.socket.event = event
self.ping()
})
}
socket.event.error = events.onWebsocketError
socket.event.open = {
self.heartbeat.addOperation() {
// Add a subscription to loginServices to each connection event
let callbackWithServiceConfiguration = { (session:String) in
// let loginServicesSubscriptionCollection = "meteor_accounts_loginServiceConfiguration"
let loginServiceConfiguration = "meteor.loginServiceConfiguration"
self.sub(loginServiceConfiguration, params: nil) // /tools/meteor-services/auth.js line 922
// Resubscribe to existing subs on connection to ensure continuity
self.subscriptions.forEach({ (subscription: (String, (id: String, name: String, ready: Bool))) -> () in
if subscription.1.name != loginServiceConfiguration {
self.sub(subscription.1.id, name: subscription.1.name, params: nil, callback: nil)
}
})
callback?(session)
}
var completion = Completion(connectedCallback: callbackWithServiceConfiguration)
//Reset the backoff to original values
backOff.reset()
completion.executionQueue = executionQueue
self.events.onConnected = completion
self.sendMessage(["msg":"connect", "version":"1", "support":["1"]])
}
}
socket.event.message = { message in
self.background.addOperation() {
if let text = message as? String {
do { try self.ddpMessageHandler(DDPMessage(message: text)) }
catch { log.debug("Message handling error. Raw message: \(text)")}
}
}
}
}
fileprivate func ping() {
heartbeat.addOperation() {
self.sendMessage(["msg":"ping", "id":self.getId()])
}
}
// Respond to a server ping
fileprivate func pong(_ ping: DDPMessage) {
heartbeat.addOperation() {
self.server.ping = Date()
var response = ["msg":"pong"]
if let id = ping.id { response["id"] = id }
self.sendMessage(response as NSDictionary)
}
}
// Parse DDP messages and dispatch to the appropriate function
internal func ddpMessageHandler(_ message: DDPMessage) throws {
log.debug("Received message: \(message.json)")
switch message.type {
case .Connected:
self.connection = (true, message.session!)
self.events.onConnected.execute(message.session!)
case .Result: callbackQueue.addOperation() {
if let id = message.id, // Message has id
let completion = self.resultCallbacks[id], // There is a callback registered for the message
let result = message.result {
completion.execute(result, error: message.error)
self.resultCallbacks[id] = nil
} else if let id = message.id,
let completion = self.resultCallbacks[id] {
completion.execute(nil, error:message.error)
self.resultCallbacks[id] = nil
}
}
// Principal callbacks for managing data
// Document was added
case .Added: documentQueue.addOperation() {
if let collection = message.collection,
let id = message.id {
self.documentWasAdded(collection, id: id, fields: message.fields)
}
}
// Document was changed
case .Changed: documentQueue.addOperation() {
if let collection = message.collection,
let id = message.id {
self.documentWasChanged(collection, id: id, fields: message.fields, cleared: message.cleared)
}
}
// Document was removed
case .Removed: documentQueue.addOperation() {
if let collection = message.collection,
let id = message.id {
self.documentWasRemoved(collection, id: id)
}
}
// Notifies you when the result of a method changes
case .Updated: documentQueue.addOperation() {
if let methods = message.methods {
self.methodWasUpdated(methods)
}
}
// Callbacks for managing subscriptions
case .Ready: documentQueue.addOperation() {
if let subs = message.subs {
self.ready(subs)
}
}
// Callback that fires when subscription has been completely removed
//
case .Nosub: documentQueue.addOperation() {
if let id = message.id {
self.nosub(id, error: message.error)
}
}
case .Ping: heartbeat.addOperation() { self.pong(message) }
case .Pong: heartbeat.addOperation() { self.server.pong = Date() }
case .Error: background.addOperation() {
self.didReceiveErrorMessage(DDPError(json: message.json))
}
default: log.error("Unhandled message: \(message.json)")
}
}
fileprivate func sendMessage(_ message:NSDictionary) {
if let m = message.stringValue() {
self.socket.send(m)
}
}
/**
Executes a method on the server. If a callback is passed, the callback is asynchronously
executed when the method has completed. The callback takes two arguments: result and error. It
the method call is successful, result contains the return value of the method, if any. If the method fails,
error contains information about the error.
- parameter name: The name of the method
- parameter params: An object containing method arguments, if any
- parameter callback: The closure to be executed when the method has been executed
*/
@discardableResult open func method(_ name: String, params: Any?, callback: DDPMethodCallback?) -> String {
let id = getId()
let message = ["msg":"method", "method":name, "id":id] as NSMutableDictionary
if let p = params { message["params"] = p }
if let completionCallback = callback {
let completion = Completion(methodCallback: completionCallback)
self.resultCallbacks[id] = completion
}
userBackground.addOperation() {
self.sendMessage(message)
}
return id
}
//
// Subscribe
//
@discardableResult internal func sub(_ id: String, name: String, params: [Any]?, callback: DDPCallback?) -> String {
if let completionCallback = callback {
let completion = Completion(callback: completionCallback)
self.subCallbacks[id] = completion
}
self.subscriptions[id] = (id, name, false)
let message = ["msg":"sub", "name":name, "id":id] as NSMutableDictionary
if let p = params { message["params"] = p }
userBackground.addOperation() {
[weak self] in
if let strongSelf = self
{
strongSelf.sendMessage(message)
} else {
log.error("Ignored message - client was already destroyed")
}
}
return id
}
/**
Sends a subscription request to the server.
- parameter name: The name of the subscription
- parameter params: An object containing method arguments, if any
*/
@discardableResult open func sub(_ name: String, params: [Any]?) -> String {
let id = getId()
return sub(id, name: name, params: params, callback:nil)
}
/**
Sends a subscription request to the server. If a callback is passed, the callback asynchronously
runs when the client receives a 'ready' message indicating that the initial subset of documents contained
in the subscription has been sent by the server.
- parameter name: The name of the subscription
- parameter params: An object containing method arguments, if any
- parameter callback: The closure to be executed when the server sends a 'ready' message
*/
open func sub(_ name:String, params: [Any]?, callback: DDPCallback?) -> String {
let id = getId()
log.info("Subscribing to ID \(id)")
return sub(id, name: name, params: params, callback: callback)
}
// Iterates over the Dictionary of subscriptions to find a subscription by name
internal func findSubscription(_ name:String) -> [String] {
var subs:[String] = []
for sub in subscriptions.values {
if sub.name == name {
subs.append(sub.id)
}
}
return subs
}
// Iterates over the Dictionary of subscriptions to find a subscription by name
internal func subscriptionReady(_ name:String) -> Bool {
for sub in subscriptions.values {
if sub.name == name {
return sub.ready
}
}
return false
}
//
// Unsubscribe
//
/**
Sends an unsubscribe request to the server.
- parameter name: The name of the subscription
- parameter callback: The closure to be executed when the server sends a 'ready' message
*/
open func unsub(withName name: String, callback: DDPCallback?) -> [String] {
let unsubgroup = DispatchGroup()
let unsub_ids = findSubscription(name).map({id -> (String) in
unsubgroup.enter()
unsub(withId: id){
unsubgroup.leave()
}
return id
})
if let completionCallback = callback {
unsubgroup.notify(queue: DispatchQueue.main, execute: completionCallback)
}
return unsub_ids
}
/**
Sends an unsubscribe request to the server. If a callback is passed, the callback asynchronously
runs when the client receives a 'ready' message indicating that the subset of documents contained
in the subscription have been removed.
- parameter name: The name of the subscription
- parameter callback: The closure to be executed when the server sends a 'ready' message
*/
open func unsub(withId id: String, callback: DDPCallback?) {
if let completionCallback = callback {
let completion = Completion(callback: completionCallback)
unsubCallbacks[id] = completion
}
background.addOperation() { self.sendMessage(["msg":"unsub", "id":id]) }
}
//
// Responding to server subscription messages
//
fileprivate func ready(_ subs: [String]) {
for id in subs {
if let completion = subCallbacks[id] {
completion.execute() // Run the callback
subCallbacks[id] = nil // Delete the callback after running
} else { // If there is no callback, execute the method
if var sub = subscriptions[id] {
sub.ready = true
subscriptions[id] = sub
subscriptionIsReady(sub.id, subscriptionName: sub.name)
}
}
}
}
fileprivate func nosub(_ id: String, error: DDPError?) {
if let e = error, (e.isValid == true) {
log.error("\(e)")
} else {
if let completion = unsubCallbacks[id],
let _ = subscriptions[id] {
completion.execute()
unsubCallbacks[id] = nil
subscriptions[id] = nil
} else {
if let subscription = subscriptions[id] {
subscriptions[id] = nil
subscriptionWasRemoved(subscription.id, subscriptionName: subscription.name)
}
}
}
}
//
// public callbacks: should be overridden
//
/**
Executes when a subscription is ready.
- parameter subscriptionId: A String representation of the hash of the subscription name
- parameter subscriptionName: The name of the subscription
*/
open func subscriptionIsReady(_ subscriptionId: String, subscriptionName:String) {}
/**
Executes when a subscription is removed.
- parameter subscriptionId: A String representation of the hash of the subscription name
- parameter subscriptionName: The name of the subscription
*/
open func subscriptionWasRemoved(_ subscriptionId:String, subscriptionName:String) {}
/**
Executes when the server has sent a new document.
- parameter collection: The name of the collection that the document belongs to
- parameter id: The document's unique id
- parameter fields: The documents properties
*/
open func documentWasAdded(_ collection:String, id:String, fields:NSDictionary?) {
if let added = events.onAdded { added(collection, id, fields) }
}
/**
Executes when the server sends a message to remove a document.
- parameter collection: The name of the collection that the document belongs to
- parameter id: The document's unique id
*/
open func documentWasRemoved(_ collection:String, id:String) {
if let removed = events.onRemoved { removed(collection, id) }
}
/**
Executes when the server sends a message to update a document.
- parameter collection: The name of the collection that the document belongs to
- parameter id: The document's unique id
- parameter fields: Optional object with EJSON values containing the fields to update
- parameter cleared: Optional array of strings (field names to delete)
*/
open func documentWasChanged(_ collection:String, id:String, fields:NSDictionary?, cleared:[String]?) {
if let changed = events.onChanged { changed(collection, id, fields, cleared as NSArray?) }
}
/**
Executes when the server sends a message indicating that the result of a method has changed.
- parameter methods: An array of strings (ids passed to 'method', all of whose writes have been reflected in data messages)
*/
open func methodWasUpdated(_ methods:[String]) {
if let updated = events.onUpdated { updated(methods) }
}
/**
Executes when the client receives an error message from the server. Such a message is used to represent errors raised by the method or subscription, as well as an attempt to subscribe to an unknown subscription or call an unknown method.
- parameter message: A DDPError object with information about the error
*/
open func didReceiveErrorMessage(_ message: DDPError) {
if let error = events.onError { error(message) }
}
}
| mit | a9c6f9d376f02a63bc6c0a00a8c2d39c | 36.090016 | 242 | 0.585297 | 5.12831 | false | false | false | false |
mitochrome/complex-gestures-demo | apps/GestureRecognizer/Carthage/Checkouts/RxSwift/RxExample/RxExample/Services/Reachability.swift | 12 | 10069 | /*
Copyright © 2014, Ashley Mills
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
import SystemConfiguration
import struct Foundation.Notification
import class Foundation.NotificationCenter
public enum ReachabilityError: Error {
case failedToCreateWithAddress(sockaddr_in)
case failedToCreateWithHostname(String)
case unableToSetCallback
case unableToSetDispatchQueue
}
public let ReachabilityChangedNotification = Notification.Name("ReachabilityChangedNotification")
func callback(reachability:SCNetworkReachability, flags: SCNetworkReachabilityFlags, info: UnsafeMutableRawPointer?) {
guard let info = info else { return }
let reachability = Unmanaged<Reachability>.fromOpaque(info).takeUnretainedValue()
DispatchQueue.main.async {
reachability.reachabilityChanged()
}
}
public class Reachability {
public typealias NetworkReachable = (Reachability) -> ()
public typealias NetworkUnreachable = (Reachability) -> ()
public enum NetworkStatus: CustomStringConvertible {
case notReachable, reachableViaWiFi, reachableViaWWAN
public var description: String {
switch self {
case .reachableViaWWAN: return "Cellular"
case .reachableViaWiFi: return "WiFi"
case .notReachable: return "No Connection"
}
}
}
public var whenReachable: NetworkReachable?
public var whenUnreachable: NetworkUnreachable?
public var reachableOnWWAN: Bool
// The notification center on which "reachability changed" events are being posted
public var notificationCenter: NotificationCenter = NotificationCenter.default
public var currentReachabilityString: String {
return "\(currentReachabilityStatus)"
}
public var currentReachabilityStatus: NetworkStatus {
guard isReachable else { return .notReachable }
if isReachableViaWiFi {
return .reachableViaWiFi
}
if isRunningOnDevice {
return .reachableViaWWAN
}
return .notReachable
}
fileprivate var previousFlags: SCNetworkReachabilityFlags?
fileprivate var isRunningOnDevice: Bool = {
#if (arch(i386) || arch(x86_64)) && os(iOS)
return false
#else
return true
#endif
}()
fileprivate var notifierRunning = false
fileprivate var reachabilityRef: SCNetworkReachability?
fileprivate let reachabilitySerialQueue = DispatchQueue(label: "uk.co.ashleymills.reachability")
required public init(reachabilityRef: SCNetworkReachability) {
reachableOnWWAN = true
self.reachabilityRef = reachabilityRef
}
public convenience init?(hostname: String) {
guard let ref = SCNetworkReachabilityCreateWithName(nil, hostname) else { return nil }
self.init(reachabilityRef: ref)
}
public convenience init?() {
var zeroAddress = sockaddr()
zeroAddress.sa_len = UInt8(MemoryLayout<sockaddr>.size)
zeroAddress.sa_family = sa_family_t(AF_INET)
guard let ref: SCNetworkReachability = withUnsafePointer(to: &zeroAddress, {
SCNetworkReachabilityCreateWithAddress(nil, UnsafePointer($0))
}) else { return nil }
self.init(reachabilityRef: ref)
}
deinit {
stopNotifier()
reachabilityRef = nil
whenReachable = nil
whenUnreachable = nil
}
}
public extension Reachability {
// MARK: - *** Notifier methods ***
func startNotifier() throws {
guard let reachabilityRef = reachabilityRef, !notifierRunning else { return }
var context = SCNetworkReachabilityContext(version: 0, info: nil, retain: nil, release: nil, copyDescription: nil)
context.info = UnsafeMutableRawPointer(Unmanaged<Reachability>.passUnretained(self).toOpaque())
if !SCNetworkReachabilitySetCallback(reachabilityRef, callback, &context) {
stopNotifier()
throw ReachabilityError.unableToSetCallback
}
if !SCNetworkReachabilitySetDispatchQueue(reachabilityRef, reachabilitySerialQueue) {
stopNotifier()
throw ReachabilityError.unableToSetDispatchQueue
}
// Perform an initial check
reachabilitySerialQueue.async {
self.reachabilityChanged()
}
notifierRunning = true
}
func stopNotifier() {
defer { notifierRunning = false }
guard let reachabilityRef = reachabilityRef else { return }
SCNetworkReachabilitySetCallback(reachabilityRef, nil, nil)
SCNetworkReachabilitySetDispatchQueue(reachabilityRef, nil)
}
// MARK: - *** Connection test methods ***
var isReachable: Bool {
guard isReachableFlagSet else { return false }
if isConnectionRequiredAndTransientFlagSet {
return false
}
if isRunningOnDevice {
if isOnWWANFlagSet && !reachableOnWWAN {
// We don't want to connect when on 3G.
return false
}
}
return true
}
var isReachableViaWWAN: Bool {
// Check we're not on the simulator, we're REACHABLE and check we're on WWAN
return isRunningOnDevice && isReachableFlagSet && isOnWWANFlagSet
}
var isReachableViaWiFi: Bool {
// Check we're reachable
guard isReachableFlagSet else { return false }
// If reachable we're reachable, but not on an iOS device (i.e. simulator), we must be on WiFi
guard isRunningOnDevice else { return true }
// Check we're NOT on WWAN
return !isOnWWANFlagSet
}
var description: String {
let W = isRunningOnDevice ? (isOnWWANFlagSet ? "W" : "-") : "X"
let R = isReachableFlagSet ? "R" : "-"
let c = isConnectionRequiredFlagSet ? "c" : "-"
let t = isTransientConnectionFlagSet ? "t" : "-"
let i = isInterventionRequiredFlagSet ? "i" : "-"
let C = isConnectionOnTrafficFlagSet ? "C" : "-"
let D = isConnectionOnDemandFlagSet ? "D" : "-"
let l = isLocalAddressFlagSet ? "l" : "-"
let d = isDirectFlagSet ? "d" : "-"
return "\(W)\(R) \(c)\(t)\(i)\(C)\(D)\(l)\(d)"
}
}
fileprivate extension Reachability {
func reachabilityChanged() {
let flags = reachabilityFlags
guard previousFlags != flags else { return }
let block = isReachable ? whenReachable : whenUnreachable
block?(self)
self.notificationCenter.post(name: ReachabilityChangedNotification, object:self)
previousFlags = flags
}
var isOnWWANFlagSet: Bool {
#if os(iOS)
return reachabilityFlags.contains(.isWWAN)
#else
return false
#endif
}
var isReachableFlagSet: Bool {
return reachabilityFlags.contains(.reachable)
}
var isConnectionRequiredFlagSet: Bool {
return reachabilityFlags.contains(.connectionRequired)
}
var isInterventionRequiredFlagSet: Bool {
return reachabilityFlags.contains(.interventionRequired)
}
var isConnectionOnTrafficFlagSet: Bool {
return reachabilityFlags.contains(.connectionOnTraffic)
}
var isConnectionOnDemandFlagSet: Bool {
return reachabilityFlags.contains(.connectionOnDemand)
}
var isConnectionOnTrafficOrDemandFlagSet: Bool {
return !reachabilityFlags.intersection([.connectionOnTraffic, .connectionOnDemand]).isEmpty
}
var isTransientConnectionFlagSet: Bool {
return reachabilityFlags.contains(.transientConnection)
}
var isLocalAddressFlagSet: Bool {
return reachabilityFlags.contains(.isLocalAddress)
}
var isDirectFlagSet: Bool {
return reachabilityFlags.contains(.isDirect)
}
var isConnectionRequiredAndTransientFlagSet: Bool {
return reachabilityFlags.intersection([.connectionRequired, .transientConnection]) == [.connectionRequired, .transientConnection]
}
var reachabilityFlags: SCNetworkReachabilityFlags {
guard let reachabilityRef = reachabilityRef else { return SCNetworkReachabilityFlags() }
var flags = SCNetworkReachabilityFlags()
let gotFlags = withUnsafeMutablePointer(to: &flags) {
SCNetworkReachabilityGetFlags(reachabilityRef, UnsafeMutablePointer($0))
}
if gotFlags {
return flags
} else {
return SCNetworkReachabilityFlags()
}
}
}
| mit | d900b07894a1da51ed15f2f45927c9e3 | 32.672241 | 137 | 0.664084 | 6.039592 | false | false | false | false |
erikackermann/pact-consumer-swift | PactConsumerSwiftTests/AnimalServiceClient.swift | 1 | 2362 | import Foundation
import Alamofire
public struct Animal {
public let name: String
public let type: String
}
public class AnimalServiceClient {
private let baseUrl: String
public init(baseUrl : String) {
self.baseUrl = baseUrl
}
public func getAlligator(success: (Animal) -> Void, failure: (NSError?) -> Void) {
Alamofire.request(.GET, "\(baseUrl)/alligator")
.responseJSON {
(_, _, json, error) in
if let jsonResult = json as? Dictionary<String, String> {
let alligator = Animal(name: jsonResult["name"]!, type: jsonResult["type"]!)
success(alligator)
} else {
failure(error)
}
}
}
public func findAnimals(#live: String, response: ([Animal]) -> Void) {
Alamofire.request(.GET, "\(baseUrl)/animals", parameters: [ "live": live])
.responseJSON {
(_, _, json, error) in
if let jsonResult = json as? Array<Dictionary<String, String>> {
var alligators : [Animal] = []
for alligator in jsonResult {
alligators.append(Animal(name: alligator["name"]!, type: alligator["type"]!))
}
response(alligators)
}
}
}
public func eat(#animal: String, success: () -> Void, error: (Int) -> Void) {
Alamofire.request(.PATCH, "\(baseUrl)/alligator/eat", parameters: [ "type" : animal ], encoding: .JSON)
.responseJSON { (_, response, json, errorResponse) in
if let errorVal = errorResponse {
error(response!.statusCode)
} else {
success()
}
}
}
public func wontEat(#animal: String, success: () -> Void, error: (Int) -> Void) {
Alamofire.request(.DELETE, "\(baseUrl)/alligator/eat", parameters: [ "type" : animal ], encoding: .JSON)
.responseJSON { (_, response, json, errorResponse) in
if let errorVal = errorResponse {
error(response!.statusCode)
} else {
success()
}
}
}
public func eats(success: ([Animal]) -> Void) {
Alamofire.request(.GET, "\(baseUrl)/alligator/eat")
.responseJSON { (_, response, json, errorResponse) in
if let jsonResult = json as? Array<Dictionary<String, String>> {
var animals: [Animal] = []
for alligator in jsonResult {
animals.append(Animal(name: alligator["name"]!, type: alligator["type"]!))
}
success(animals)
}
}
}
} | mit | e57b8b6d4e4266cfa95c3354c4680978 | 29.688312 | 108 | 0.600762 | 4.195382 | false | false | false | false |
Allow2CEO/browser-ios | AlertPopupView.swift | 1 | 3730 | /* 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 UIKit
class AlertPopupView: PopupView {
fileprivate var dialogImage: UIImageView?
fileprivate var titleLabel: UILabel!
fileprivate var messageLabel: UILabel!
fileprivate var containerView: UIView!
fileprivate let kAlertPopupScreenFraction: CGFloat = 0.8
fileprivate let kPadding: CGFloat = 20.0
init(image: UIImage?, title: String, message: String) {
super.init(frame: CGRect.zero)
overlayDismisses = false
defaultShowType = .normal
defaultDismissType = .noAnimation
presentsOverWindow = true
containerView = UIView(frame: CGRect.zero)
containerView.autoresizingMask = [.flexibleWidth]
if let image = image {
let di = UIImageView(image: image)
containerView.addSubview(di)
dialogImage = di
}
titleLabel = UILabel(frame: CGRect.zero)
titleLabel.textColor = UIColor.black
titleLabel.textAlignment = .center
titleLabel.font = UIFont.systemFont(ofSize: 24, weight: UIFontWeightBold)
titleLabel.text = title
titleLabel.numberOfLines = 0
containerView.addSubview(titleLabel)
messageLabel = UILabel(frame: CGRect.zero)
messageLabel.textColor = UIColor(rgb: 0x696969)
messageLabel.textAlignment = .center
messageLabel.font = UIFont.systemFont(ofSize: 15, weight: UIFontWeightRegular)
messageLabel.text = message
messageLabel.numberOfLines = 0
containerView.addSubview(messageLabel)
updateSubviews()
setPopupContentView(view: containerView)
setStyle(popupStyle: .dialog)
setDialogColor(color: BraveUX.PopupDialogColorLight)
}
func updateSubviews() {
let width: CGFloat = dialogWidth
var imageFrame: CGRect = dialogImage?.frame ?? CGRect.zero
if let dialogImage = dialogImage {
imageFrame.origin.x = (width - imageFrame.width) / 2.0
imageFrame.origin.y = kPadding * 2.0
dialogImage.frame = imageFrame
}
let titleLabelSize: CGSize = titleLabel.sizeThatFits(CGSize(width: width - kPadding * 4.0, height: CGFloat.greatestFiniteMagnitude))
var titleLabelFrame: CGRect = titleLabel.frame
titleLabelFrame.size = titleLabelSize
titleLabelFrame.origin.x = rint((width - titleLabelSize.width) / 2.0)
titleLabelFrame.origin.y = imageFrame.maxY + kPadding
titleLabel.frame = titleLabelFrame
let messageLabelSize: CGSize = messageLabel.sizeThatFits(CGSize(width: width - kPadding * 4.0, height: CGFloat.greatestFiniteMagnitude))
var messageLabelFrame: CGRect = messageLabel.frame
messageLabelFrame.size = messageLabelSize
messageLabelFrame.origin.x = rint((width - messageLabelSize.width) / 2.0)
messageLabelFrame.origin.y = rint(titleLabelFrame.maxY + kPadding / 2.0)
messageLabel.frame = messageLabelFrame
var containerViewFrame: CGRect = containerView.frame
containerViewFrame.size.width = width
containerViewFrame.size.height = messageLabelFrame.maxY + kPadding
containerView.frame = containerViewFrame
}
override func layoutSubviews() {
super.layoutSubviews()
updateSubviews()
}
required init(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| mpl-2.0 | 1efc9c325aeb09632d8759ee432efd2f | 37.854167 | 144 | 0.658177 | 5.22409 | false | false | false | false |
jkolb/Shkadov | Sources/PlatformXCB/GetCRTCInfo.swift | 1 | 2042 | /*
The MIT License (MIT)
Copyright (c) 2016 Justin Kolb
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 ShkadovXCB.RandR
public struct GetCRTCInfo {
private let connection: OpaquePointer
private let crtc: xcb_randr_crtc_t
private let timestamp: xcb_timestamp_t
init(connection: OpaquePointer, crtc: xcb_randr_crtc_t, timestamp: xcb_timestamp_t) {
self.connection = connection
self.crtc = crtc
self.timestamp = timestamp
}
public func withReply<R>(_ body: (CRTCInfo) throws -> R) throws -> R {
let cookie = xcb_randr_get_crtc_info(connection, crtc, timestamp)
var errorPointer: UnsafeMutablePointer<xcb_generic_error_t>?
if let replyPointer = xcb_randr_get_crtc_info_reply(connection, cookie, &errorPointer) {
defer {
free(replyPointer)
}
return try body(CRTCInfo(connection: connection, reply: replyPointer))
}
else if let errorPointer = errorPointer {
defer {
free(errorPointer)
}
throw XCBError.generic(errorPointer.pointee)
}
else {
throw XCBError.improbable
}
}
}
| mit | 16c38d3c963728503ccd96b04d2ff7dd | 33.033333 | 90 | 0.755142 | 3.889524 | false | false | false | false |
WeirdMath/TimetableSDK | Sources/EducatorSchedule.swift | 1 | 5373 | //
// EducatorSchedule.swift
// TimetableSDK
//
// Created by Sergej Jaskiewicz on 05.12.2016.
//
//
import Foundation
import SwiftyJSON
/// The information about an educator's schedule.
public final class EducatorSchedule : JSONRepresentable, TimetableEntity {
fileprivate static let dateFormatter: DateFormatter = {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
dateFormatter.locale = .posix
return dateFormatter
}()
/// The Timetable this entity was fetched from. `nil` if it was initialized from a custom JSON object.
public weak var timetable: Timetable? {
didSet {
educatorEventsDays.forEach { $0.timetable = timetable }
}
}
public let autumnTermLinkAvailable: Bool
public let dateRangeDisplayText: String
public let educatorDisplayText: String
public let educatorEventsDays: [Day]
public let educatorLongDisplayText: String
public let educatorID: Int
public let from: Date
public let hasEvents: Bool
public let isSpringTerm: Bool
public let next: Int?
public let springTermLinkAvailable: Bool
public let title: String
public let to: Date
internal init(autumnTermLinkAvailable: Bool,
dateRangeDisplayText: String,
educatorDisplayText: String,
educatorEventsDays: [Day],
educatorLongDisplayText: String,
educatorID: Int,
from: Date,
hasEvents: Bool,
isSpringTerm: Bool,
next: Int?,
springTermLinkAvailable: Bool,
title: String,
to: Date) {
self.autumnTermLinkAvailable = autumnTermLinkAvailable
self.dateRangeDisplayText = dateRangeDisplayText
self.educatorDisplayText = educatorDisplayText
self.educatorEventsDays = educatorEventsDays
self.educatorLongDisplayText = educatorLongDisplayText
self.educatorID = educatorID
self.from = from
self.hasEvents = hasEvents
self.isSpringTerm = isSpringTerm
self.next = next
self.springTermLinkAvailable = springTermLinkAvailable
self.title = title
self.to = to
}
/// Creates a new entity from its JSON representation.
///
/// - Parameter json: The JSON representation of the entity.
/// - Throws: `TimetableError.incorrectJSONFormat`
public init(from json: JSON) throws {
do {
autumnTermLinkAvailable = try map(json["AutumnTermLinkAvailable"])
dateRangeDisplayText = try map(json["DateRangeDisplayText"])
educatorDisplayText = try map(json["EducatorDisplayText"])
educatorEventsDays = try map(json["EducatorEventsDays"])
educatorLongDisplayText = try map(json["EducatorLongDisplayText"])
educatorID = try map(json["EducatorMasterId"])
from = try map(json["From"],
transformation: EducatorSchedule.dateFormatter.date(from:))
hasEvents = try map(json["HasEvents"])
isSpringTerm = try map(json["IsSpringTerm"])
next = try map(json["Next"])
springTermLinkAvailable = try map(json["SpringTermLinkAvailable"])
title = try map(json["Title"])
to = try map(json["To"],
transformation: EducatorSchedule.dateFormatter.date(from:))
} catch {
throw TimetableError.incorrectJSON(json, whenConverting: EducatorSchedule.self)
}
}
}
extension EducatorSchedule : Equatable {
/// Returns a Boolean value indicating whether two values are equal.
///
/// Equality is the inverse of inequality. For any values `a` and `b`,
/// `a == b` implies that `a != b` is `false`.
///
/// - Parameters:
/// - lhs: A value to compare.
/// - rhs: Another value to compare.
public static func ==(lhs: EducatorSchedule, rhs: EducatorSchedule) -> Bool {
return
lhs.autumnTermLinkAvailable == rhs.autumnTermLinkAvailable &&
lhs.dateRangeDisplayText == rhs.dateRangeDisplayText &&
lhs.educatorDisplayText == rhs.educatorDisplayText &&
lhs.educatorEventsDays == rhs.educatorEventsDays &&
lhs.educatorLongDisplayText == rhs.educatorLongDisplayText &&
lhs.educatorID == rhs.educatorID &&
lhs.from == rhs.from &&
lhs.hasEvents == rhs.hasEvents &&
lhs.isSpringTerm == rhs.isSpringTerm &&
lhs.next == rhs.next &&
lhs.springTermLinkAvailable == rhs.springTermLinkAvailable &&
lhs.title == rhs.title &&
lhs.to == rhs.to
}
}
| mit | 0961574d4aed8d689df5775bd335c3fd | 42.330645 | 106 | 0.560208 | 4.771758 | false | false | false | false |
rokuz/omim | iphone/Maps/Classes/Components/VerticallyAlignedButton.swift | 5 | 1640 | @IBDesignable
class VerticallyAlignedButton: MWMButton {
override init(frame: CGRect) {
super.init(frame: frame)
titleLabel?.textAlignment = .center
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
titleLabel?.textAlignment = .center
}
override func contentRect(forBounds bounds: CGRect) -> CGRect {
let w = CGFloat.maximum(intrinsicContentSize.width, bounds.width)
let h = CGFloat.maximum(intrinsicContentSize.height, bounds.height)
return CGRect(x: bounds.minX, y: bounds.minY, width: w, height: h)
}
override func titleRect(forContentRect contentRect: CGRect) -> CGRect {
let titleRect = super.titleRect(forContentRect: contentRect)
return CGRect(x: contentRect.minX,
y: contentRect.height - titleRect.height,
width: contentRect.width,
height: titleRect.height)
}
override func imageRect(forContentRect contentRect: CGRect) -> CGRect {
let imageRect = super.imageRect(forContentRect: contentRect)
return CGRect(x: floor((contentRect.width - imageRect.width) / 2),
y: 0,
width: imageRect.width,
height: imageRect.height)
}
override var intrinsicContentSize: CGSize {
let r = CGRect(x: 0, y: 0, width: CGFloat.greatestFiniteMagnitude, height: CGFloat.greatestFiniteMagnitude)
let imageRect = super.imageRect(forContentRect: r)
let titleRect = super.titleRect(forContentRect: r)
let w = CGFloat.maximum(imageRect.width, titleRect.width)
return CGSize(width: w, height: imageRect.height + titleRect.height + 4)
}
}
| apache-2.0 | 7a4467fabf6cd787dddbf1d154bf2643 | 36.272727 | 111 | 0.687195 | 4.530387 | false | false | false | false |
Mobilette/MobiletteDashboardiOS | Pods/OAuthSwift/OAuthSwift/OAuth1Swift.swift | 1 | 6521 | //
// OAuth1Swift.swift
// OAuthSwift
//
// Created by Dongri Jin on 6/22/14.
// Copyright (c) 2014 Dongri Jin. All rights reserved.
//
import Foundation
public class OAuth1Swift: OAuthSwift {
// If your oauth provider doesn't provide `oauth_verifier`
// set value to true (default: false)
public var allowMissingOauthVerifier: Bool = false
var consumer_key: String
var consumer_secret: String
var request_token_url: String
var authorize_url: String
var access_token_url: String
// MARK: init
public init(consumerKey: String, consumerSecret: String, requestTokenUrl: String, authorizeUrl: String, accessTokenUrl: String){
self.consumer_key = consumerKey
self.consumer_secret = consumerSecret
self.request_token_url = requestTokenUrl
self.authorize_url = authorizeUrl
self.access_token_url = accessTokenUrl
super.init(consumerKey: consumerKey, consumerSecret: consumerSecret)
self.client.credential.version = .OAuth1
}
public convenience init?(parameters: [String:String]){
guard let consumerKey = parameters["consumerKey"], consumerSecret = parameters["consumerSecret"],
requestTokenUrl = parameters["requestTokenUrl"], authorizeUrl = parameters["authorizeUrl"], accessTokenUrl = parameters["accessTokenUrl"] else {
return nil
}
self.init(consumerKey:consumerKey, consumerSecret: consumerSecret,
requestTokenUrl: requestTokenUrl,
authorizeUrl: authorizeUrl,
accessTokenUrl: accessTokenUrl)
}
// MARK: functions
// 0. Start
public func authorizeWithCallbackURL(callbackURL: NSURL, success: TokenSuccessHandler, failure: FailureHandler?) {
self.postOAuthRequestTokenWithCallbackURL(callbackURL, success: { [unowned self]
credential, response, _ in
self.observeCallback { [unowned self] url in
var responseParameters = [String: String]()
if let query = url.query {
responseParameters += query.parametersFromQueryString()
}
if let fragment = url.fragment where !fragment.isEmpty {
responseParameters += fragment.parametersFromQueryString()
}
if let token = responseParameters["token"] {
responseParameters["oauth_token"] = token
}
if (responseParameters["oauth_token"] != nil && (self.allowMissingOauthVerifier || responseParameters["oauth_verifier"] != nil)) {
//var credential: OAuthSwiftCredential = self.client.credential
self.client.credential.oauth_token = responseParameters["oauth_token"]!.safeStringByRemovingPercentEncoding
if (responseParameters["oauth_verifier"] != nil) {
self.client.credential.oauth_verifier = responseParameters["oauth_verifier"]!.safeStringByRemovingPercentEncoding
}
self.postOAuthAccessTokenWithRequestToken(success, failure: failure)
} else {
let userInfo = [NSLocalizedDescriptionKey: "Oauth problem. oauth_token or oauth_verifier not returned"]
failure?(error: NSError(domain: OAuthSwiftErrorDomain, code: -1, userInfo: userInfo))
return
}
}
// 2. Authorize
let urlString = self.authorize_url + (self.authorize_url.has("?") ? "&" : "?") + "oauth_token=\(credential.oauth_token)"
if let queryURL = NSURL(string: urlString) {
self.authorize_url_handler.handle(queryURL)
}
else {
let errorInfo = [NSLocalizedFailureReasonErrorKey: NSLocalizedString("Failed to create URL", comment: "\(urlString) not convertible to URL, please encode.")]
failure?(error: NSError(domain: OAuthSwiftErrorDomain, code: -1, userInfo: errorInfo))
}
}, failure: failure)
}
// 1. Request token
func postOAuthRequestTokenWithCallbackURL(callbackURL: NSURL, success: TokenSuccessHandler, failure: FailureHandler?) {
var parameters = Dictionary<String, AnyObject>()
if let callbackURLString: String = callbackURL.absoluteString {
parameters["oauth_callback"] = callbackURLString
}
self.client.post(self.request_token_url, parameters: parameters, success: {
data, response in
let responseString = NSString(data: data, encoding: NSUTF8StringEncoding) as String!
let parameters = responseString.parametersFromQueryString()
if let oauthToken=parameters["oauth_token"] {
self.client.credential.oauth_token = oauthToken.safeStringByRemovingPercentEncoding
}
if let oauthTokenSecret=parameters["oauth_token_secret"] {
self.client.credential.oauth_token_secret = oauthTokenSecret.safeStringByRemovingPercentEncoding
}
success(credential: self.client.credential, response: response, parameters: parameters)
}, failure: failure)
}
// 3. Get Access token
func postOAuthAccessTokenWithRequestToken(success: TokenSuccessHandler, failure: FailureHandler?) {
var parameters = Dictionary<String, AnyObject>()
parameters["oauth_token"] = self.client.credential.oauth_token
parameters["oauth_verifier"] = self.client.credential.oauth_verifier
self.client.post(self.access_token_url, parameters: parameters, success: {
data, response in
let responseString = NSString(data: data, encoding: NSUTF8StringEncoding) as String!
let parameters = responseString.parametersFromQueryString()
if let oauthToken=parameters["oauth_token"] {
self.client.credential.oauth_token = oauthToken.safeStringByRemovingPercentEncoding
}
if let oauthTokenSecret=parameters["oauth_token_secret"] {
self.client.credential.oauth_token_secret = oauthTokenSecret.safeStringByRemovingPercentEncoding
}
success(credential: self.client.credential, response: response, parameters: parameters)
}, failure: failure)
}
@available(*, deprecated=0.5.0, message="Use OAuthSwift.handleOpenURL()")
public override class func handleOpenURL(url: NSURL) {
super.handleOpenURL(url)
}
}
| mit | ec62778545b193df4923751880c3e826 | 48.401515 | 173 | 0.650054 | 5.447786 | false | false | false | false |
yonasstephen/swift-of-airbnb | frameworks/airbnb-datepicker/airbnb-datepicker/AirbnbDatePickerFlowLayout.swift | 2 | 976 | //
// AirbnbDatePickerFlowLayout.swift
// airbnb-datepicker
//
// Created by Yonas Stephen on 28/2/17.
// Copyright © 2017 Yonas Stephen. All rights reserved.
//
import UIKit
class AirbnbDatePickerFlowLayout : UICollectionViewFlowLayout {
let cellSpacing:CGFloat = 0
override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
if let attributes = super.layoutAttributesForElements(in: rect) {
for (index, attribute) in attributes.enumerated() {
if index == 0 { continue }
let prevLayoutAttributes = attributes[index - 1]
let origin = prevLayoutAttributes.frame.maxX
if origin + cellSpacing + attribute.frame.size.width < self.collectionViewContentSize.width {
attribute.frame.origin.x = origin + cellSpacing
}
}
return attributes
}
return nil
}
}
| mit | e4fb739718bdabb9365a4da7376a3e65 | 32.62069 | 109 | 0.629744 | 5.241935 | false | false | false | false |
BObereder/Bureaucracy | Bureaucracy/Sections/SelectorFormSection.swift | 1 | 2818 | //
// SelectorFormSection.swift
// Bureaucracy
//
// Created by Bernhard Obereder on 28.10.14.
// Copyright (c) 2014 Alexander Kolov. All rights reserved.
//
import UIKit
public class SelectorFormSection<Type: protocol<Equatable, Printable>>: FormSection, FormDataProtocol {
public typealias Internal = Int
public typealias Representation = String
public init(_ name: String, value: Type, values: [Type]) {
valueTransformer = { (var x) -> Internal in return find(values, x)! }
reverseValueTransformer = { (var idx) -> Type in return values[idx] }
super.init(name)
self.values = values
self.value = value
internalValue = valueTransformer(value)
representationTransformer = { (var x) -> Representation in
if let theRepresentation = self.representation {
if let idx = find(values, x) {
return theRepresentation[idx]
}
}
return "\(x)"
}
for i in 0..<values.count {
var x = values[i]
let field = append(SelectorGroupFormField("\(name).\(i)", value: x == value))
field.localizedTitle = representationTransformer?(x)
}
}
// MARK: PreviousValue
var previousValue: Type?
// MARK: Value
public var value: Type? {
didSet {
if previousValue != value {
didSetValue(oldValue: oldValue, newValue: value)
}
}
}
public var internalValue: Internal? {
get {
return FormUtilities.convertValue(value, transformer: valueTransformer)
}
set {
(value, error) = FormUtilities.convertInternalValue(internalValue, transformer: reverseValueTransformer, validator: validator)
}
}
var valueTransformer: Type -> Internal
var reverseValueTransformer: Internal -> Type
func didSetValue(#oldValue: Type?, newValue: Type?) {
error = FormUtilities.validateValue(newValue, validator: validator)
if error != nil {
previousValue = oldValue
value = oldValue
}
}
// MARK: Values
public var values: [Type] = []
public var representation: [Representation]?
public var representationValues: [Representation]? {
return FormUtilities.convertToRepresenationValues(values, representationTransformer: representationTransformer)
}
public var representationTransformer: ((Type) -> (Representation))?
// MARK: Validation
public var validator: ((Type) -> (NSError?))?
public var error: NSError?
// MARK: Serialization
public override func serialize() -> [String: Any?] {
return [name: value]
}
// MARK: FormSection
public override func didUpdate(#item: FormElement) {
for aItem in items {
if item !== aItem {
if let theItem = aItem as? SelectorGroupFormField {
theItem.value = false
}
}
}
form?.didUpdate(section: self, item: item)
}
}
| mit | 479b2586102bb2c5761430a2682c1e6b | 23.938053 | 132 | 0.661107 | 4.348765 | false | false | false | false |
chili-ios/CHICore | CHICore/Classes/Utils/Device/DeviceUtils.swift | 1 | 1311 | //
// DeviceUtils.swift
// CHICore
//
// Created by McSims on 05/04/2019.
//
import Foundation
import Device
public protocol PDeviceUtils {
static var isIPhone4: Bool { get }
static var isIPhone5: Bool { get }
static var isSmallDevice: Bool { get }
static var isPhone: Bool { get }
static var isPad: Bool { get }
static var isIPhoneX: Bool { get }
static var isIphone4s: Bool { get }
static var isIphoneSEOrSmaller: Bool { get }
}
public struct DeviceUtils: PDeviceUtils {
public static var isIPhone4: Bool {
return Device.size() == .screen3_5Inch
}
public static var isIPhone5: Bool {
return Device.size() == .screen4Inch
}
public static var isSmallDevice: Bool {
return DeviceUtils.isIPhone4 || DeviceUtils.isIPhone5
}
public static var isPhone: Bool {
return UIDevice.current.userInterfaceIdiom == .phone
}
public static var isPad: Bool {
return UIDevice.current.userInterfaceIdiom == .pad
}
public static var isIPhoneX: Bool {
return Device.size() == .screen5_8Inch
}
public static var isIphone4s: Bool {
return Device.size() == .screen3_5Inch
}
public static var isIphoneSEOrSmaller: Bool {
return Device.size() <= .screen4Inch
}
}
| mit | e629c0a199c8b7457d5c8f271268507e | 22.836364 | 61 | 0.647597 | 3.984802 | false | false | false | false |
wordpress-mobile/WordPress-iOS | WordPress/Classes/ViewRelated/Stats/Today Widgets/Data/AllTimeWidgetStats.swift | 1 | 2817 | import Foundation
/// This struct contains data for the Insights All Time stats to be displayed in the corresponding widget.
/// The data is stored in a plist for the widget to access.
///
struct AllTimeWidgetStats: Codable {
let views: Int
let visitors: Int
let posts: Int
let bestViews: Int
init(views: Int? = 0, visitors: Int? = 0, posts: Int? = 0, bestViews: Int? = 0) {
self.views = views ?? 0
self.visitors = visitors ?? 0
self.posts = posts ?? 0
self.bestViews = bestViews ?? 0
}
}
extension AllTimeWidgetStats {
static func loadSavedData() -> AllTimeWidgetStats? {
guard let sharedDataFileURL = dataFileURL,
FileManager.default.fileExists(atPath: sharedDataFileURL.path) == true else {
DDLogError("AllTimeWidgetStats: data file '\(dataFileName)' does not exist.")
return nil
}
let decoder = PropertyListDecoder()
do {
let data = try Data(contentsOf: sharedDataFileURL)
return try decoder.decode(AllTimeWidgetStats.self, from: data)
} catch {
DDLogError("Failed loading AllTimeWidgetStats data: \(error.localizedDescription)")
return nil
}
}
static func clearSavedData() {
guard let dataFileURL = AllTimeWidgetStats.dataFileURL else {
return
}
do {
try FileManager.default.removeItem(at: dataFileURL)
}
catch {
DDLogError("AllTimeWidgetStats: failed deleting data file '\(dataFileName)': \(error.localizedDescription)")
}
}
func saveData() {
guard let dataFileURL = AllTimeWidgetStats.dataFileURL else {
return
}
let encoder = PropertyListEncoder()
encoder.outputFormat = .xml
do {
let data = try encoder.encode(self)
try data.write(to: dataFileURL)
} catch {
DDLogError("Failed saving AllTimeWidgetStats data: \(error.localizedDescription)")
}
}
private static var dataFileName = AppConfiguration.Widget.StatsToday.allTimeFilename
private static var dataFileURL: URL? {
guard let url = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: WPAppGroupName) else {
DDLogError("AllTimeWidgetStats: unable to get file URL for \(WPAppGroupName).")
return nil
}
return url.appendingPathComponent(dataFileName)
}
}
extension AllTimeWidgetStats: Equatable {
static func == (lhs: AllTimeWidgetStats, rhs: AllTimeWidgetStats) -> Bool {
return lhs.views == rhs.views &&
lhs.visitors == rhs.visitors &&
lhs.posts == rhs.posts &&
lhs.bestViews == rhs.bestViews
}
}
| gpl-2.0 | 08f0e4d4d83823a3228f1d7de70fa0bf | 31.011364 | 120 | 0.621938 | 4.734454 | false | false | false | false |
Bunn/Xgist | Shared/GitHubAPI.swift | 1 | 5108 | //
// GitHubAPI.swift
// Xgist
//
// Created by Fernando Bunn on 27/03/17.
// Copyright © 2017 Fernando Bunn. All rights reserved.
//
import Foundation
struct GitHubAPI {
let twoFactorHeader = "X-GitHub-OTP"
enum GitHubAPIError: Error {
case badHHTPStatus
case invalidRequest
case invalidJSON
case tokenNotFound
case twoFactorRequired
}
//MARK: - Variables
var isAuthenticated: Bool {
if let _ = token {
return true
} else {
return false
}
}
var token: String? {
do {
let password = try Keychain().readPassword()
return password
} catch {
return nil
}
}
//MARK: - Public Functions
func logout() {
do {
try Keychain().deleteItem()
} catch {
fatalError("Error deleting keychain item - \(error)")
}
}
func post(gist: String, fileExtension: String, authenticated: Bool, completion: @escaping (Error?, String?) -> Void) {
var file = [String : Any]()
file["content"] = gist
var files = [String : Any]()
files["Xgist.\(fileExtension)"] = file
let formatter = DateFormatter()
formatter.dateStyle = .medium
formatter.timeStyle = .medium
let dateString = formatter.string(from: Date())
var jsonDictionary = [String : Any]()
jsonDictionary["description"] = "Generated by Xgist (https://github.com/Bunn/Xgist) at \(dateString)"
jsonDictionary["public"] = false
jsonDictionary["files"] = files
guard let request = GitHubRouter.gist(jsonDictionary, authenticated).request else {
completion(GitHubAPIError.invalidRequest, nil)
return
}
//Setup Session
let task = URLSession.shared.dataTask(with: request) { (data, response, error) in
guard let data = data, error == nil else {
completion(error, nil)
return
}
if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 201 {
completion(GitHubAPIError.badHHTPStatus, nil)
return
}
if let json = try? JSONSerialization.jsonObject(with: data, options: []) as! [String : Any] {
if let htmlURL = json["html_url"] as? String {
completion(nil, htmlURL)
}
}
}
task.resume()
}
func authenticate (username: String, password: String, twoFactorCode: String? = nil, completion: @escaping (Error?) -> Void) {
let scopes = ["gist"]
let params = ["client_secret" : GitHubCredential.clientSecret.rawValue,
"scopes" : scopes,
"note" : "testNote"] as [String : Any]
guard var request = GitHubRouter.auth(params).request else {
completion(GitHubAPIError.invalidRequest)
return
}
if let code = twoFactorCode {
request.setValue(code, forHTTPHeaderField: twoFactorHeader)
}
let loginData = base64Login(username: username, password: password)
request.setValue("Basic \(loginData)", forHTTPHeaderField: "Authorization")
//Setup Session
let task = URLSession.shared.dataTask(with: request) { (data, response, error) in
guard let responseData = data, error == nil,
let jsonObject = try? JSONSerialization.jsonObject(with: responseData, options: []) else {
completion(error)
return
}
guard let json = jsonObject as? [String : Any] else {
completion(GitHubAPIError.invalidJSON)
return
}
guard let httpStatus = response as? HTTPURLResponse else {
completion(GitHubAPIError.invalidRequest)
return
}
guard httpStatus.allHeaderFields[self.twoFactorHeader] == nil else {
completion(GitHubAPIError.twoFactorRequired)
return
}
guard let token = json["token"] as? String else {
completion(GitHubAPIError.tokenNotFound)
return
}
do {
try Keychain().savePassword(token)
completion(nil)
} catch {
completion(error)
}
}
task.resume()
}
//MARK: - Private Functions
fileprivate func base64Login(username: String, password: String) -> String {
let loginString = "\(username):\(password)"
let loginData = loginString.data(using: String.Encoding.utf8)!
let base64LoginString = loginData.base64EncodedString()
return base64LoginString
}
}
| mit | 9c11db22360113ab85d3afd821bb500c | 30.91875 | 130 | 0.534756 | 5.264948 | false | false | false | false |
wanghdnku/Whisper | Whisper/ChatRoom.swift | 1 | 2518 | //
// ChatRoom.swift
// Whisper
//
// Created by Hayden on 2016/10/13.
// Copyright © 2016年 unimelb. All rights reserved.
//
import Foundation
import Firebase
struct ChatRoom {
var username: String!
var other_Username: String!
var userId: String!
var other_UserId: String!
var members: [String]!
var chatRoomId: String!
var lastMessage: String!
var userPhotoUrl: String!
var other_UserPhotoUrl: String!
var key: String = ""
var date: NSNumber!
var ref: FIRDatabaseReference!
init(snapshot: FIRDataSnapshot) {
self.key = snapshot.key
self.ref = snapshot.ref
let snap = snapshot.value! as! [String: AnyObject]
self.username = snap["username"] as! String
self.other_Username = snap["other_Username"] as! String
self.userId = snap["userId"] as! String
self.other_UserId = snap["other_UserId"] as! String
self.members = snap["members"] as! [String]
self.chatRoomId = snap["chatRoomId"] as! String
self.lastMessage = snap["lastMessage"] as! String
self.userPhotoUrl = snap["userPhotoUrl"] as! String
self.other_UserPhotoUrl = snap["other_UserPhotoUrl"] as! String
self.date = snap["date"] as! NSNumber
}
init(username: String, other_Username: String, userId: String, other_UserId: String, members: [String], chatRoomId: String, lastMessage: String, userPhotoUrl: String, other_UserPhotoUrl: String, key: String = "", date: NSNumber!) {
self.username = username
self.other_Username = other_Username
self.userId = userId
self.other_UserId = other_UserId
self.members = members
self.chatRoomId = chatRoomId
self.lastMessage = lastMessage
self.userPhotoUrl = userPhotoUrl
self.other_UserPhotoUrl = other_UserPhotoUrl
self.date = date
}
func toAnyObject() -> [String: AnyObject] {
return ["username": username as AnyObject,
"other_Username": other_Username as AnyObject,
"userId": userId as AnyObject,
"other_UserId": other_UserId as AnyObject,
"members": members as AnyObject,
"chatRoomId": chatRoomId as AnyObject,
"lastMessage": lastMessage as AnyObject,
"userPhotoUrl": userPhotoUrl as AnyObject,
"other_UserPhotoUrl": other_UserPhotoUrl as AnyObject,
"date": date as AnyObject]
}
}
| mit | b934972067c0fbbb2eb2de3cceca098c | 35.449275 | 235 | 0.62505 | 4.277211 | false | false | false | false |
jcavar/refresher | Refresher/PullToRefreshView.swift | 1 | 6490 | //
// PullToRefreshView.swift
//
// Copyright (c) 2014 Josip Cavar
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
import UIKit
import QuartzCore
public enum PullToRefreshViewState {
case loading
case pullToRefresh
case releaseToRefresh
}
public protocol PullToRefreshViewDelegate {
func pullToRefreshAnimationDidStart(_ view: PullToRefreshView)
func pullToRefreshAnimationDidEnd(_ view: PullToRefreshView)
func pullToRefresh(_ view: PullToRefreshView, progressDidChange progress: CGFloat)
func pullToRefresh(_ view: PullToRefreshView, stateDidChange state: PullToRefreshViewState)
}
open class PullToRefreshView: UIView {
private var observation: NSKeyValueObservation?
private var scrollViewBouncesDefaultValue: Bool = false
private var scrollViewInsetsDefaultValue: UIEdgeInsets = UIEdgeInsets.zero
private var animator: PullToRefreshViewDelegate
private var action: (() -> ()) = {}
private var previousOffset: CGFloat = 0
internal var loading: Bool = false {
didSet {
if loading != oldValue {
if loading {
startAnimating()
} else {
stopAnimating()
}
}
}
}
// MARK: Object lifecycle methods
convenience init(action: @escaping (() -> ()), frame: CGRect) {
var bounds = frame
bounds.origin.y = 0
let animator = Animator(frame: bounds)
self.init(frame: frame, animator: animator)
self.action = action;
addSubview(animator.animatorView)
}
convenience init(action: @escaping (() -> ()), frame: CGRect, animator: PullToRefreshViewDelegate, subview: UIView) {
self.init(frame: frame, animator: animator)
self.action = action;
subview.frame = self.bounds
addSubview(subview)
}
convenience init(action: @escaping (() -> ()), frame: CGRect, animator: PullToRefreshViewDelegate) {
self.init(frame: frame, animator: animator)
self.action = action;
}
init(frame: CGRect, animator: PullToRefreshViewDelegate) {
self.animator = animator
super.init(frame: frame)
self.autoresizingMask = .flexibleWidth
}
public required init?(coder aDecoder: NSCoder) {
self.animator = Animator(frame: CGRect.zero)
super.init(coder: aDecoder)
// It is not currently supported to load view from nib
}
// MARK: UIView methods
open override func willMove(toSuperview newSuperview: UIView!) {
self.observation?.invalidate()
if let scrollView = newSuperview as? UIScrollView {
self.observation = scrollView.observe(\.contentOffset, options: [.initial]) { [unowned self] (scrollView, change) in
let offsetWithoutInsets = self.previousOffset + self.scrollViewInsetsDefaultValue.top
if (offsetWithoutInsets < -self.frame.size.height) {
if (scrollView.isDragging == false && self.loading == false) {
self.loading = true
} else if (self.loading) {
self.animator.pullToRefresh(self, stateDidChange: .loading)
} else {
self.animator.pullToRefresh(self, stateDidChange: .releaseToRefresh)
self.animator.pullToRefresh(self, progressDidChange: -offsetWithoutInsets / self.frame.size.height)
}
} else if (self.loading) {
self.animator.pullToRefresh(self, stateDidChange: .loading)
} else if (offsetWithoutInsets < 0) {
self.animator.pullToRefresh(self, stateDidChange: .pullToRefresh)
self.animator.pullToRefresh(self, progressDidChange: -offsetWithoutInsets / self.frame.size.height)
}
self.previousOffset = scrollView.contentOffset.y
}
scrollViewBouncesDefaultValue = scrollView.bounces
scrollViewInsetsDefaultValue = scrollView.contentInset
}
}
// MARK: PullToRefreshView methods
private func startAnimating() {
let scrollView = superview as! UIScrollView
var insets = scrollView.contentInset
insets.top += self.frame.size.height
// We need to restore previous offset because we will animate scroll view insets and regular scroll view animating is not applied then
scrollView.contentOffset.y = previousOffset
scrollView.bounces = false
UIView.animate(withDuration: 0.3, delay: 0, options: UIViewAnimationOptions(), animations: {
scrollView.contentInset = insets
scrollView.contentOffset = CGPoint(x: scrollView.contentOffset.x, y: -insets.top)
}, completion: {finished in
self.animator.pullToRefreshAnimationDidStart(self)
self.action()
})
}
private func stopAnimating() {
self.animator.pullToRefreshAnimationDidEnd(self)
let scrollView = superview as! UIScrollView
scrollView.bounces = self.scrollViewBouncesDefaultValue
UIView.animate(withDuration: 0.3, animations: {
scrollView.contentInset = self.scrollViewInsetsDefaultValue
}, completion: { finished in
self.animator.pullToRefresh(self, progressDidChange: 0)
})
}
}
| mit | 8a9d2aacce22e9f2aaa84bc62c7b8857 | 39.81761 | 142 | 0.655778 | 5.350371 | false | false | false | false |
codingforentrepreneurs/Django-to-iOS | Source/ios/srvup/ProjectTableViewController.swift | 1 | 5131 | //
// ProjectTableViewController.swift
// srvup
//
// Created by Justin Mitchel on 6/16/15.
// Copyright (c) 2015 Coding for Entrepreneurs. All rights reserved.
//
import UIKit
import KeychainAccess
class ProjectTableViewController: UITableViewController {
var projects = [Project]()
let keychain = Keychain(service: "com.codingforentrepreneurs.srvup")
let user = User()
override func viewWillAppear(animated: Bool) {
user.checkToken()
}
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = .blackColor()
self.tableView.separatorStyle = UITableViewCellSeparatorStyle.None
let btn = UINavButton(title: "Logout", direction: UIButtonDirection.Right, parentView: self.tableView)
btn.addTarget(self, action: "doLogout:", forControlEvents: UIControlEvents.TouchUpInside)
btn.titleLabel?.adjustsFontSizeToFitWidth = true
self.tableView.addSubview(btn)
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem()
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
tableView.deselectRowAtIndexPath(indexPath, animated: true)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Potentially incomplete method implementation.
// Return the number of sections.
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete method implementation.
// Return the number of rows in the section.
return self.projects.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! ProjectTableCell
let project = self.projects[indexPath.row]
// Configure the cell...
// cell.textLabel?.text = "\(indexPath.row + 1) - \(self.projects[indexPath.row].title)"
if project.imageUrlString != nil {
let imageUrl = NSURL(string: project.imageUrlString!)
let data = NSData(contentsOfURL: imageUrl!)
let image = UIImage(data: data!)
// let imageView = UIimageView()
cell.projectImage.image = image
}
cell.backgroundColor = self.view.backgroundColor
cell.projectLabel.text = "\(project.title)"
return cell
}
func doLogout(sender:AnyObject) {
// println("logout")
self.keychain["token"] = nil
self.navigationController?.popViewControllerAnimated(true)
self.dismissViewControllerAnimated(true, completion: nil)
}
/*
// Override to support conditional editing of the table view.
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return NO if you do not want the specified item to be editable.
return true
}
*/
/*
// Override to support editing the table view.
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
// Delete the row from the data source
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
} else if editingStyle == .Insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// Override to support rearranging the table view.
override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return NO if you do not want the item to be re-orderable.
return true
}
*/
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
let vc = segue.destinationViewController as! LectureListTableViewController
let indexPath = self.tableView.indexPathForSelectedRow()
let project = self.projects[indexPath!.row]
vc.project = project
}
}
| apache-2.0 | 75d20b0eaec6775904fae5caec7d9186 | 35.390071 | 157 | 0.677646 | 5.378407 | false | false | false | false |
dzenbot/XCSwiftr | XCSwiftr/Classes/ViewControllers/XCSConverterWindowController.swift | 1 | 3063 | //
// XCSConverterWindowController.swift
// XCSwiftr
//
// Created by Ignacio Romero on 4/3/16.
// Copyright © 2016 DZN Labs. All rights reserved.
//
import Cocoa
private let XCSwifterDomain = "com.dzn.XCSwiftr"
extension Bool {
init<T: Integer>(_ integer: T) {
self.init(integer != 0)
}
}
class XCSConverterWindowController: NSWindowController, NSTextViewDelegate {
let commandController = XCSCommandController()
let snippetManager = XCSSnippetManager(domain: XCSwifterDomain)
var initialText: String?
var inPlugin: Bool = false
var autoConvert: Bool = false
#if PLUGIN
@IBOutlet var primaryTextView: DVTSourceTextView!
@IBOutlet var secondaryTextView: DVTSourceTextView!
#else
@IBOutlet var primaryTextView: NSTextView!
@IBOutlet var secondaryTextView: NSTextView!
#endif
@IBOutlet var autoCheckBox: NSButton!
@IBOutlet var cancelButton: NSButton!
@IBOutlet var acceptButton: NSButton!
@IBOutlet var progressIndicator: NSProgressIndicator!
var loading: Bool = false {
didSet {
if loading {
self.progressIndicator.startAnimation(self)
self.acceptButton.title = ""
} else {
self.progressIndicator.stopAnimation(self)
self.acceptButton.title = "Convert"
}
}
}
// MARK: View lifecycle
override func windowDidLoad() {
super.windowDidLoad()
primaryTextView.delegate = self
primaryTextView.string = ""
secondaryTextView.string = ""
if let string = initialText {
primaryTextView.string = string
convertToSwift(objcString: string)
updateAcceptButton()
}
if inPlugin == true {
cancelButton.isHidden = false
}
}
// MARK: Actions
func convertToSwift(objcString: String?) {
guard let objcString = objcString else { return }
loading = true
snippetManager.cacheTemporary(snippet: objcString) { (filePath) in
if let path = filePath {
self.commandController.objc2Swift(path) { (result) in
self.loading = false
self.secondaryTextView.string = result
}
}
}
}
func updateAcceptButton() {
acceptButton.isEnabled = ((primaryTextView.string?.characters.count)! > 0)
}
// MARK: IBActions
@IBAction func convertAction(sender: AnyObject) {
convertToSwift(objcString: primaryTextView.string)
}
@IBAction func dismissAction(sender: AnyObject) {
guard let window = window, let sheetParent = window.sheetParent else { return }
sheetParent.endSheet(window, returnCode: NSModalResponseCancel)
}
@IBAction func autoConvert(sender: AnyObject) {
autoConvert = Bool(autoCheckBox.state)
}
// MARK: NSTextViewDelegate
func textDidChange(_ notification: Notification) {
updateAcceptButton()
}
}
| mit | 127f00a04b843f79f91ec79b25975fc9 | 23.496 | 87 | 0.629001 | 4.791862 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.