repo_name
stringlengths
7
91
path
stringlengths
8
658
copies
stringclasses
125 values
size
stringlengths
3
6
content
stringlengths
118
674k
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
6.09
99.2
line_max
int64
17
995
alpha_frac
float64
0.3
0.9
ratio
float64
2
9.18
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
tianyc1019/LSPhotoPicker
LSPhotoPicker/LSPhotoPicker/LSPhotoPicker/LSPhotoPicker/view/LSAlbumToolbarView.swift
1
4018
// // LSAlbumToolbarView.swift // LSPhotoPicker // // Created by John_LS on 2017/2/8. // Copyright © 2017年 John_LS. All rights reserved. // import UIKit protocol LSAlbumToolbarViewDelegate: class{ func ls_onFinishedButtonClicked() } class LSAlbumToolbarView: UIView { var doneNumberAnimationLayer: UIView? var labelTextView: UILabel? var buttonDone: UIButton? var doneNumberContainer: UIView? weak var delegate: LSAlbumToolbarViewDelegate? override init(frame: CGRect) { super.init(frame: frame) self.setupView() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.setupView() } private func setupView(){ self.backgroundColor = UIColor.white let bounds = self.bounds let width = bounds.width let toolbarHeight = bounds.height let buttonWidth: CGFloat = 40 let buttonHeight: CGFloat = 40 let padding:CGFloat = 5 // button self.buttonDone = UIButton(type: .custom) buttonDone!.frame = CGRect(x: width - buttonWidth - padding, y:(toolbarHeight - buttonHeight) / 2, width: buttonWidth, height: buttonHeight) buttonDone!.setTitle(LSPhotoPickerConfig.ButtonDone, for: .normal) buttonDone!.titleLabel?.font = UIFont.systemFont(ofSize: 16.0) buttonDone!.setTitleColor(UIColor.black, for: .normal) buttonDone!.addTarget(self, action: #selector(LSAlbumToolbarView.ls_eventDoneClicked), for: .touchUpInside) buttonDone!.isEnabled = true buttonDone!.setTitleColor(UIColor.gray, for: .disabled) self.addSubview(self.buttonDone!) // done number let labelWidth:CGFloat = 20 let labelX = buttonDone!.frame.minX - labelWidth let labelY = (toolbarHeight - labelWidth) / 2 self.doneNumberContainer = UIView(frame: CGRect(x:labelX,y: labelY,width: labelWidth, height: labelWidth)) let labelRect = CGRect(x:0, y:0, width: labelWidth, height: labelWidth) self.doneNumberAnimationLayer = UIView.init(frame: labelRect) self.doneNumberAnimationLayer!.backgroundColor = UIColor.init(red: 7/255, green: 179/255, blue: 20/255, alpha: 1) self.doneNumberAnimationLayer!.layer.cornerRadius = labelWidth / 2 doneNumberContainer!.addSubview(self.doneNumberAnimationLayer!) self.labelTextView = UILabel(frame: labelRect) self.labelTextView!.textAlignment = .center self.labelTextView!.backgroundColor = UIColor.clear self.labelTextView!.textColor = UIColor.white doneNumberContainer!.addSubview(self.labelTextView!) doneNumberContainer?.isHidden = true self.addSubview(self.doneNumberContainer!) // 添加分割线 let divider = UIView(frame: CGRect(x:0, y:0, width:width, height:1)) divider.backgroundColor = UIColor.init(red: 0, green: 0, blue: 0, alpha: 0.15) self.addSubview(divider) } // MARK: - toolbar delegate func ls_eventDoneClicked(){ if let delegate = self.delegate { delegate.ls_onFinishedButtonClicked() } } func ls_changeNumber(number:Int){ self.labelTextView?.text = String(number) if number > 0 { self.buttonDone?.isEnabled = true self.doneNumberContainer?.isHidden = false self.doneNumberAnimationLayer!.transform = CGAffineTransform(scaleX: 0.5, y: 0.5) UIView.animate(withDuration: 0.5, delay: 0, usingSpringWithDamping: 0.3, initialSpringVelocity: 10, options: UIViewAnimationOptions.curveEaseIn, animations: { () -> Void in self.doneNumberAnimationLayer!.transform = CGAffineTransform(scaleX: 1.0, y: 1.0) }, completion: nil) } else { self.buttonDone?.isEnabled = false self.doneNumberContainer?.isHidden = true } } }
mit
2851924616b878cce120dc3486c813fa
37.509615
184
0.649688
4.48991
false
false
false
false
CocoaLumberjack/CocoaLumberjack
Sources/CocoaLumberjackSwift/DDLog+Combine.swift
2
4412
// Software License Agreement (BSD License) // // Copyright (c) 2010-2022, Deusty, LLC // All rights reserved. // // Redistribution and use of this software in source and binary forms, // with or without modification, are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Neither the name of Deusty nor the names of its contributors may be used // to endorse or promote products derived from this software without specific // prior written permission of Deusty, LLC. #if arch(arm64) || arch(x86_64) #if canImport(Combine) import Combine #if SWIFT_PACKAGE import CocoaLumberjack import CocoaLumberjackSwiftSupport #endif @available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) extension DDLog { // MARK: - Subscription private final class Subscription<S: Subscriber>: NSObject, DDLogger, Combine.Subscription where S.Input == DDLogMessage { // swiftlint:disable:this opening_brace private var subscriber: S? private weak var log: DDLog? /// Not used but `DDLogger` requires it. /// The preferred way to achieve this is to use the `map` Combine operator of the publisher. /// Example: /// ``` /// DDLog.sharedInstance.messagePublisher() /// .map { message in /* format message */ } /// .sink(receiveValue: { formattedMessage in /* process formattedMessage */ }) /// ``` #if compiler(>=5.7) var logFormatter: (any DDLogFormatter)? #else var logFormatter: DDLogFormatter? #endif init(log: DDLog, with logLevel: DDLogLevel, subscriber: S) { self.subscriber = subscriber self.log = log super.init() log.add(self, with: logLevel) } func request(_ demand: Subscribers.Demand) { // The log messages are endless until canceled, so we won't do any demand management. // Combine operators can be used to deal with it as needed. } func cancel() { log?.remove(self) subscriber = nil } func log(message logMessage: DDLogMessage) { _ = subscriber?.receive(logMessage) } } // MARK: - Publisher @available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) public struct MessagePublisher: Combine.Publisher { public typealias Output = DDLogMessage public typealias Failure = Never private let log: DDLog private let logLevel: DDLogLevel public init(log: DDLog, with logLevel: DDLogLevel) { self.log = log self.logLevel = logLevel } public func receive<S>(subscriber: S) where S: Subscriber, S.Failure == Failure, S.Input == Output { // swiftlint:disable:this opening_brace let subscription = Subscription(log: log, with: logLevel, subscriber: subscriber) subscriber.receive(subscription: subscription) } } /** * Creates a message publisher. * * The publisher will add and remove loggers as subscriptions are added and removed. * * The level that you provide here is a preemptive filter (for performance). * That is, the level specified here will be used to filter out logMessages so that * the logger is never even invoked for the messages. * * More information: * See -[DDLog addLogger:with:] * * - Parameter logLevel: preemptive filter of the message returned by the publisher. All levels are sent by default * - Returns: A MessagePublisher that emits LogMessages filtered by the specified logLevel **/ public func messagePublisher(with logLevel: DDLogLevel = .all) -> MessagePublisher { MessagePublisher(log: self, with: logLevel) } } @available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) extension Publisher where Output == DDLogMessage { #if compiler(>=5.7) public func formatted(with formatter: any DDLogFormatter) -> Publishers.CompactMap<Self, String> { compactMap { formatter.format(message: $0) } } #else public func formatted(with formatter: DDLogFormatter) -> Publishers.CompactMap<Self, String> { compactMap { formatter.format(message: $0) } } #endif } #endif #endif
bsd-3-clause
a2d40f1f2d3e682f2fca7c6577e854c1
33.740157
119
0.651405
4.479188
false
false
false
false
huangboju/QMUI.swift
QMUI.swift/QMUIKit/UIComponents/QMUIEmotionView.swift
1
19690
// // QMUIEmotionView.swift // QMUI.swift // // Created by 黄伯驹 on 2017/7/10. // Copyright © 2017年 伯驹 黄. All rights reserved. // /** * 代表一个表情的数据对象 */ class QMUIEmotion: NSObject { /// 当前表情的标识符,可用于区分不同表情 var identifier: String /// 当前表情展示出来的名字,可用于输入框里的占位文字,例如“[委屈]” var displayName: String /// 表情对应的图片。若表情图片存放于项目内,则建议用当前表情的`identifier`作为图片名 var image: UIImage? /// 生成一个`QMUIEmotion`对象,并且以`identifier`为图片名在当前项目里查找,作为表情的图片 /// /// - Parameters: /// - identifier: 表情的标识符,也会被当成图片的名字 /// - displayName: 表情展示出来的名字 /// - image: 展示的图片 init(identifier: String, displayName: String, image: UIImage? = nil) { self.identifier = identifier self.displayName = displayName self.image = image } override var description: String { return "\(super.description) identifier: \(identifier), displayName: \(displayName)" } } @objc fileprivate protocol QMUIEmotionPageViewDelegate: NSObjectProtocol { @objc optional func emotionPageView(_ emotionPageView: QMUIEmotionPageView, didSelectEmotion emotion: QMUIEmotion, at index: Int) @objc optional func didSelectDeleteButton(in emotionPageView: QMUIEmotionPageView) } /** * 表情控件,支持任意表情的展示,每个表情以相同的大小显示。 * * 使用方式: * * - 通过`initWithFrame:`初始化,如果面板高度不变,建议在init时就设置好,若最终布局以父类的`layoutSubviews`为准,则也可通过`init`方法初始化,再在`layoutSubviews`里计算布局 * - 通过调整`paddingInPage`、`emotionSize`等变量来自定义UI * - 通过`emotions`设置要展示的表情 * - 通过`didSelectEmotionBlock`设置选中表情时的回调,通过`didSelectDeleteButtonBlock`来响应面板内的删除按钮 * - 为`sendButton`添加`addTarget:action:forState:`事件,从而触发发送逻辑 * * 本控件支持通过`UIAppearance`设置全局的默认样式。若要修改控件内的`UIPageControl`的样式,可通过`[UIPageControl appearanceWhenContainedIn:[QMUIEmotionView class], nil]`的方式来修改。 */ class QMUIEmotionView: UIView { /// 要展示的所有表情 var emotions: [QMUIEmotion] = [] { didSet { pageEmotions() } } /** * 选中表情时的回调 * @argv index 被选中的表情在`emotions`里的索引 * @argv emotion 被选中的表情对应的`QMUIEmotion`对象 * @see QMUIEmotion */ var didSelectEmotionClosure: ((Int, QMUIEmotion) -> Void)? /// 删除按钮的点击事件回调 var didSelectDeleteButtonClosure: (() -> Void)? /// 用于展示表情面板的横向滚动collectionView,布局撑满整个控件 private(set) var collectionView: UICollectionView! /// 用于横向按页滚动的collectionViewLayout private(set) var collectionViewLayout: UICollectionViewFlowLayout! /// 控件底部的分页控件,可点击切换表情页面 private(set) var pageControl: UIPageControl! /// 控件右下角的发送按钮 private(set) var sendButton: QMUIButton! /// 每一页表情的上下左右padding,默认为{18, 18, 65, 18} var paddingInPage = UIEdgeInsets(top: 18, left: 18, bottom: 65, right: 18) /// 每一页表情允许的最大行数,默认为4 var numberOfRowsPerPage = 4 /// 表情的图片大小,不管`QMUIEmotion.image.size`多大,都会被缩放到`emotionSize`里显示,默认为{30, 30} var emotionSize = CGSize(width: 30, height: 30) /// 表情点击时的背景遮罩相对于`emotionSize`往外拓展的区域,负值表示遮罩比表情还大,正值表示遮罩比表情还小,默认为{-3, -3, -3, -3} var emotionSelectedBackgroundExtension = UIEdgeInsets(top: -3, left: -3, bottom: -3, right: -3) /// 表情与表情之间的最小水平间距,默认为10 var minimumEmotionHorizontalSpacing: CGFloat = 10 /// 表情面板右下角的删除按钮的图片,默认为`QMUIHelper.image(name: "QMUI_emotion_delete")` var deleteButtonImage = QMUIHelper.image(name: "QMUI_emotion_delete") /// 发送按钮的文字样式,默认为{NSFontAttributeName: UIFontMake(15), NSForegroundColorAttributeName: UIColorWhite} var sendButtonTitleAttributes: [NSAttributedString.Key: Any] = [:] { didSet { if let title = sendButton.currentTitle { sendButton.setAttributedTitle(NSAttributedString(string: title, attributes: sendButtonTitleAttributes), for: .normal) } } } /// 发送按钮的背景色,默认为`UIColorBlue` var sendButtonBackgroundColor = UIColorBlue { didSet { sendButton.backgroundColor = sendButtonBackgroundColor } } /// 发送按钮的圆角大小,默认为4 var sendButtonCornerRadius: CGFloat = 4 { didSet { sendButton.layer.cornerRadius = sendButtonCornerRadius } } /// 发送按钮布局时的外边距,相对于控件右下角。仅right/bottom有效,默认为{0, 0, 16, 16} var sendButtonMargins = UIEdgeInsets(top: 0, left: 0, bottom: 16, right: 16) /// 分页控件距离底部的间距,默认为22 var pageControlMarginBottom: CGFloat = 22 private var pagedEmotions: [[QMUIEmotion]]! private var isDebug = false override init(frame: CGRect) { super.init(frame: frame) didInitialized(with: frame) } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) didInitialized(with: .zero) } func didInitialized(with frame: CGRect) { isDebug = false pagedEmotions = [[]] collectionViewLayout = UICollectionViewFlowLayout() collectionViewLayout.scrollDirection = .horizontal collectionViewLayout.minimumLineSpacing = 0 collectionViewLayout.minimumInteritemSpacing = 0 collectionViewLayout.sectionInset = UIEdgeInsets.zero collectionView = UICollectionView(frame: CGRect(x: qmui_safeAreaInsets.left, y: qmui_safeAreaInsets.top, width: frame.width - qmui_safeAreaInsets.horizontalValue, height: frame.height - qmui_safeAreaInsets.verticalValue), collectionViewLayout: collectionViewLayout) collectionView.backgroundColor = UIColorClear collectionView.scrollsToTop = false collectionView.isPagingEnabled = true collectionView.showsHorizontalScrollIndicator = false collectionView.dataSource = self collectionView.delegate = self collectionView.register(QMUIEmotionPageView.self, forCellWithReuseIdentifier: "page") addSubview(collectionView) pageControl = UIPageControl() pageControl.addTarget(self, action: #selector(handlePageControlEvent(_:)), for: .valueChanged) pageControl.pageIndicatorTintColor = UIColor(r: 210, g: 210, b: 210) pageControl.currentPageIndicatorTintColor = UIColor(r: 162, g: 162, b: 162) addSubview(pageControl) sendButton = QMUIButton() sendButton.setTitle("发送", for: .normal) sendButton.contentEdgeInsets = UIEdgeInsets(top: 5, left: 17, bottom: 5, right: 17) sendButton.sizeToFit() addSubview(sendButton) } override func layoutSubviews() { super.layoutSubviews() let collectionViewFrame = bounds.insetEdges(qmui_safeAreaInsets) let collectionViewSizeChanged = collectionView.bounds.size != collectionViewFrame.size collectionViewLayout.itemSize = collectionView.bounds.size // 先更新 itemSize 再设置 collectionView.frame,否则会触发系统的 UICollectionViewFlowLayoutBreakForInvalidSizes 断点 collectionView.frame = collectionViewFrame if collectionViewSizeChanged { pageEmotions() } sendButton.qmui_right = qmui_width - qmui_safeAreaInsets.right - sendButtonMargins.right sendButton.qmui_bottom = qmui_height - qmui_safeAreaInsets.bottom - sendButtonMargins.bottom let pageControlHeight: CGFloat = 16 let pageControlMaxX: CGFloat = sendButton.qmui_left let pageControlMinX: CGFloat = qmui_width - pageControlMaxX pageControl.frame = CGRect(x: pageControlMinX, y: qmui_height - qmui_safeAreaInsets.bottom - pageControlMarginBottom - pageControlHeight, width: pageControlMaxX - pageControlMinX, height: pageControlHeight) } private func pageEmotions() { pagedEmotions.removeAll(keepingCapacity: true) pageControl.numberOfPages = 0 if !collectionView.bounds.isEmpty && !emotions.isEmpty && !emotionSize.isEmpty { let contentWidthInPage = collectionView.bounds.width - paddingInPage.horizontalValue let maximumEmotionCountPerRowInPage = (contentWidthInPage + minimumEmotionHorizontalSpacing) / (emotionSize.width + minimumEmotionHorizontalSpacing) let maximumEmotionCountPerPage = Int(maximumEmotionCountPerRowInPage * CGFloat(numberOfRowsPerPage) - 1) // 删除按钮占一个表情位置 let pageCount = Int(ceil(Float(emotions.count) / Float(maximumEmotionCountPerPage))) for i in 0 ..< pageCount { let startIdx = maximumEmotionCountPerPage * i // 最后一页可能不满一整页,所以取剩余的所有表情即可 var endIdx = maximumEmotionCountPerPage if maximumEmotionCountPerPage > emotions.count { endIdx = emotions.count - startIdx } let emotionForPage = emotions[startIdx ..< endIdx] pagedEmotions.append(Array(emotionForPage)) } pageControl.numberOfPages = pageCount } collectionView.reloadData() collectionView.qmui_scrollToTop() } @objc func handlePageControlEvent(_ pageControl: UIPageControl) { collectionView.scrollToItem(at: IndexPath(row: pageControl.currentPage, section: 0), at: .centeredHorizontally, animated: true) } } extension QMUIEmotionView: QMUIEmotionPageViewDelegate { fileprivate func emotionPageView(_: QMUIEmotionPageView, didSelectEmotion emotion: QMUIEmotion, at _: Int) { guard let i = emotions.firstIndex(of: emotion) else { return } didSelectEmotionClosure?(i, emotion) } fileprivate func didSelectDeleteButton(in _: QMUIEmotionPageView) { didSelectDeleteButtonClosure?() } } extension QMUIEmotionView: UICollectionViewDataSource { func collectionView(_: UICollectionView, numberOfItemsInSection _: Int) -> Int { return pagedEmotions.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "page", for: indexPath) let pageView = cell as? QMUIEmotionPageView pageView?.delegate = self pageView?.emotions = pagedEmotions[indexPath.item] pageView?.padding = paddingInPage pageView?.numberOfRows = numberOfRowsPerPage pageView?.emotionSize = emotionSize pageView?.emotionSelectedBackgroundExtension = emotionSelectedBackgroundExtension pageView?.minimumEmotionHorizontalSpacing = minimumEmotionHorizontalSpacing pageView?.deleteButton.setImage(deleteButtonImage, for: .normal) pageView?.deleteButton.setImage(deleteButtonImage?.qmui_image(alpha: ButtonHighlightedAlpha), for: .highlighted) pageView?.isDebug = isDebug pageView?.setNeedsDisplay() return cell } } extension QMUIEmotionView: UICollectionViewDelegate { func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) { if scrollView == collectionView { let currentPage = round(scrollView.contentOffset.x / scrollView.bounds.width) pageControl.currentPage = Int(currentPage) } } } /// 表情面板每一页的cell,在drawRect里将所有表情绘制上去,同时自带一个末尾的删除按钮 fileprivate class QMUIEmotionPageView: UICollectionViewCell { fileprivate weak var delegate: (QMUIEmotionView & QMUIEmotionPageViewDelegate)? /// 表情被点击时盖在表情上方用于表示选中的遮罩 fileprivate var emotionSelectedBackgroundView: UIView! /// 表情面板右下角的删除按钮 fileprivate var deleteButton: QMUIButton! /// 分配给当前pageView的所有表情 fileprivate var emotions: [QMUIEmotion]? /// 记录当前pageView里所有表情的可点击区域的rect,在drawRect:里更新,在tap事件里使用 fileprivate var emotionHittingRects: [CGRect]! /// 负责实现表情的点击 fileprivate var tapGestureRecognizer: UITapGestureRecognizer! /// 整个pageView内部的padding fileprivate var padding: UIEdgeInsets = .zero /// 每个pageView能展示表情的行数 fileprivate var numberOfRows: Int = 0 /// 每个表情的绘制区域大小,表情图片最终会以UIViewContentModeScaleAspectFit的方式撑满这个大小。表情计算布局时也是基于这个大小来算的。 fileprivate var emotionSize: CGSize = .zero /// 点击表情时出现的遮罩要在表情所在的矩形位置拓展多少空间,负值表示遮罩比emotionSize更大,正值表示遮罩比emotionSize更小。最终判断表情点击区域时也是以拓展后的区域来判定的 fileprivate var emotionSelectedBackgroundExtension: UIEdgeInsets = .zero /// 表情与表情之间的水平间距的最小值,实际值可能比这个要大一点(pageView会把剩余空间分配到表情的水平间距里) fileprivate var minimumEmotionHorizontalSpacing: CGFloat = 0 /// debug模式会把表情的绘制矩形显示出来 fileprivate var isDebug = false override init(frame: CGRect) { super.init(frame: frame) backgroundColor = UIColorClear emotionSelectedBackgroundView = UIView() emotionSelectedBackgroundView.isUserInteractionEnabled = false emotionSelectedBackgroundView.backgroundColor = UIColor(r: 0, g: 0, b: 0, a: 0.16) emotionSelectedBackgroundView.layer.cornerRadius = 3 emotionSelectedBackgroundView.alpha = 0 addSubview(emotionSelectedBackgroundView) deleteButton = QMUIButton() deleteButton.adjustsButtonWhenDisabled = false // 去掉QMUIButton默认的高亮动画,从而加快连续快速点击的响应速度 deleteButton.qmui_automaticallyAdjustTouchHighlightedInScrollView = true deleteButton.addTarget(self, action: #selector(handleDeleteButtonEvent), for: .touchUpInside) addSubview(deleteButton) emotionHittingRects = [] tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(handleTapGestureRecognizer)) addGestureRecognizer(tapGestureRecognizer) } override func layoutSubviews() { super.layoutSubviews() // 删除按钮必定布局到最后一个表情的位置,且与表情上下左右居中 deleteButton.sizeToFit() let deleteButtonW = deleteButton.frame.width let deleteButtonH = deleteButton.frame.height deleteButton.frame = deleteButton.frame.setXY(flat(bounds.width - padding.right - deleteButtonW - (emotionSize.width - deleteButtonW) / 2.0), flat(bounds.height - padding.bottom - deleteButtonH - (emotionSize.height - deleteButtonH) / 2.0)) } override func draw(_: CGRect) { emotionHittingRects.removeAll(keepingCapacity: true) let contentSize = bounds.insetEdges(padding).size let emotionCountPerRow = (contentSize.width + minimumEmotionHorizontalSpacing) / (emotionSize.width + minimumEmotionHorizontalSpacing) let emotionHorizontalSpacing = flat((contentSize.width - emotionCountPerRow * emotionSize.width) / (emotionCountPerRow - 1)) let numberOfRows = CGFloat(self.numberOfRows) let emotionVerticalSpacing = flat((contentSize.height - numberOfRows * emotionSize.height) / (numberOfRows - 1)) var emotionOrigin = CGPoint.zero guard let emotions = emotions else { return } for (index, emotion) in emotions.enumerated() { let i = CGFloat(index) let row = CGFloat(Int(i / emotionCountPerRow)) emotionOrigin.x = padding.left + (emotionSize.width + emotionHorizontalSpacing) * i.truncatingRemainder(dividingBy: emotionCountPerRow) emotionOrigin.y = padding.top + (emotionSize.height + emotionVerticalSpacing) * row let emotionRect = CGRect(origin: emotionOrigin, size: emotionSize) let emotionHittingRect = emotionRect.insetEdges(emotionSelectedBackgroundExtension) emotionHittingRects.append(emotionHittingRect) drawImage(emotion.image, in: emotionRect) } } required init?(coder _: NSCoder) { fatalError("init(coder:) has not been implemented") } private func drawImage(_ image: UIImage?, in contextRect: CGRect) { guard let image = image else { return } let imageSize = image.size let horizontalRatio = contextRect.width / imageSize.width let verticalRatio = contextRect.height / imageSize.height // 表情图片按UIViewContentModeScaleAspectFit的方式来绘制 let ratio = min(horizontalRatio, verticalRatio) var drawingRect = CGRect.zero drawingRect.size.width = imageSize.width * ratio drawingRect.size.height = imageSize.height * ratio drawingRect = drawingRect.setXY(contextRect.minXHorizontallyCenter(drawingRect), contextRect.minYVerticallyCenter(drawingRect)) if isDebug { let context = UIGraphicsGetCurrentContext() context?.setLineWidth(PixelOne) context?.setStrokeColor(UIColorTestRed.cgColor) context?.stroke(contextRect.insetBy(dx: PixelOne / 2.0, dy: PixelOne / 2.0)) } image.draw(in: drawingRect) } @objc func handleDeleteButtonEvent(_: QMUIButton) { delegate?.didSelectDeleteButton(in: self) } @objc func handleTapGestureRecognizer(_ gestureRecognizer: UITapGestureRecognizer) { let location = gestureRecognizer.location(in: self) guard let emotions = emotions else { return } for i in 0 ..< emotionHittingRects.count { let rect = emotionHittingRects[i] if rect.contains(location) { let emotion = emotions[i] emotionSelectedBackgroundView.frame = rect UIView.animate(withDuration: 0.08, animations: { self.emotionSelectedBackgroundView.alpha = 1 }, completion: { _ in UIView.animate(withDuration: 0.08, animations: { self.emotionSelectedBackgroundView.alpha = 0 }) }) delegate?.emotionPageView(self, didSelectEmotion: emotion, at: i) if isDebug { print("最终确定了点击的是当前页里的第 %\(i) 个表情,\(emotion)") } return } } } }
mit
d64b8a00244aa18ef99e3026aa2d097a
39.242494
273
0.691248
4.535398
false
false
false
false
ycaihua/Paranormal
Paranormal/ParanormalTests/Tools/ZoomToolTests.swift
3
2880
import Cocoa import Quick import Nimble import Paranormal class ZoomToolTests: QuickSpec { override func spec() { describe("ZoomTool") { var editorViewController : EditorViewController? var document : Document? var editorView : EditorView? beforeEach { editorViewController = EditorViewController(nibName: "Editor", bundle: nil) editorView = editorViewController?.view as? EditorView document = DocumentController() .makeUntitledDocumentOfType("Paranormal", error: nil) as? Document editorViewController?.document = document } var getTranslate : () -> CGVector = { let point = CGPointApplyAffineTransform(CGPoint(x: 0, y:0), editorView!.transform) return CGVector(dx: point.x, dy: point.y) } var getScale : () -> CGVector = { let pt = getTranslate() let point = CGPointApplyAffineTransform(CGPoint(x: 1, y:1), editorView!.transform) return CGVector(dx: point.x - pt.dx, dy: point.y - pt.dy) } describe("When clicking on the canvas") { beforeEach() { editorViewController? .setZoomAroundApplicationSpacePoint(NSPoint(x:0, y:0), scale: 2.0) editorViewController?.translateView(4.0, 8.0) } xit("scales the editorView around the click point") { let zoomTool = ZoomTool() zoomTool.mouseDownAtPoint(NSPoint(x:30, y:30), editorViewController: editorViewController!) zoomTool.mouseUpAtPoint(NSPoint(x:30, y:30), editorViewController: editorViewController!) expect(getScale()).to(equal(CGVector(dx: 3, dy: 3))) expect(getTranslate()).to(equal(CGVector(dx:-26.0, dy:-22))) } xit("Triggers a PNNotificationZoomChanged notification") { var ranNotification = false NSNotificationCenter.defaultCenter() .addObserverForName(PNNotificationZoomChanged, object: nil, queue: nil, usingBlock: { (n) -> Void in ranNotification = true }) let zoomTool = ZoomTool() zoomTool.mouseDownAtPoint(NSPoint(x:30, y:30), editorViewController: editorViewController!) zoomTool.mouseUpAtPoint(NSPoint(x:30, y:30), editorViewController: editorViewController!) expect(ranNotification).toEventually(beTrue(())) } } } } }
mit
71aed28718b38756af09bc4c59f50d75
41.352941
98
0.532986
5.393258
false
false
false
false
lizhuoli1126/e-lexer
other/e-lexer-swift/e-lexer/production.swift
1
862
// // production.swift // e-lexer // // Created by lizhuoli on 15/12/5. // Copyright © 2015年 lizhuoli. All rights reserved. // import Foundation enum SymbolType:Int { case Terminal = 1 case NonTerminal = 0 } struct Symbol: Equatable { init(value: Character, type: SymbolType) { self.value = value self.type = type } var value:Character var type:SymbolType } func ==(lhs: Symbol, rhs: Symbol) -> Bool { return lhs.value == rhs.value && lhs.type == rhs.type } class Production: Hashable { init(){ } deinit{ } var left:Symbol? var right:[Symbol] = [] var hashValue: Int { get { return "\(self.left), \(self.right)".hashValue } } } func ==(lhs: Production, rhs: Production) -> Bool { return lhs.left == lhs.left && lhs.right == rhs.right }
mit
d67547b02109c50eed2c6d08f190d0f4
17.297872
58
0.583236
3.46371
false
false
false
false
scoremedia/Fisticuffs
Samples/ControlsSample.swift
1
2763
// The MIT License (MIT) // // Copyright (c) 2015 theScore Inc. // // 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 Fisticuffs class ControlsViewModel { //MARK: Colors let red = Observable<Float>(0.1) let green = Observable<Float>(0.8) let blue = Observable<Float>(0.5) lazy var color: Computed<UIColor> = Computed { [red = self.red, green = self.green, blue = self.blue] in return UIColor( red: CGFloat(red.value), green: CGFloat(green.value), blue: CGFloat(blue.value), alpha: 1.0 ) } //MARK: Visibility let alpha = Observable<Float>(1.0) let hidden = Observable<Bool>(false) } class ControlsSampleViewController: UITableViewController { @IBOutlet var resultsDisplay: UIView! @IBOutlet var redSlider: UISlider! @IBOutlet var greenSlider: UISlider! @IBOutlet var blueSlider: UISlider! @IBOutlet var alphaSlider: UISlider! @IBOutlet var hiddenSwitch: UISwitch! //MARK: - let viewModel = ControlsViewModel() //MARK: - override func viewDidLoad() { super.viewDidLoad() resultsDisplay.b_backgroundColor.bind(viewModel.color) resultsDisplay.b_alpha.bind(viewModel.alpha, BindingHandlers.transform { value in CGFloat(value) }) resultsDisplay.b_hidden.bind(viewModel.hidden) redSlider.b_value.bind(viewModel.red) greenSlider.b_value.bind(viewModel.green) blueSlider.b_value.bind(viewModel.blue) alphaSlider.b_value.bind(viewModel.alpha) hiddenSwitch.b_on.bind(viewModel.hidden) } }
mit
07b73ebd5a95a37e21f08d208191ec19
31.505882
108
0.674629
4.290373
false
false
false
false
plenprojectcompany/plen-Scenography_iOS
PLENConnect/Connect/ViewControllers/ProgramViewController.swift
1
8399
// // ProgramViewController.swift // Scenography // // Created by PLEN Project on 2016/03/02. // Copyright © 2016年 PLEN Project. All rights reserved. // import UIKit import MaterialKit import RxSwift import RxCocoa import RxBlocking import CoreBluetooth import Toaster // TODO: 全体的に汚い class ProgramViewController: UIViewController, UIGestureRecognizerDelegate { // MARK: - IBOutlets @IBOutlet weak var playButton: UIBarButtonItem! @IBOutlet weak var programTitle: UILabel! @IBOutlet weak var programTitleHolder: UIView! @IBOutlet weak var tabBarHolder: UIView! @IBOutlet weak var leftContainer: UIView! @IBOutlet weak var rightContainer: UIView! // MARK: - Variables and Constants fileprivate var programViewController: PlenProgramViewController! fileprivate var motionPageViewController: PlenMotionPageViewController! fileprivate var connectionLogs = [String: PlenConnectionLog]() fileprivate let _disposeBag = DisposeBag() fileprivate var modeDisposeBag = DisposeBag() fileprivate var programPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] + "/program.json" fileprivate var connectionLogsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] + "/connectionLogs.json" var leftContainerMode = LeftContainerMode.program { didSet { updateMode() } } let rx_program = Variable(PlenProgram.Empty) var program: PlenProgram { get {return rx_program.value} set(value) {rx_program.value = value} } enum LeftContainerMode { case program case joystick } // MARK: - Lifecycle override func viewDidLoad() { super.viewDidLoad() // motion page view motionPageViewController = UIViewControllerUtil.loadChildViewController(self, container: rightContainer, childType: PlenMotionPageViewController.self) motionPageViewController.motionCategories = try! loadMotionCategories() // title programTitle.font = UIFont(name: "HelveticaNeue", size: 10) // layout let tabBar = motionPageViewController.tabBar tabBarHolder.addSubview(tabBar!) let views = ["tabBar": motionPageViewController.tabBar] tabBar?.translatesAutoresizingMaskIntoConstraints = false UIViewUtil.constrain( by: tabBarHolder, formats: ["H:|-(-1)-[tabBar]-(-1)-|", "V:|[tabBar]|"], views: views as [String : AnyObject]) makeShadow(tabBarHolder.layer) makeShadow(programTitleHolder.layer) // tap to close keyboard let gestureRecognizer = UITapGestureRecognizer(target: self, action: nil) gestureRecognizer.delegate = self view.addGestureRecognizer(gestureRecognizer) // updateMode() // TODO: Add into functions PlenConnection.defaultInstance().rx_peripheralState .filter {$0 == .connected} .subscribe {[weak self] _ in guard let s = self else {return} let peripheral = PlenConnection.defaultInstance().peripheral! s.connectionLogs[peripheral.identifier.uuidString]?.connectedCount += 1 s.connectionLogs[peripheral.identifier.uuidString]?.lastConnectedTime = Date() Toast(text: "PLEN connected", duration: Delay.short).show() s.playButton.isEnabled = true } .addDisposableTo(_disposeBag) PlenConnection.defaultInstance().rx_peripheralState .filter {$0 == .disconnected} .subscribe {[weak self] _ in guard let s = self else {return} Toast(text: "PLEN disconnected", duration: Delay.short).show() s.playButton.isEnabled = false } .addDisposableTo(_disposeBag) if !PlenConnection.defaultInstance().isConnected(){ PlenAlert.autoConnect() } } override func viewDidDisappear(_ animated: Bool) { try! program.toData().write(to: URL(fileURLWithPath: programPath), options: []) try! PlenConnectionLog.toData(connectionLogs.map {$0.1}).write(to: URL(fileURLWithPath: connectionLogsPath), options: []) } override func viewDidAppear(_ animated: Bool) { guard let data = try? Data(contentsOf: URL(fileURLWithPath: programPath)) else {return} program = try! PlenProgram.fromJSON(data, motionCategories: motionPageViewController.motionCategories) guard let data2 = try? Data(contentsOf: URL(fileURLWithPath: connectionLogsPath)) else {return} connectionLogs = Dictionary(pairs: try! PlenConnectionLog.fromJSON(data2).map {($0.peripheralIdentifier, $0)}) } // MARK: – IBAction @IBAction func startScan(_ sender: UIBarButtonItem?) { PlenAlert.beginScan(for: self) } @IBAction func floatButtonTouched(_ sender: UIButton) { switch leftContainerMode { case .program: leftContainerMode = .joystick case .joystick: leftContainerMode = .program } } @IBAction func trashProgram(_ sender: AnyObject) { if program.sequence.isEmpty { return } presentDeleteProgramAlert() } @IBAction func playProgram(_ sender: AnyObject) { PlenConnection.defaultInstance().writeValue(Constants.PlenCommand.playProgram(program)) } // MARK: - Methods func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool { view.endEditing(true) return false } fileprivate func updateMode() { programViewController?.removeFromParentViewController() leftContainer.subviews.forEach {$0.removeFromSuperview()} modeDisposeBag = DisposeBag() switch leftContainerMode { case .program: motionPageViewController.draggable = true programTitle.text = "PROGRAM" programViewController = UIViewControllerUtil.loadChildViewController(self, container: leftContainer, childType: PlenProgramViewController.self) RxUtil.bind(rx_program, programViewController.rx_program) .addDisposableTo(modeDisposeBag) default: break } } fileprivate enum JsonError: Error { case parseError } fileprivate func loadMotionCategories() throws -> [PlenMotionCategory] { guard let path = Bundle.main.path(forResource: "json/default_motions", ofType: "json") else {return []} guard let data = try? Data(contentsOf: URL(fileURLWithPath: path)) else {return []} return try PlenMotionCategory.fromJSON(data) } fileprivate func makeShadow(_ layer: CALayer) { layer.rasterizationScale = UIScreen.main.scale; layer.shadowRadius = 0.5 layer.shadowOpacity = 0.3 layer.shadowOffset = CGSize(width: 0, height: 1); layer.shouldRasterize = true } fileprivate func makeShadow(_ layer: CALayer, z: Float) { layer.rasterizationScale = UIScreen.main.scale; layer.shadowRadius = CGFloat(z) layer.shadowOpacity = 1 / sqrt(z) layer.shadowOffset = CGSize(width: 0, height: CGFloat(z)); layer.shouldRasterize = true } fileprivate func presentDeleteProgramAlert() { let controller = UIAlertController( title: "Are you sure you want to delete this program?", message: nil, preferredStyle: .alert) controller.addAction(UIAlertAction( title: "OK", style: .default, handler: {[weak self] _ in self?.program.sequence.removeAll()})) controller.addAction(UIAlertAction( title: "Cancel", style: .default, handler: nil)) present(controller, animated: true, completion: nil) } }
mit
d6998b94106deb00976cd90a3cf0633f
32.394422
147
0.624672
5.268385
false
false
false
false
efa85/WeatherApp
WeatherApp/AppDelegate.swift
1
2858
// // AppDelegate.swift // WeatherApp // // Created by Emilio Fernandez on 24/11/14. // Copyright (c) 2014 Emilio Fernandez. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? private(set) lazy var container: Container = { let configuration = Container.Configuration( wwoBaseUrl: "http://api.worldweatheronline.com/free/v2/weather.ashx", wwoApiV2Key: PrivateKeys.wwoApiKey, modelName: "Locations.momd", storeName: "testStore.sqlite" ) return Container(configuration: configuration) }() func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { if NSClassFromString("XCTestCase") != nil { return true } // Override point for customization after application launch. window = UIWindow(frame: UIScreen.mainScreen().bounds) window!.rootViewController = container.resolveRootViewController() window!.makeKeyAndVisible() return true } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
apache-2.0
89881b7c83641cb62cbb923daef34424
41.656716
285
0.713786
5.464627
false
true
false
false
Woildan/SwiftFilePath
SwiftFilePath/PathExtensionDir.swift
1
2914
// // Dir.swift // SwiftFilePath // // Created by nori0620 on 2015/01/08. // Copyright (c) 2015年 Norihiro Sakamoto. All rights reserved. // // Instance Factories for accessing to readable iOS dirs. #if os(iOS) extension Path { public class var homeDir :Path{ let pathString = NSHomeDirectory() return Path( pathString ) } public class var temporaryDir:Path { let pathString = NSTemporaryDirectory() return Path( pathString ) } public class var documentsDir:Path { return Path.userDomainOf(.DocumentDirectory) } public class var cacheDir:Path { return Path.userDomainOf(.CachesDirectory) } private class func userDomainOf(pathEnum:NSSearchPathDirectory)->Path{ let pathString = NSSearchPathForDirectoriesInDomains(pathEnum, .UserDomainMask, true)[0] as! String return Path( pathString ) } } #endif // Add Dir Behavior to Path by extension extension Path: SequenceType { public subscript(filename: String) -> Path{ get { return self.content(filename) } } public var children:Array<Path>? { assert(self.isDir,"To get children, path must be dir< \(path_string) >") assert(self.exists,"Dir must be exists to get children.< \(path_string) >") var loadError: NSError? let contents = self.fileManager.contentsOfDirectoryAtPath(path_string , error: &loadError) if let error = loadError { println("Error< \(error.localizedDescription) >") } return contents!.map({ [unowned self] content in return self.content(content as! String) }) } public var contents:Array<Path>? { return self.children } public func content(path_string:NSString) -> Path { return Path( self.path_string.stringByAppendingPathComponent(path_string as String) ) } public func child(path:NSString) -> Path { return self.content(path) } public func mkdir() -> Result<Path,NSError> { var error: NSError? let result = fileManager.createDirectoryAtPath(path_string, withIntermediateDirectories:true, attributes:nil, error: &error ) return result ? Result(success: self) : Result(failure: error!) } public func generate() -> GeneratorOf<Path> { assert(self.isDir,"To get iterator, path must be dir< \(path_string) >") let iterator = fileManager.enumeratorAtPath(path_string) return GeneratorOf<Path>() { let optionalContent = iterator?.nextObject() as? String if var content = optionalContent { return self.content(content) } else { return .None } } } }
mit
ead6bbe34a8bb09ca7f1dca605461fe4
28.12
107
0.602335
4.681672
false
false
false
false
qingtianbuyu/Mono
Moon/Classes/Other/Theme.swift
1
809
// // Theme.swift // Moon // // Created by YKing on 16/5/17. // Copyright © 2016年 YKing. All rights reserved. // import UIKit public let ScreenBounds = UIScreen.main.bounds public let ScreenWidth = ScreenBounds.width public let exploreTopBarH:CGFloat = 60 public let exploreToolBarH:CGFloat = 50 public let commonLightColor = UIColor(red: 59/255.0, green: 186/255.0, blue: 195/225.0, alpha: 1) public let commonBgColor = UIColor(red: 239/255.0, green: 239/255.0, blue: 244/225.0, alpha: 1) public let commonCyRanColor = UIColor(red: 38/255.0, green: 162/255.0, blue: 172/225.0, alpha: 1) public let commonGrayTextColor = UIColor(red: 163/255.0, green: 163/255.0, blue: 163/225.0, alpha: 1) public let commonLineTextColor = UIColor(red: 210/255.0, green: 210/255.0, blue: 210/225.0, alpha: 1)
mit
0abb1d1a99b5159b0803342f24c1011a
37.380952
101
0.718362
2.909747
false
false
false
false
ReiVerdugo/uikit-fundamentals
step5.7-makeYourOwnAdventure-incomplete/MYOA/Adventure.swift
1
1171
// // Story.swift // MYOA // // Copyright (c) 2015 Udacity. All rights reserved. // import Foundation // MARK: - Adventure class Adventure { // MARK: Properties var credits: Credits var startNode: StoryNode! var storyNodes: [String : StoryNode] // MARK: Initializer init(dictionary: [String : AnyObject]) { // Get the two dictionaries let creditsDictionary = dictionary["credits"] as! [String : String] let storyNodesDictionary = dictionary["nodes"] as! [String : AnyObject] // Create the credits credits = Credits(dictionary: creditsDictionary) // Create the nodes array storyNodes = [String : StoryNode]() // Add a Story Node for each item in storyNodesDictionary for (key, dictionary): (String, AnyObject) in storyNodesDictionary { storyNodes[key] = StoryNode(dictionary: dictionary as! [String : AnyObject], adventure: self) } // Set the first node let startNodeKey = dictionary["startNodeKey"]as! String startNode = storyNodes[startNodeKey]! } }
mit
74ae2dea95943dcfff39b0d3a416f7ea
25.613636
105
0.605465
4.646825
false
false
false
false
sclark01/Swift_VIPER_Demo
VIPER_Demo/VIPER_Demo/Modules/PersonDetails/Presenter/PersonDetailsDataModel.swift
1
541
import Foundation struct PersonDetailsDataModel { fileprivate let person: PersonDetailsData init(person: PersonDetailsData) { self.person = person } var name: String { return "Name: \(person.name)" } var phone: String { return "Phone: \(person.phone)" } var age: String { return "Age: \(person.age)" } } extension PersonDetailsDataModel : Equatable {} func ==(lhs: PersonDetailsDataModel, rhs: PersonDetailsDataModel) -> Bool { return lhs.person == rhs.person }
mit
e8096ee6db5fbaea408eb8d0f5768c19
19.037037
75
0.637708
4.193798
false
false
false
false
myhyazid/WordPress-iOS
WordPress/Classes/ViewRelated/Notifications/Views/NoteTableViewCell.swift
3
11007
import Foundation /** * @class NoteTableViewCell * @brief The purpose of this class is to render a Notification entity, onscreen. * @details This cell should be loaded from its nib, since the autolayout constraints and outlets are not * generated via code. * Supports specific styles for Unapproved Comment Notifications, Unread Notifications, and a brand * new "Undo Deletion" mechanism has been implemented. See "NoteUndoOverlayView" for reference. */ @objc public class NoteTableViewCell : WPTableViewCell { // MARK: - Public Properties public var read: Bool = false { didSet { if read != oldValue { refreshBackgrounds() } } } public var unapproved: Bool = false { didSet { if unapproved != oldValue { refreshBackgrounds() } } } public var markedForDeletion: Bool = false { didSet { if markedForDeletion != oldValue { refreshSubviewVisibility() refreshBackgrounds() refreshUndoOverlay() } } } public var showsBottomSeparator: Bool { set { separatorsView.bottomVisible = newValue } get { return separatorsView.bottomVisible == false } } public var attributedSubject: NSAttributedString? { set { subjectLabel.attributedText = newValue setNeedsLayout() } get { return subjectLabel.attributedText } } public var attributedSnippet: NSAttributedString? { set { snippetLabel.attributedText = newValue refreshNumberOfLines() setNeedsLayout() } get { return snippetLabel.attributedText } } public var noticon: String? { set { noticonLabel.text = newValue } get { return noticonLabel.text } } public var onUndelete: (Void -> Void)? // MARK: - Public Methods public class func reuseIdentifier() -> String { return classNameWithoutNamespaces() } public func downloadGravatarWithURL(url: NSURL?) { if url == gravatarURL { return } let placeholderImage = WPStyleGuide.Notifications.gravatarPlaceholderImage // Scale down Gravatar images: faster downloads! if let unrawppedURL = url { let size = iconImageView.frame.width * UIScreen.mainScreen().scale let scaledURL = unrawppedURL.patchGravatarUrlWithSize(size) iconImageView.downloadImage(scaledURL, placeholderImage: placeholderImage) } else { iconImageView.image = placeholderImage } gravatarURL = url } // MARK: - UITableViewCell Methods public override func awakeFromNib() { super.awakeFromNib() contentView.autoresizingMask = .FlexibleHeight | .FlexibleWidth iconImageView.image = WPStyleGuide.Notifications.gravatarPlaceholderImage noticonContainerView.layer.cornerRadius = noticonContainerView.frame.size.width / 2 noticonView.layer.cornerRadius = Settings.noticonRadius noticonLabel.font = Style.noticonFont noticonLabel.textColor = Style.noticonTextColor subjectLabel.numberOfLines = Settings.subjectNumberOfLinesWithSnippet subjectLabel.shadowOffset = CGSizeZero snippetLabel.numberOfLines = Settings.snippetNumberOfLines // Separators: Setup bottom separators! separatorsView.bottomColor = WPStyleGuide.Notifications.noteSeparatorColor separatorsView.bottomInsets = Settings.separatorInsets backgroundView = separatorsView } public override func layoutSubviews() { refreshLabelPreferredMaxLayoutWidth() refreshBackgrounds() super.layoutSubviews() } public override func setSelected(selected: Bool, animated: Bool) { // Note: this is required, since the cell unhighlight mechanism will reset the new background color super.setSelected(selected, animated: animated) refreshBackgrounds() } public override func setHighlighted(highlighted: Bool, animated: Bool) { // Note: this is required, since the cell unhighlight mechanism will reset the new background color super.setHighlighted(highlighted, animated: animated) refreshBackgrounds() } // MARK: - Private Methods private func refreshLabelPreferredMaxLayoutWidth() { let maxWidthLabel = frame.width - Settings.textInsets.right - subjectLabel.frame.minX subjectLabel.preferredMaxLayoutWidth = maxWidthLabel snippetLabel.preferredMaxLayoutWidth = maxWidthLabel } private func refreshBackgrounds() { // Noticon Background if unapproved { noticonView.backgroundColor = Style.noticonUnmoderatedColor noticonContainerView.backgroundColor = Style.noticonTextColor } else if read { noticonView.backgroundColor = Style.noticonReadColor noticonContainerView.backgroundColor = Style.noticonTextColor } else { noticonView.backgroundColor = Style.noticonUnreadColor noticonContainerView.backgroundColor = Style.noteBackgroundUnreadColor } // Cell Background: Assign only if needed, for performance let newBackgroundColor = read ? Style.noteBackgroundReadColor : Style.noteBackgroundUnreadColor if backgroundColor != newBackgroundColor { backgroundColor = newBackgroundColor } } private func refreshSubviewVisibility() { for subview in contentView.subviews as! [UIView] { subview.hidden = markedForDeletion } } private func refreshNumberOfLines() { // When the snippet is present, let's clip the number of lines in the subject let showsSnippet = attributedSnippet != nil subjectLabel.numberOfLines = Settings.subjectNumberOfLines(showsSnippet) } private func refreshUndoOverlay() { // Remove if markedForDeletion == false { undoOverlayView?.removeFromSuperview() return } // Load if undoOverlayView == nil { let nibName = NoteUndoOverlayView.classNameWithoutNamespaces() NSBundle.mainBundle().loadNibNamed(nibName, owner: self, options: nil) undoOverlayView.setTranslatesAutoresizingMaskIntoConstraints(false) } // Attach if undoOverlayView.superview == nil { contentView.addSubview(undoOverlayView) contentView.pinSubviewToAllEdges(undoOverlayView) } } // MARK: - Public Static Helpers public class func layoutHeightWithWidth(width: CGFloat, subject: NSAttributedString?, snippet: NSAttributedString?) -> CGFloat { // Limit the width (iPad Devices) let cellWidth = min(width, Style.maximumCellWidth) var cellHeight = Settings.textInsets.top + Settings.textInsets.bottom // Calculate the maximum label size let maxLabelWidth = cellWidth - Settings.textInsets.left - Settings.textInsets.right let maxLabelSize = CGSize(width: maxLabelWidth, height: CGFloat.max) // Helpers let showsSnippet = snippet != nil // If we must render a snippet, the maximum subject height will change. Account for that please if let unwrappedSubject = subject { let subjectRect = unwrappedSubject.boundingRectWithSize(maxLabelSize, options: .UsesLineFragmentOrigin, context: nil) cellHeight += min(subjectRect.height, Settings.subjectMaximumHeight(showsSnippet)) } if let unwrappedSubject = snippet { let snippetRect = unwrappedSubject.boundingRectWithSize(maxLabelSize, options: .UsesLineFragmentOrigin, context: nil) cellHeight += min(snippetRect.height, Settings.snippetMaximumHeight()) } return max(cellHeight, Settings.minimumCellHeight) } // MARK: - Action Handlers @IBAction public func undeleteWasPressed(sender: AnyObject) { if let handler = onUndelete { handler() } } // MARK: - Private Alias private typealias Style = WPStyleGuide.Notifications // MARK: - Private Settings private struct Settings { static let minimumCellHeight = CGFloat(70) static let textInsets = UIEdgeInsets(top: 9.0, left: 71.0, bottom: 12.0, right: 12.0) static let separatorInsets = UIEdgeInsets(top: 0.0, left: 12.0, bottom: 0.0, right: 0.0) static let subjectNumberOfLinesWithoutSnippet = 3 static let subjectNumberOfLinesWithSnippet = 2 static let snippetNumberOfLines = 2 static let noticonRadius = CGFloat(10) static func subjectNumberOfLines(showsSnippet: Bool) -> Int { return showsSnippet ? subjectNumberOfLinesWithSnippet : subjectNumberOfLinesWithoutSnippet } static func subjectMaximumHeight(showsSnippet: Bool) -> CGFloat { return CGFloat(Settings.subjectNumberOfLines(showsSnippet)) * Style.subjectLineSize } static func snippetMaximumHeight() -> CGFloat { return CGFloat(snippetNumberOfLines) * Style.snippetLineSize } } // MARK: - Private Properties private var gravatarURL : NSURL? private var separatorsView = SeparatorsView() // MARK: - IBOutlets @IBOutlet private weak var iconImageView: CircularImageView! @IBOutlet private weak var noticonLabel: UILabel! @IBOutlet private weak var noticonContainerView: UIView! @IBOutlet private weak var noticonView: UIView! @IBOutlet private weak var subjectLabel: UILabel! @IBOutlet private weak var snippetLabel: UILabel! @IBOutlet private weak var timestampLabel: UILabel! // MARK: - Undo Overlay Optional @IBOutlet private var undoOverlayView: NoteUndoOverlayView! }
gpl-2.0
c4f677d89e408b476425849fa57be3e8
35.936242
132
0.608522
5.826893
false
false
false
false
gouyz/GYZBaking
baking/Pods/SKPhotoBrowser/SKPhotoBrowser/SKZoomingScrollView.swift
4
10770
// // SKZoomingScrollView.swift // SKViewExample // // Created by suzuki_keihsi on 2015/10/01. // Copyright © 2015 suzuki_keishi. All rights reserved. // import UIKit open class SKZoomingScrollView: UIScrollView { var captionView: SKCaptionView! var photo: SKPhotoProtocol! { didSet { photoImageView.image = nil if photo != nil && photo.underlyingImage != nil { displayImage(complete: true) } if photo != nil { displayImage(complete: false) } } } fileprivate(set) var photoImageView: SKDetectingImageView! fileprivate weak var photoBrowser: SKPhotoBrowser? fileprivate var tapView: SKDetectingView! fileprivate var indicatorView: SKIndicatorView! required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setup() } override init(frame: CGRect) { super.init(frame: frame) setup() } convenience init(frame: CGRect, browser: SKPhotoBrowser) { self.init(frame: frame) photoBrowser = browser setup() } deinit { photoBrowser = nil } func setup() { // tap tapView = SKDetectingView(frame: bounds) tapView.delegate = self tapView.backgroundColor = .clear tapView.autoresizingMask = [.flexibleHeight, .flexibleWidth] addSubview(tapView) // image photoImageView = SKDetectingImageView(frame: frame) photoImageView.delegate = self photoImageView.contentMode = .bottom photoImageView.backgroundColor = .clear addSubview(photoImageView) // indicator indicatorView = SKIndicatorView(frame: frame) addSubview(indicatorView) // self backgroundColor = .clear delegate = self showsHorizontalScrollIndicator = SKPhotoBrowserOptions.displayHorizontalScrollIndicator showsVerticalScrollIndicator = SKPhotoBrowserOptions.displayVerticalScrollIndicator decelerationRate = UIScrollViewDecelerationRateFast autoresizingMask = [.flexibleWidth, .flexibleTopMargin, .flexibleBottomMargin, .flexibleRightMargin, .flexibleLeftMargin] } // MARK: - override open override func layoutSubviews() { tapView.frame = bounds indicatorView.frame = bounds super.layoutSubviews() let boundsSize = bounds.size var frameToCenter = photoImageView.frame // horizon if frameToCenter.size.width < boundsSize.width { frameToCenter.origin.x = floor((boundsSize.width - frameToCenter.size.width) / 2) } else { frameToCenter.origin.x = 0 } // vertical if frameToCenter.size.height < boundsSize.height { frameToCenter.origin.y = floor((boundsSize.height - frameToCenter.size.height) / 2) } else { frameToCenter.origin.y = 0 } // Center if !photoImageView.frame.equalTo(frameToCenter) { photoImageView.frame = frameToCenter } } open func setMaxMinZoomScalesForCurrentBounds() { maximumZoomScale = 1 minimumZoomScale = 1 zoomScale = 1 guard let photoImageView = photoImageView else { return } let boundsSize = bounds.size let imageSize = photoImageView.frame.size let xScale = boundsSize.width / imageSize.width let yScale = boundsSize.height / imageSize.height let minScale: CGFloat = min(xScale, yScale) var maxScale: CGFloat = 1.0 let scale = max(UIScreen.main.scale, 2.0) let deviceScreenWidth = UIScreen.main.bounds.width * scale // width in pixels. scale needs to remove if to use the old algorithm let deviceScreenHeight = UIScreen.main.bounds.height * scale // height in pixels. scale needs to remove if to use the old algorithm if photoImageView.frame.width < deviceScreenWidth { // I think that we should to get coefficient between device screen width and image width and assign it to maxScale. I made two mode that we will get the same result for different device orientations. if UIApplication.shared.statusBarOrientation.isPortrait { maxScale = deviceScreenHeight / photoImageView.frame.width } else { maxScale = deviceScreenWidth / photoImageView.frame.width } } else if photoImageView.frame.width > deviceScreenWidth { maxScale = 1.0 } else { // here if photoImageView.frame.width == deviceScreenWidth maxScale = 2.5 } maximumZoomScale = maxScale minimumZoomScale = minScale zoomScale = minScale // on high resolution screens we have double the pixel density, so we will be seeing every pixel if we limit the // maximum zoom scale to 0.5 // After changing this value, we still never use more /* maxScale = maxScale / scale if maxScale < minScale { maxScale = minScale * 2 } */ // reset position photoImageView.frame = CGRect(x: 0, y: 0, width: photoImageView.frame.size.width, height: photoImageView.frame.size.height) setNeedsLayout() } open func prepareForReuse() { photo = nil if captionView != nil { captionView.removeFromSuperview() captionView = nil } } // MARK: - image open func displayImage(complete flag: Bool) { // reset scale maximumZoomScale = 1 minimumZoomScale = 1 zoomScale = 1 contentSize = CGSize.zero if !flag { if photo.underlyingImage == nil { indicatorView.startAnimating() } photo.loadUnderlyingImageAndNotify() } else { indicatorView.stopAnimating() } if let image = photo.underlyingImage { // image photoImageView.image = image photoImageView.contentMode = photo.contentMode photoImageView.backgroundColor = SKPhotoBrowserOptions.backgroundColor var photoImageViewFrame = CGRect.zero photoImageViewFrame.origin = CGPoint.zero photoImageViewFrame.size = image.size photoImageView.frame = photoImageViewFrame contentSize = photoImageViewFrame.size setMaxMinZoomScalesForCurrentBounds() } setNeedsLayout() } open func displayImageFailure() { indicatorView.stopAnimating() } // MARK: - handle tap open func handleDoubleTap(_ touchPoint: CGPoint) { if let photoBrowser = photoBrowser { NSObject.cancelPreviousPerformRequests(withTarget: photoBrowser) } if zoomScale > minimumZoomScale { // zoom out setZoomScale(minimumZoomScale, animated: true) } else { // zoom in // I think that the result should be the same after double touch or pinch /* var newZoom: CGFloat = zoomScale * 3.13 if newZoom >= maximumZoomScale { newZoom = maximumZoomScale } */ let zoomRect = zoomRectForScrollViewWith(maximumZoomScale, touchPoint: touchPoint) zoom(to: zoomRect, animated: true) } // delay control photoBrowser?.hideControlsAfterDelay() } } // MARK: - UIScrollViewDelegate extension SKZoomingScrollView: UIScrollViewDelegate { public func viewForZooming(in scrollView: UIScrollView) -> UIView? { return photoImageView } public func scrollViewWillBeginZooming(_ scrollView: UIScrollView, with view: UIView?) { photoBrowser?.cancelControlHiding() } public func scrollViewDidZoom(_ scrollView: UIScrollView) { setNeedsLayout() layoutIfNeeded() } } // MARK: - SKDetectingImageViewDelegate extension SKZoomingScrollView: SKDetectingViewDelegate { func handleSingleTap(_ view: UIView, touch: UITouch) { guard let browser = photoBrowser else { return } guard SKPhotoBrowserOptions.enableZoomBlackArea == true else { return } if browser.areControlsHidden() == false && SKPhotoBrowserOptions.enableSingleTapDismiss == true { browser.determineAndClose() } else { browser.toggleControls() } } func handleDoubleTap(_ view: UIView, touch: UITouch) { if SKPhotoBrowserOptions.enableZoomBlackArea == true { let needPoint = getViewFramePercent(view, touch: touch) handleDoubleTap(needPoint) } } } // MARK: - SKDetectingImageViewDelegate extension SKZoomingScrollView: SKDetectingImageViewDelegate { func handleImageViewSingleTap(_ touchPoint: CGPoint) { guard let browser = photoBrowser else { return } if SKPhotoBrowserOptions.enableSingleTapDismiss { browser.determineAndClose() } else { browser.toggleControls() } } func handleImageViewDoubleTap(_ touchPoint: CGPoint) { handleDoubleTap(touchPoint) } } private extension SKZoomingScrollView { func getViewFramePercent(_ view: UIView, touch: UITouch) -> CGPoint { let oneWidthViewPercent = view.bounds.width / 100 let viewTouchPoint = touch.location(in: view) let viewWidthTouch = viewTouchPoint.x let viewPercentTouch = viewWidthTouch / oneWidthViewPercent let photoWidth = photoImageView.bounds.width let onePhotoPercent = photoWidth / 100 let needPoint = viewPercentTouch * onePhotoPercent var Y: CGFloat! if viewTouchPoint.y < view.bounds.height / 2 { Y = 0 } else { Y = photoImageView.bounds.height } let allPoint = CGPoint(x: needPoint, y: Y) return allPoint } func zoomRectForScrollViewWith(_ scale: CGFloat, touchPoint: CGPoint) -> CGRect { let w = frame.size.width / scale let h = frame.size.height / scale let x = touchPoint.x - (h / max(UIScreen.main.scale, 2.0)) let y = touchPoint.y - (w / max(UIScreen.main.scale, 2.0)) return CGRect(x: x, y: y, width: w, height: h) } }
mit
76fda5a6642e16c1766bfb79653dee92
31.732523
211
0.607299
5.626437
false
false
false
false
qiuncheng/study-for-swift
learn-rx-swift/Chocotastic-starter/Pods/RxCocoa/RxCocoa/iOS/UITextView+Rx.swift
4
3444
// // UITextView+Rx.swift // RxCocoa // // Created by Yuta ToKoRo on 7/19/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // #if os(iOS) || os(tvOS) import Foundation import UIKit #if !RX_NO_MODULE import RxSwift #endif extension UITextView { /** Factory method that enables subclasses to implement their own `delegate`. - returns: Instance of delegate proxy that wraps `delegate`. */ public override func createRxDelegateProxy() -> RxScrollViewDelegateProxy { return RxTextViewDelegateProxy(parentObject: self) } } extension Reactive where Base: UITextView { /** Reactive wrapper for `text` property. */ public var text: ControlProperty<String> { let source: Observable<String> = Observable.deferred { [weak textView = self.base] in let text = textView?.text ?? "" let textChanged = textView?.textStorage // This project uses text storage notifications because // that's the only way to catch autocorrect changes // in all cases. Other suggestions are welcome. .rx.didProcessEditingRangeChangeInLength // This observe on is here because text storage // will emit event while process is not completely done, // so rebinding a value will cause an exception to be thrown. .observeOn(MainScheduler.asyncInstance) .map { _ in return textView?.textStorage.string ?? "" } ?? Observable.empty() return textChanged .startWith(text) } let bindingObserver = UIBindingObserver(UIElement: self.base) { (textView, text: String) in // This check is important because setting text value always clears control state // including marked text selection which is imporant for proper input // when IME input method is used. if textView.text != text { textView.text = text } } return ControlProperty(values: source, valueSink: bindingObserver) } /** Reactive wrapper for `delegate` message. */ public var didBeginEditing: ControlEvent<()> { return ControlEvent<()>(events: self.delegate.observe(#selector(UITextViewDelegate.textViewDidBeginEditing(_:))) .map { a in return () }) } /** Reactive wrapper for `delegate` message. */ public var didEndEditing: ControlEvent<()> { return ControlEvent<()>(events: self.delegate.observe(#selector(UITextViewDelegate.textViewDidEndEditing(_:))) .map { a in return () }) } /** Reactive wrapper for `delegate` message. */ public var didChange: ControlEvent<()> { return ControlEvent<()>(events: self.delegate.observe(#selector(UITextViewDelegate.textViewDidChange(_:))) .map { a in return () }) } /** Reactive wrapper for `delegate` message. */ public var didChangeSelection: ControlEvent<()> { return ControlEvent<()>(events: self.delegate.observe(#selector(UITextViewDelegate.textViewDidChangeSelection(_:))) .map { a in return () }) } } #endif
mit
c9a9a9b1439b6f9cd8d63df002727cdf
30.018018
123
0.586407
5.379688
false
false
false
false
powerytg/Accented
Accented/UI/User/Sections/UserGallerySection.swift
1
4793
// // UserGallerySection.swift // Accented // // Created by Tiangong You on 8/23/17. // Copyright © 2017 Tiangong You. All rights reserved. // import UIKit class UserGallerySection: UserSectionViewBase { override var title: String? { let userName = TextUtils.preferredAuthorName(user).uppercased() return userName + "'S GALLERIES" } private var thumbnailSize : CGFloat! private let hGap : CGFloat = 12 private let vGap : CGFloat = 20 // Maximum number of comments pre-created private let maxRenderesOnScreen = 3 // Gallery renderers private var renderers = [GalleryRenderer]() // Load more button private let loadMoreButton = PushButton(frame: CGRect.zero) // User gallery collection data mdoel private var galleryCollection : GalleryCollectionModel! override func initialize() { super.initialize() // Calculate a proper size for the thumbnails let maxWidth = UIScreen.main.bounds.width - contentLeftPadding - contentRightPadding let rendererCount = CGFloat(maxRenderesOnScreen) thumbnailSize = (maxWidth - (hGap * rendererCount - 1)) / rendererCount // Create a limited number of comment renderers ahead of time for _ in 1...maxRenderesOnScreen { let renderer = GalleryRenderer(frame : CGRect(x: 0, y: 0, width: thumbnailSize, height: thumbnailSize)) contentView.addSubview(renderer) renderers.append(renderer) renderer.isHidden = true } // Create a load-more button loadMoreButton.contentEdgeInsets = UIEdgeInsets(top: 4, left: 8, bottom: 4, right: 8) loadMoreButton.setTitle("See More Galleries", for: .normal) loadMoreButton.sizeToFit() loadMoreButton.isHidden = true contentView.addSubview(loadMoreButton) // Events loadMoreButton.addTarget(self, action: #selector(loadMoreButtonDidTap(_:)), for: .touchUpInside) NotificationCenter.default.addObserver(self, selector: #selector(userGalleryListDidUpdate(_:)), name: StorageServiceEvents.userGalleryListDidUpdate, object: nil) // Load the galery list from user APIService.sharedInstance.getGalleries(userId: user.userId) } deinit { NotificationCenter.default.removeObserver(self) } @objc private func loadMoreButtonDidTap(_ sender : NSObject) { NavigationService.sharedInstance.navigateToUserGalleryListPage(user: user) } override func layoutSubviews() { super.layoutSubviews() guard galleryCollection != nil else { return } if galleryCollection.totalCount == 0 || galleryCollection.items.count == 0 { // Photo has no galleries or still being loaded loadMoreButton.isHidden = true } else { // Showing the first few gallery thumbnails loadMoreButton.isHidden = false var nextX : CGFloat = contentLeftPadding for (index, renderer) in renderers.enumerated() { if index < galleryCollection.items.count { let gallery = galleryCollection.items[index] renderer.frame = CGRect(x: nextX, y: contentTopPadding, width: thumbnailSize, height: thumbnailSize) renderer.gallery = gallery renderer.isHidden = false } else { renderer.isHidden = true } nextX += thumbnailSize + hGap } var f = loadMoreButton.frame f.origin.x = contentLeftPadding f.origin.y = contentTopPadding + thumbnailSize + vGap loadMoreButton.frame = f } } override func calculateContentHeight(maxWidth: CGFloat) -> CGFloat { // Get a copy of the comments self.galleryCollection = StorageService.sharedInstance.getUserGalleries(userId: user.userId) if galleryCollection.totalCount == 0 || galleryCollection.items.count == 0 { return 0 } else { return sectionTitleHeight + thumbnailSize + vGap + 40 } } // MARK: - Events @objc private func userGalleryListDidUpdate(_ notification : Notification) { let userId = notification.userInfo![StorageServiceEvents.userId] as! String guard user.userId == userId else { return } // Get a copy of the updated comments self.galleryCollection = StorageService.sharedInstance.getUserGalleries(userId: userId) // Trigger an animated layout validation invalidateSize() } }
mit
fc9e7b3838c7fa0f0c7420d7d4e52849
36.147287
169
0.626252
5.318535
false
false
false
false
chinlam91/edx-app-ios
Source/AuthenticatedWebViewController.swift
2
12418
// // AuthenticatedWebViewController.swift // edX // // Created by Akiva Leffert on 5/26/15. // Copyright (c) 2015 edX. All rights reserved. // import UIKit import WebKit class HeaderViewInsets : ContentInsetsSource { weak var insetsDelegate : ContentInsetsSourceDelegate? var view : UIView? var currentInsets : UIEdgeInsets { return UIEdgeInsets(top : view?.frame.size.height ?? 0, left : 0, bottom : 0, right : 0) } var affectsScrollIndicators : Bool { return false } } private protocol WebContentController { var view : UIView {get} var scrollView : UIScrollView {get} var alwaysRequiresOAuthUpdate : Bool { get} var initialContentState : AuthenticatedWebViewController.State { get } func loadURLRequest(request : NSURLRequest) func clearDelegate() func resetState() } private class UIWebViewContentController : WebContentController { private let webView = UIWebView(frame: CGRectZero) var view : UIView { return webView } var scrollView : UIScrollView { return webView.scrollView } func clearDelegate() { return webView.delegate = nil } func loadURLRequest(request: NSURLRequest) { webView.loadRequest(request) } func resetState() { webView.stopLoading() webView.loadHTMLString("", baseURL: nil) } var alwaysRequiresOAuthUpdate : Bool { return true } var initialContentState : AuthenticatedWebViewController.State { return AuthenticatedWebViewController.State.CreatingSession } } @available(iOS 8.0, *) private class WKWebViewContentController : WebContentController { private let webView = WKWebView(frame: CGRectZero) var view : UIView { return webView } var scrollView : UIScrollView { return webView.scrollView } func clearDelegate() { return webView.navigationDelegate = nil } func loadURLRequest(request: NSURLRequest) { webView.loadRequest(request) } func resetState() { webView.stopLoading() webView.loadHTMLString("", baseURL: nil) } var alwaysRequiresOAuthUpdate : Bool { return false } var initialContentState : AuthenticatedWebViewController.State { return AuthenticatedWebViewController.State.LoadingContent } } // Allows access to course content that requires authentication. // Forwarding our oauth token to the server so we can get a web based cookie public class AuthenticatedWebViewController: UIViewController, UIWebViewDelegate, UIScrollViewDelegate, WKNavigationDelegate { private enum State { case CreatingSession case LoadingContent case NeedingSession } public struct Environment { public let config : OEXConfig? public let session : OEXSession? public let styles : OEXStyles? public init(config : OEXConfig?, session : OEXSession?, styles : OEXStyles?) { self.config = config self.session = session self.styles = styles } } private let environment : Environment private let loadController : LoadStateViewController private let insetsController : ContentInsetsController private let headerInsets : HeaderViewInsets // After we drop support for iOS7, we can just always use WKWebView private lazy var webController : WebContentController = { // Temporarily disable the WKWebView version while we figure out why we're not sending a // a meta name="viewport" tag. See https://openedx.atlassian.net/browse/MA-960 // if NSClassFromString("WKWebView") != nil { // let controller = WKWebViewContentController() // controller.webView.navigationDelegate = self // return controller // } // else { let controller = UIWebViewContentController() controller.webView.delegate = self return controller // } }() private var state = State.CreatingSession private var contentRequest : NSURLRequest? = nil public init(environment : Environment) { self.environment = environment loadController = LoadStateViewController(styles: self.environment.styles) insetsController = ContentInsetsController() headerInsets = HeaderViewInsets() insetsController.addSource(headerInsets) super.init(nibName: nil, bundle: nil) automaticallyAdjustsScrollViewInsets = false } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } deinit { // Prevent crash due to stale back pointer, since WKWebView's UIScrollView apparently doesn't // use weak for its delegate webController.scrollView.delegate = nil webController.clearDelegate() } override public func viewDidLoad() { self.state = webController.initialContentState self.view.addSubview(webController.view) webController.view.snp_makeConstraints {make in make.edges.equalTo(self.view) } self.loadController.setupInController(self, contentView: webController.view) webController.view.backgroundColor = self.environment.styles?.standardBackgroundColor() webController.scrollView.backgroundColor = self.environment.styles?.standardBackgroundColor() webController.scrollView.delegate = self self.insetsController.setupInController(self, scrollView: webController.scrollView) if let request = self.contentRequest { loadRequest(request) } } private func resetState() { loadController.state = .Initial state = .CreatingSession } public override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() if view.window == nil { webController.resetState() } resetState() } public override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() insetsController.updateInsets() } public func showError(error : NSError?, icon : Icon? = nil, message : String? = nil) { loadController.state = LoadState.failed(error, icon : icon, message : message) } // MARK: Header View public func scrollViewDidScroll(scrollView: UIScrollView) { // Ideally we'd just add the header view directly to the webview's .scrollview, // and then we would get scrolling with the content for free // but that totally screwed up leading/trailing constraints for a label // inside a UIWebView, so we go this route instead headerInsets.view?.transform = CGAffineTransformMakeTranslation(0, -(scrollView.contentInset.top + scrollView.contentOffset.y)) } var headerView : UIView? { get { return headerInsets.view } set { headerInsets.view?.removeFromSuperview() headerInsets.view = newValue if let headerView = newValue { webController.view.addSubview(headerView) headerView.snp_makeConstraints {make in if #available(iOS 9.0, *) { make.top.equalTo(self.topLayoutGuide.bottomAnchor) } else { make.top.equalTo(self.snp_topLayoutGuideBottom) } make.leading.equalTo(webController.view) make.trailing.equalTo(webController.view) } webController.view.setNeedsLayout() webController.view.layoutIfNeeded() } } } var apiHostURL : String { return environment.config?.apiHostURL() ?? "" } private func loadOAuthRefreshRequest() { if let URL = NSURL(string:apiHostURL + "/oauth2/login/") { let exchangeRequest = NSMutableURLRequest(URL: URL) exchangeRequest.HTTPMethod = HTTPMethod.POST.rawValue for (key, value) in self.environment.session?.authorizationHeaders ?? [:] { exchangeRequest.addValue(value, forHTTPHeaderField: key) } self.webController.loadURLRequest(exchangeRequest) } } // MARK: Request Loading public func loadRequest(request : NSURLRequest) { contentRequest = request loadController.state = .Initial state = webController.initialContentState if webController.alwaysRequiresOAuthUpdate { loadOAuthRefreshRequest() } else { webController.loadURLRequest(request) } } // MARK: WKWebView delegate @available(iOS 8.0, *) public func webView(webView: WKWebView, decidePolicyForNavigationAction navigationAction: WKNavigationAction, decisionHandler: (WKNavigationActionPolicy) -> Void) { switch navigationAction.navigationType { case .LinkActivated, .FormSubmitted, .FormResubmitted: if let URL = navigationAction.request.URL { UIApplication.sharedApplication().openURL(URL) } decisionHandler(.Cancel) default: decisionHandler(.Allow) } } @available(iOS 8.0, *) public func webView(webView: WKWebView, decidePolicyForNavigationResponse navigationResponse: WKNavigationResponse, decisionHandler: (WKNavigationResponsePolicy) -> Void) { let continueAction : () -> Void = { self.state = .LoadingContent decisionHandler(.Allow) } if let httpResponse = navigationResponse.response as? NSHTTPURLResponse, statusCode = OEXHTTPStatusCode(rawValue: httpResponse.statusCode) where state == .LoadingContent { if statusCode.is4xx { decisionHandler(.Cancel) loadOAuthRefreshRequest() state = .NeedingSession } else { continueAction() } } else { continueAction() } } @available(iOS 8.0, *) public func webView(webView: WKWebView, didFinishNavigation navigation: WKNavigation!) { switch state { case .CreatingSession: if let request = contentRequest { state = .LoadingContent webController.loadURLRequest(request) } else { loadController.state = LoadState.failed() } case .LoadingContent: loadController.state = .Loaded case .NeedingSession: state = .CreatingSession loadOAuthRefreshRequest() } } @available(iOS 8.0, *) public func webView(webView: WKWebView, didFailNavigation navigation: WKNavigation!, withError error: NSError) { showError(error) } // MARK: UIWebView delegate public func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool { if navigationType == .LinkClicked || navigationType == .FormSubmitted { if let URL = request.URL { UIApplication.sharedApplication().openURL(URL) } return false } return true } public func webViewDidFinishLoad(webView: UIWebView) { switch state { case .CreatingSession: if let request = contentRequest { state = .LoadingContent webController.loadURLRequest(request) } else { loadController.state = LoadState.failed() } case .LoadingContent: loadController.state = .Loaded case .NeedingSession: loadOAuthRefreshRequest() state = .CreatingSession } } public func webView(webView: UIWebView, didFailLoadWithError error: NSError?) { showError(error) } }
apache-2.0
743b1dc0819a4c150f8798f5d134a496
30.678571
176
0.617571
5.733149
false
false
false
false
alexruperez/ARFacebookShareKitActivity
ARFacebookShareKitActivity/Classes/ShareLinkActivity/ShareLinkActivity.swift
1
2390
// // ShareLinkActivity.swift // ARFacebookShareKitActivity // // Created by alexruperez on 2/6/16. // Copyright © 2016 CocoaPods. All rights reserved. // import FBSDKShareKit @objc open class ShareLinkActivity: UIActivity { @objc open var title: String? @objc open var image: UIImage? @objc open var mode: FBSDKShareDialogMode = .automatic open static var category: UIActivityCategory? fileprivate lazy var shareDialog: FBSDKShareDialog = { let shareDialog = FBSDKShareDialog() shareDialog.delegate = self shareDialog.shareContent = FBSDKShareLinkContent() shareDialog.mode = self.mode return shareDialog }() open override class var activityCategory : UIActivityCategory { return category ?? .share } open class func setActivityCategory(_ category: UIActivityCategory) { self.category = category } @objc public convenience init(title: String?, image: UIImage?, mode: FBSDKShareDialogMode) { self.init() self.title = title self.image = image self.mode = mode } open override var activityType : UIActivityType? { return UIActivityType(String(describing: ShareLinkActivity.self)) } open override var activityTitle : String? { return title ?? NSLocalizedString("Facebook Share", comment: "\(activityType!) Title") } open override var activityImage : UIImage? { return image ?? UIImage(named: "\(activityType!.rawValue)\(ShareLinkActivity.activityCategory.rawValue)", in: Bundle(for: ShareLinkActivity.self), compatibleWith: nil) } open override func canPerform(withActivityItems activityItems: [Any]) -> Bool { for item in activityItems { if let contentURL = item as? URL { shareDialog.shareContent.contentURL = contentURL } if let quote = item as? String { if let shareContent = shareDialog.shareContent as? FBSDKShareLinkContent { shareContent.quote = quote } } } do { try shareDialog.validate() return shareDialog.canShow() } catch { return false } } open override func perform() { shareDialog.show() } }
mit
fde144b8c12674ddcf6fe00efc2694eb
29.240506
175
0.619087
5.093817
false
false
false
false
edragoev1/pdfjet
Sources/PDFjet/Destination.swift
1
1678
/** * Destination.swift * Copyright 2020 Innovatics Inc. 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. */ /// /// Used to create PDF destination objects. /// public class Destination { var name: String? var pageObjNumber = 0 var yPosition: Float = 0.0 /// /// This class is used to create destination objects. /// /// @param name the name of this destination object. /// @param yPosition the y coordinate of the top left corner. /// public init(_ name: String, _ yPosition: Float) { self.name = name self.yPosition = yPosition } func setPageObjNumber(_ pageObjNumber: Int) { self.pageObjNumber = pageObjNumber } }
mit
14fd695b22990784065cbe81f7aa6bca
31.901961
78
0.734207
4.522911
false
false
false
false
RyoAbe/PARTNER
PARTNER/PARTNER/Core/Model/Status/StatusType.swift
1
2657
// // StatusType.swift // PARTNER // // Created by RyoAbe on 2015/01/24. // Copyright (c) 2015年 RyoAbe. All rights reserved. // import UIKit func countEnumElements(test: (Int) -> Any?) -> Int { var i = 0 while test(i) != nil { i++ } return i } enum StatusTypes : NSInteger { case GoodMorning = 0 case GoingHome case ThunkYou case EatOut case AlmostThere case GodId case GoodNight case Sorry case Love var statusType : StatusType { switch self { case GoodMorning: return StatusType(iconImageName: "good_morning_icon", name: LocalizedString.key("GoodMorning")) case GoingHome: return StatusType(iconImageName: "going_home_icon", name: LocalizedString.key("GoingHome")) case ThunkYou: return StatusType(iconImageName: "thank_you_icon", name: LocalizedString.key("ThunkYou")) case EatOut: return StatusType(iconImageName: "have_dinner_icon", name: LocalizedString.key("EatOut")) case AlmostThere: return StatusType(iconImageName: "there_icon", name: LocalizedString.key("AlmostThere")) case GodId: return StatusType(iconImageName: "god_it_icon", name: LocalizedString.key("GodId")) case GoodNight: return StatusType(iconImageName: "good_night_icon", name: LocalizedString.key("GoodNight")) case Sorry: return StatusType(iconImageName: "bow_icon", name: LocalizedString.key("Sorry")) case Love: return StatusType(iconImageName: "love_icon", name: LocalizedString.key("Love")) } } // Max4つ。あとの一つはOther static let notificationActions = [GodId, GoingHome, AlmostThere] static let count = countEnumElements({StatusTypes(rawValue: $0)}) } class StatusType: NSObject, NSCoding { var identifier : String! var iconImageName : String! var name : String! init(iconImageName: String, name: String) { self.identifier = iconImageName self.iconImageName = iconImageName self.name = name } required init(coder aDecoder: NSCoder) { identifier = aDecoder.decodeObjectForKey("iconImageName") as! String iconImageName = aDecoder.decodeObjectForKey("iconImageName") as! String name = aDecoder.decodeObjectForKey("name") as! String super.init() } func encodeWithCoder(aCoder: NSCoder) { aCoder.encodeObject(identifier, forKey: "iconImageName") aCoder.encodeObject(iconImageName, forKey: "iconImageName") aCoder.encodeObject(name, forKey: "name") } }
gpl-3.0
cbbe95a3f204a2814dc8b390c7158492
30.795181
107
0.650625
4.305057
false
false
false
false
leeaken/LTMap
LTMap/LTLocationMap/LocationManager/Privates/LTGoogleGeocode.swift
1
5265
// // LTGoogleGeocode.swift // LTMap // // 使用google webservice地理编译 // Created by aken on 2017/6/14. // Copyright © 2017年 LTMap. All rights reserved. // import Foundation class LTGoogleGeocode: NSObject,LTGeocodeProtocol { let type: LTGeocodeType = .LTAbroad fileprivate var dataCompletion:SearchCompletion? fileprivate var pagetoken:String? override init() { } func searchReGeocodeWithCoordinate(coordinate: CLLocationCoordinate2D,completion:@escaping(SearchCompletion)) { } func searchNearbyWithCoordinate(param:LTPOISearchAroundArg,completion:@escaping(SearchCompletion)) { dataCompletion = completion var keywork:String = "" if (param.keyword == nil) { keywork = "" }else { keywork = param.keyword! } var location:String = "" if let lat = param.location?.latitude , let log = param.location?.longitude { location = "\(String(describing: lat)),\(String(describing: log))" } var parameter: [String: Any] if pagetoken==nil { parameter = ["input":keywork, "location":location] }else { parameter = ["input":keywork, "location":location, "pagetoken":pagetoken!] } let request = MXGooglNearbysearchRequest(requestParameter: parameter) LTGoogleManager().request(request) { [weak self] (model) in if let model = model { var poiArray = [LTPoiModel]() if (model.models != nil && (model.models?.count)! > 0) { for infos in model.models! { let poi = LTPoiModel() poi.uid = infos.uid poi.title = infos.title poi.subtitle = infos.subtitle poi.coordinate = infos.coordinate self?.pagetoken = infos.pagetoken poiArray.append(poi) } } if let closure = self?.dataCompletion { if self?.pagetoken == nil { closure(poiArray,false) }else { closure(poiArray,true) } } } } } func searchInputTipsAutoCompletionWithKeyword(param:LTPOISearchAroundArg,completion:@escaping(SearchCompletion)) { searchPlaceWithKeyWord(param: param, completion: completion) } func searchPlaceWithKeyWord(param:LTPOISearchAroundArg,completion:@escaping(SearchCompletion)) { searchNearbyWithCoordinate(param: param, completion: completion) } // 此函数搜索返回的数据量少 private func autoCompleteWithKeyWord(param:LTPOISearchAroundArg,completion:@escaping(SearchCompletion)) { dataCompletion = completion let keywork:String = param.keyword! var location:String = "" if let lat = param.location?.latitude , let log = param.location?.longitude { location = "\(String(describing: lat)),\(String(describing: log))" } var parameter: [String: Any] if pagetoken==nil { parameter = ["input":keywork, "location":location] }else { parameter = ["input":keywork, "location":location, "pagetoken":pagetoken!] } let request = MXGooglAutoCompleteRequest(requestParameter: parameter) LTGoogleManager().request(request) { [weak self] (model) in if let model = model { var poiArray = [LTPoiModel]() for infos in model.models! { let poi = LTPoiModel() poi.uid = infos.uid poi.title = infos.title poi.subtitle = infos.subtitle self?.pagetoken = infos.pagetoken poiArray.append(poi) } if let closure = self?.dataCompletion { if self?.pagetoken == nil { closure(poiArray,false) }else { closure(poiArray,true) } } } } } }
mit
0ea4c1cc0b03d2236f584e4a7eb390be
27.096774
118
0.441638
5.945392
false
false
false
false
tlax/GaussSquad
GaussSquad/Model/Calculator/Base/MCalculatorFunctionsItem.swift
1
2455
import UIKit class MCalculatorFunctionsItem { let icon:UIImage let title:String init(icon:UIImage, title:String) { self.icon = icon self.title = title } //MARK: public func selected(controller:CCalculator) { DispatchQueue.global(qos:DispatchQoS.QoSClass.background).async { [weak self, weak controller] in guard let textView:UITextView = controller?.viewCalculator.viewText, let keyboard:VKeyboard = textView.inputView as? VKeyboard else { return } let model:MKeyboard = keyboard.model guard let lastState:MKeyboardState = model.states.last else { return } if lastState.needsUpdate { model.states.removeLast() } let currentValue:Double = model.lastNumber() let currentString:String = model.lastString() self?.processFunction( currentValue:currentValue, currentString:currentString, modelKeyboard:model, view:textView) } } func applyUpdate( modelKeyboard:MKeyboard, view:UITextView, newEditing:String, descr:String) { guard let lastState:MKeyboardState = modelKeyboard.states.last else { return } let emptyString:String = modelKeyboard.kEmpty DispatchQueue.main.async { [weak view] in guard let view:UITextView = view else { return } view.text = emptyString view.insertText(newEditing) lastState.editing = newEditing NotificationCenter.default.post( name:Notification.functionUpdate, object:descr) } } func processFunction( currentValue:Double, currentString:String, modelKeyboard:MKeyboard, view:UITextView) { } }
mit
e2f619f3476353afff7083716468dded
22.605769
78
0.464358
6.106965
false
false
false
false
kylef/JSONWebToken.swift
Sources/JWT/ClaimSet.swift
1
4649
import Foundation func parseTimeInterval(_ value: Any?) -> Date? { guard let value = value else { return nil } if let string = value as? String, let interval = TimeInterval(string) { return Date(timeIntervalSince1970: interval) } if let interval = value as? Int { let double = Double(interval) return Date(timeIntervalSince1970: double) } if let interval = value as? TimeInterval { return Date(timeIntervalSince1970: interval) } return nil } public struct ClaimSet { var claims: [String: Any] public init(claims: [String: Any]? = nil) { self.claims = claims ?? [:] } public subscript(key: String) -> Any? { get { return claims[key] } set { if let newValue = newValue, let date = newValue as? Date { claims[key] = date.timeIntervalSince1970 } else { claims[key] = newValue } } } } // MARK: Accessors extension ClaimSet { public var issuer: String? { get { return claims["iss"] as? String } set { claims["iss"] = newValue } } public var audience: String? { get { return claims["aud"] as? String } set { claims["aud"] = newValue } } public var expiration: Date? { get { return parseTimeInterval(claims["exp"]) } set { self["exp"] = newValue } } public var notBefore: Date? { get { return parseTimeInterval(claims["nbf"]) } set { self["nbf"] = newValue } } public var issuedAt: Date? { get { return parseTimeInterval(claims["iat"]) } set { self["iat"] = newValue } } } // MARK: Validations extension ClaimSet { public func validate(audience: String? = nil, issuer: String? = nil, leeway: TimeInterval = 0) throws { if let issuer = issuer { try validateIssuer(issuer) } if let audience = audience { try validateAudience(audience) } try validateExpiry(leeway: leeway) try validateNotBefore(leeway: leeway) try validateIssuedAt(leeway: leeway) } public func validateAudience(_ audience: String) throws { if let aud = self["aud"] as? [String] { if !aud.contains(audience) { throw InvalidToken.invalidAudience } } else if let aud = self["aud"] as? String { if aud != audience { throw InvalidToken.invalidAudience } } else { throw InvalidToken.decodeError("Invalid audience claim, must be a string or an array of strings") } } public func validateIssuer(_ issuer: String) throws { if let iss = self["iss"] as? String { if iss != issuer { throw InvalidToken.invalidIssuer } } else { throw InvalidToken.invalidIssuer } } @available(*, deprecated, message: "This method's name is misspelled. Please instead use validateExpiry(leeway:).") public func validateExpiary(leeway: TimeInterval = 0) throws { try validateExpiry(leeway: leeway) } public func validateExpiry(leeway: TimeInterval = 0) throws { try validateDate(claims, key: "exp", comparison: .orderedAscending, leeway: (-1 * leeway), failure: .expiredSignature, decodeError: "Expiration time claim (exp) must be an integer") } public func validateNotBefore(leeway: TimeInterval = 0) throws { try validateDate(claims, key: "nbf", comparison: .orderedDescending, leeway: leeway, failure: .immatureSignature, decodeError: "Not before claim (nbf) must be an integer") } public func validateIssuedAt(leeway: TimeInterval = 0) throws { try validateDate(claims, key: "iat", comparison: .orderedDescending, leeway: leeway, failure: .invalidIssuedAt, decodeError: "Issued at claim (iat) must be an integer") } } // MARK: Builder public class ClaimSetBuilder { var claims = ClaimSet() public var issuer: String? { get { return claims.issuer } set { claims.issuer = newValue } } public var audience: String? { get { return claims.audience } set { claims.audience = newValue } } public var expiration: Date? { get { return claims.expiration } set { claims.expiration = newValue } } public var notBefore: Date? { get { return claims.notBefore } set { claims.notBefore = newValue } } public var issuedAt: Date? { get { return claims.issuedAt } set { claims.issuedAt = newValue } } public subscript(key: String) -> Any? { get { return claims[key] } set { claims[key] = newValue } } } typealias PayloadBuilder = ClaimSetBuilder
bsd-2-clause
a4abb9d57ba028a17fd67ab324acb0a3
19.662222
185
0.620779
4.025108
false
false
false
false
wikimedia/wikipedia-ios
Wikipedia/Code/PageHistoryFilterCountsViewController.swift
1
6997
import UIKit protocol PageHistoryFilterCountsViewControllerDelegate: AnyObject { func didDetermineFilterCountsAvailability(_ available: Bool, viewController: PageHistoryFilterCountsViewController) } class PageHistoryFilterCountsViewController: UIViewController { private let activityIndicator = UIActivityIndicatorView(style: .large) private let collectionView = UICollectionView(frame: .zero, collectionViewLayout: UICollectionViewFlowLayout()) weak var delegate: PageHistoryFilterCountsViewControllerDelegate? var theme = Theme.standard private var counts: [Count] = [] var editCountsGroupedByType: EditCountsGroupedByType? { didSet { counts = [] defer { collectionView.reloadData() activityIndicator.stopAnimating() } guard let editCounts = editCountsGroupedByType else { delegate?.didDetermineFilterCountsAvailability(false, viewController: self) return } if let userEdits = editCounts[.userEdits]?.count { counts.append(Count(title: WMFLocalizedString("page-history-user-edits", value: "user edits", comment: "Text for view that shows many edits were made by logged-in users"), image: UIImage(named: "user-edit"), count: userEdits)) } if let anonEdits = editCounts[.anonymous]?.count { counts.append(Count(title: WMFLocalizedString("page-history-anonymous-edits", value: "anon edits", comment: "Text for view that shows many edits were made by anonymous users"), image: UIImage(named: "anon"), count: anonEdits)) } if let botEdits = editCounts[.bot]?.count { counts.append(Count(title: WMFLocalizedString("page-history-bot-edits", value: "bot edits", comment: "Text for view that shows many edits were made by bots"), image: UIImage(named: "bot"), count: botEdits)) } if let minorEdits = editCounts[.minor]?.count { counts.append(Count(title: WMFLocalizedString("page-history-minor-edits", value: "minor edits", comment: "Text for view that shows many edits were marked as minor edits"), image: UIImage(named: "m"), count: minorEdits)) } countOfColumns = CGFloat(counts.count) delegate?.didDetermineFilterCountsAvailability(!counts.isEmpty, viewController: self) } } private struct Count { let title: String let image: UIImage? let count: Int } private func displayCount(_ count: Int) -> String { return NumberFormatter.localizedThousandsStringFromNumber(NSNumber(value: count)) } private lazy var collectionViewHeightConstraint = collectionView.heightAnchor.constraint(equalToConstant: 60) override func viewDidLoad() { super.viewDidLoad() collectionView.dataSource = self collectionView.register(UINib(nibName: "PageHistoryFilterCountCollectionViewCell", bundle: nil), forCellWithReuseIdentifier: PageHistoryFilterCountCollectionViewCell.identifier) collectionViewHeightConstraint.isActive = true view.wmf_addSubviewWithConstraintsToEdges(collectionView) addActivityIndicator() activityIndicator.color = theme.isDark ? .white : .gray activityIndicator.startAnimating() flowLayout.scrollDirection = .horizontal flowLayout.minimumInteritemSpacing = 0 flowLayout.sectionInset = .zero flowLayout.minimumLineSpacing = 0 apply(theme: theme) } private func addActivityIndicator() { activityIndicator.translatesAutoresizingMaskIntoConstraints = false view.insertSubview(activityIndicator, aboveSubview: collectionView) NSLayoutConstraint.activate([ activityIndicator.centerYAnchor.constraint(equalTo: view.centerYAnchor), activityIndicator.centerXAnchor.constraint(equalTo: view.centerXAnchor) ]) } override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) { super.viewWillTransition(to: size, with: coordinator) coordinator.animate(alongsideTransition: { _ in self.collectionView.collectionViewLayout.invalidateLayout() self.calculateSizes() }) } private var countOfColumns: CGFloat = 4 { didSet { calculateSizes() } } private var columnWidth: CGFloat { let availableWidth = collectionView.bounds.width - flowLayout.minimumInteritemSpacing * (countOfColumns - 1) - collectionView.contentInset.left - collectionView.contentInset.right - flowLayout.sectionInset.left - flowLayout.sectionInset.right return floor(availableWidth / countOfColumns) } private var flowLayout: UICollectionViewFlowLayout { return collectionView.collectionViewLayout as! UICollectionViewFlowLayout } private lazy var placeholderCell = PageHistoryFilterCountCollectionViewCell.wmf_viewFromClassNib()! private func calculateSizes() { var height = collectionViewHeightConstraint.constant for (index, count) in counts.enumerated() { let size = placeholderCell.sizeWith(width: columnWidth, title: count.title, image: count.image, imageText: displayCount(count.count), isRightSeparatorHidden: index == counts.count - 1) height = max(height, size.height) } collectionViewHeightConstraint.constant = height flowLayout.itemSize = CGSize(width: columnWidth, height: height) } } extension PageHistoryFilterCountsViewController: UICollectionViewDataSource { func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return counts.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: PageHistoryFilterCountCollectionViewCell.identifier, for: indexPath) as? PageHistoryFilterCountCollectionViewCell else { return UICollectionViewCell() } configure(cell, at: indexPath) return cell } private func configure(_ cell: PageHistoryFilterCountCollectionViewCell, at indexPath: IndexPath) { let count = counts[indexPath.item] cell.configure(with: count.title, image: count.image, imageText: displayCount(count.count), isRightSeparatorHidden: indexPath.item == counts.count - 1) cell.apply(theme: theme) } } extension PageHistoryFilterCountsViewController: Themeable { func apply(theme: Theme) { self.theme = theme guard viewIfLoaded != nil else { return } view.backgroundColor = theme.colors.paperBackground collectionView.backgroundColor = view.backgroundColor activityIndicator.color = theme.isDark ? .white : .gray } }
mit
699ba553a9d8ceb147c2228e92443c56
45.337748
250
0.703587
5.505114
false
false
false
false
corosukeK/ConstraintsTranslator
Sources/main.swift
1
803
import Foundation import Commandant public var filePath: String? = nil var arguments = CommandLine.arguments assert(!arguments.isEmpty) arguments.removeFirst() if let verb = arguments.first, verb == GenerateCommand().verb { arguments.removeFirst() if let filepath = arguments.first { filePath = filepath } } let registry = CommandRegistry<ConstraintsTranslatorError>() registry.register(GenerateCommand()) registry.register(VersionCommand()) let helpCommand = HelpCommand(registry: registry) registry.register(helpCommand) registry.main(defaultVerb: helpCommand.verb) { (error) in switch error { case .fileNotFound: print("FileNotFound") case .fileIsNotReadable: print("fileIsNotReadable") case .parseError: print("parseError") } }
apache-2.0
0748034e7efe9d35263d0538830eee4e
22.617647
63
0.726027
4.436464
false
false
false
false
Maxim-38RUS-Zabelin/ios-charts
Charts/Classes/Data/ChartDataSet.swift
1
10540
// // ChartDataSet.swift // Charts // // Created by Daniel Cohen Gindi on 23/2/15. // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/ios-charts // import Foundation import UIKit public class ChartDataSet: NSObject { public var colors = [UIColor]() internal var _yVals: [ChartDataEntry]! internal var _yMax = Double(0.0) internal var _yMin = Double(0.0) internal var _yValueSum = Double(0.0) /// the last start value used for calcMinMax internal var _lastStart: Int = 0 /// the last end value used for calcMinMax internal var _lastEnd: Int = 0 public var label: String? = "DataSet" public var visible = true public var drawValuesEnabled = true /// the color used for the value-text public var valueTextColor: UIColor = UIColor.blackColor() /// the font for the value-text labels public var valueFont: UIFont = UIFont.systemFontOfSize(7.0) /// the formatter used to customly format the values public var valueFormatter: NSNumberFormatter? /// the axis this DataSet should be plotted against. public var axisDependency = ChartYAxis.AxisDependency.Left public var yVals: [ChartDataEntry] { return _yVals } public var yValueSum: Double { return _yValueSum } public var yMin: Double { return _yMin } public var yMax: Double { return _yMax } /// if true, value highlighting is enabled public var highlightEnabled = true /// :returns: true if value highlighting is enabled for this dataset public var isHighlightEnabled: Bool { return highlightEnabled } public override init() { super.init() } public init(yVals: [ChartDataEntry]?, label: String?) { super.init() self.label = label _yVals = yVals == nil ? [ChartDataEntry]() : yVals // default color colors.append(UIColor(red: 140.0/255.0, green: 234.0/255.0, blue: 255.0/255.0, alpha: 1.0)) self.calcMinMax(start: _lastStart, end: _lastEnd) self.calcYValueSum() } public convenience init(yVals: [ChartDataEntry]?) { self.init(yVals: yVals, label: "DataSet") } /// Use this method to tell the data set that the underlying data has changed public func notifyDataSetChanged() { calcMinMax(start: _lastStart, end: _lastEnd) calcYValueSum() } internal func calcMinMax(#start : Int, end: Int) { if _yVals!.count == 0 { return } var endValue : Int if end == 0 { endValue = _yVals.count - 1 } else { endValue = end } _lastStart = start _lastEnd = endValue _yMin = DBL_MAX _yMax = -DBL_MIN for (var i = start; i <= endValue; i++) { let e = _yVals[i] if (!e.value.isNaN) { if (e.value < _yMin) { _yMin = e.value } if (e.value > _yMax) { _yMax = e.value } } } if (_yMin == DBL_MAX) { _yMin = 0.0 _yMax = 0.0 } } private func calcYValueSum() { _yValueSum = 0 for var i = 0; i < _yVals.count; i++ { _yValueSum += fabs(_yVals[i].value) } } public var entryCount: Int { return _yVals!.count; } public func yValForXIndex(x: Int) -> Double { let e = self.entryForXIndex(x) if (e !== nil && e!.xIndex == x) { return e!.value } else { return Double.NaN } } /// Returns the first Entry object found at the given xIndex with binary search. /// If the no Entry at the specifed x-index is found, this method returns the Entry at the closest x-index. /// Returns nil if no Entry object at that index. public func entryForXIndex(x: Int) -> ChartDataEntry? { var index = self.entryIndex(xIndex: x) if (index > -1) { return _yVals[index] } return nil } public func entriesForXIndex(x: Int) -> [ChartDataEntry] { var entries = [ChartDataEntry]() var low = 0 var high = _yVals.count - 1 while (low <= high) { var m = Int((high + low) / 2) var entry = _yVals[m] if (x == entry.xIndex) { while (m > 0 && _yVals[m - 1].xIndex == x) { m-- } high = _yVals.count for (; m < high; m++) { entry = _yVals[m] if (entry.xIndex == x) { entries.append(entry) } else { break } } } if (x > _yVals[m].xIndex) { low = m + 1 } else { high = m - 1 } } return entries } public func entryIndex(xIndex x: Int) -> Int { var low = 0 var high = _yVals.count - 1 var closest = -1 while (low <= high) { var m = (high + low) / 2 var entry = _yVals[m] if (x == entry.xIndex) { while (m > 0 && _yVals[m - 1].xIndex == x) { m-- } return m } if (x > entry.xIndex) { low = m + 1 } else { high = m - 1 } closest = m } return closest } public func entryIndex(entry e: ChartDataEntry, isEqual: Bool) -> Int { if (isEqual) { for (var i = 0; i < _yVals.count; i++) { if (_yVals[i].isEqual(e)) { return i } } } else { for (var i = 0; i < _yVals.count; i++) { if (_yVals[i] === e) { return i } } } return -1 } /// Returns the number of entries this DataSet holds. public var valueCount: Int { return _yVals.count; } public func addEntry(e: ChartDataEntry) { var val = e.value if (_yVals == nil) { _yVals = [ChartDataEntry]() } if (_yVals.count == 0) { _yMax = val _yMin = val } else { if (_yMax < val) { _yMax = val } if (_yMin > val) { _yMin = val } } _yValueSum += val _yVals.append(e) } public func removeEntry(entry: ChartDataEntry) -> Bool { var removed = false for (var i = 0; i < _yVals.count; i++) { if (_yVals[i] === entry) { _yVals.removeAtIndex(i) removed = true break } } if (removed) { _yValueSum -= entry.value calcMinMax(start: _lastStart, end: _lastEnd) } return removed } public func removeEntry(#xIndex: Int) -> Bool { var index = self.entryIndex(xIndex: xIndex) if (index > -1) { var e = _yVals.removeAtIndex(index) _yValueSum -= e.value calcMinMax(start: _lastStart, end: _lastEnd) return true } return false } public func resetColors() { colors.removeAll(keepCapacity: false) } public func addColor(color: UIColor) { colors.append(color) } public func setColor(color: UIColor) { colors.removeAll(keepCapacity: false) colors.append(color) } public func colorAt(var index: Int) -> UIColor { if (index < 0) { index = 0 } return colors[index % colors.count] } public var isVisible: Bool { return visible } public var isDrawValuesEnabled: Bool { return drawValuesEnabled } /// Checks if this DataSet contains the specified Entry. /// :returns: true if contains the entry, false if not. public func contains(e: ChartDataEntry) -> Bool { for entry in _yVals { if (entry.isEqual(e)) { return true } } return false } /// Removes all values from this DataSet and recalculates min and max value. public func clear() { _yVals.removeAll(keepCapacity: true) _lastStart = 0 _lastEnd = 0 notifyDataSetChanged() } // MARK: NSObject public override var description: String { return String(format: "ChartDataSet, label: %@, %i entries", arguments: [self.label ?? "", _yVals.count]) } public override var debugDescription: String { var desc = description + ":" for (var i = 0; i < _yVals.count; i++) { desc += "\n" + _yVals[i].description } return desc } // MARK: NSCopying public func copyWithZone(zone: NSZone) -> AnyObject { var copy = self.dynamicType.allocWithZone(zone) as ChartDataSet copy.colors = colors copy._yVals = _yVals copy._yMax = _yMax copy._yMin = _yMin copy._yValueSum = _yValueSum copy.label = self.label return copy } }
apache-2.0
5b6a589e66a46655784a08bcb4fa9998
22.632287
113
0.452277
4.758465
false
false
false
false
usbong/UsbongKit
UsbongKit/Usbong/XML/TaskNodeType.swift
2
944
// // TaskNodeType.swift // UsbongKit // // Created by Chris Amanse on 26/05/2016. // Copyright © 2016 Usbong Social Systems, Inc. All rights reserved. // import Foundation /// Task node types internal enum TaskNodeType: String { case TextDisplay = "textDisplay" case ImageDisplay = "imageDisplay" case TextImageDisplay = "textImageDisplay" case ImageTextDisplay = "imageTextDisplay" case Link = "link" case RadioButtons = "radioButtons" case Checklist = "checkList" case Classification = "classification" case TextField = "textField" case TextFieldNumerical = "textFieldNumerical" case TextFieldWithUnit = "textFieldWithUnit" case TextArea = "textArea" case TextFieldWithAnswer = "textFieldWithAnswer" case TextAreaWithAnswer = "textAreaWithAnswer" case TimestampDisplay = "timestampDisplay" case Date = "date" case RadioButtonsWithAnswer = "radioButtonsWithAnswer" }
apache-2.0
7c0aaaa48c61b6138bfdc93f6d081839
30.433333
69
0.726405
4.247748
false
false
false
false
Geor9eLau/WorkHelper
Carthage/Checkouts/SwiftCharts/SwiftCharts/Views/ChartPointViewBar.swift
1
1764
// // ChartPointViewBar.swift // Examples // // Created by ischuetz on 14/05/15. // Copyright (c) 2015 ivanschuetz. All rights reserved. // import UIKit open class ChartPointViewBar: UIView { fileprivate let targetFrame: CGRect fileprivate let animDuration: Float public init(p1: CGPoint, p2: CGPoint, width: CGFloat, bgColor: UIColor? = nil, animDuration: Float = 0.5) { let (targetFrame, firstFrame): (CGRect, CGRect) = { if p1.y - p2.y == 0 { // horizontal let targetFrame = CGRect(x: p1.x, y: p1.y - width / 2, width: p2.x - p1.x, height: width) let initFrame = CGRect(x: targetFrame.origin.x, y: targetFrame.origin.y, width: 0, height: targetFrame.size.height) return (targetFrame, initFrame) } else { // vertical let targetFrame = CGRect(x: p1.x - width / 2, y: p1.y, width: width, height: p2.y - p1.y) let initFrame = CGRect(x: targetFrame.origin.x, y: targetFrame.origin.y, width: targetFrame.size.width, height: 0) return (targetFrame, initFrame) } }() self.targetFrame = targetFrame self.animDuration = animDuration super.init(frame: firstFrame) self.backgroundColor = bgColor } required public init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override open func didMoveToSuperview() { UIView.animate(withDuration: CFTimeInterval(self.animDuration), delay: 0.0, options: UIViewAnimationOptions.curveEaseOut, animations: {() -> Void in self.frame = self.targetFrame }, completion: nil) } }
mit
67616e99ebbf27d3e79fe1fbd456623e
35.75
156
0.599773
4.2
false
false
false
false
RickieL/learn-swift
swift-automatic-reference-counting.playground/section-1.swift
1
3100
// Playground - noun: a place where people can play import UIKit var str = "Hello, playground" class Person { let name: String init(name: String) { self.name = name println("\(name) is being initialized") } deinit { println("\(name) is being deinitialized") } } var reference1: Person? var reference2: Person? var reference3: Person? reference1 = Person(name: "John Appleseed") reference2 = reference1 reference3 = reference1 reference1 = nil reference2 = nil reference3 = nil /* Xcode's Playgrounds for Swift don't work like regular apps; they aren't being run just once. The objects created stay in memory and can be inspected until you change the code, at which point the whole playground is reevaluated. When this happens, all previous results are discarded and while all object will be deallocated, you won't see any output from that. Your code is correct, but Playgrounds is not suited to test things related to memory management. Here's a related SO question: Memory leaks in the swift playground / deinit{} not called consistently http://stackoverflow.com/questions/24021340/memory-leaks-in-the-swift-playground-deinit-not-called-consistently */ // unowned references class Customer { let name: String var card: CreditCard? init(name: String) { self.name = name } deinit { println("\(name) is being deinitialized.") } } class CreditCard { let number: UInt64 unowned let customer: Customer init(number: UInt64, customer: Customer) { self.number = number self.customer = customer } deinit { println("Card #\(number) is being deinitialized") } } var john: Customer? john = Customer(name: "John Appleseed") john!.card = CreditCard(number: 1234_5678_9012_3456, customer: john!) john = nil class Country { let name: String let capitalCity: City! init(name: String, capitalName: String) { self.name = name self.capitalCity = City(name: capitalName, country: self) } } class City { let name: String unowned let country: Country init(name: String, country: Country) { self.name = name self.country = country } } var country = Country(name: "Canada", capitalName: "Ottawa") println("\(country.name)'s capital city is called \(country.capitalCity.name)") // strong reference cycles for closures class HTMLElement { let name: String let text: String? lazy var asHTML: () -> String = { // [ unowned self ] in //resolving strong reference cycles for closures if let text = self.text { return "<\(self.name)>\(text)</\(self.name)>" } else { return "<\(self.name) />" } } init(name:String, text: String? = nil) { self.name = name self.text = text } deinit { println("\(name) is being deinitialized") } } var paragraph: HTMLElement? = HTMLElement(name: "p", text: "hello, world") println(paragraph!.asHTML()) paragraph = nil // resolving strong reference cycles for closures
bsd-3-clause
4f2f6df0f9a77f516abdef476db8b2cb
24.833333
359
0.662903
4.052288
false
false
false
false
JyerZ/BeiDou-iOS
BeiDou/Intro2TermsViewController.swift
1
3822
// // Intro2TermsViewController.swift // BeiDou // // Created by Jyer on 2017/1/25. // Copyright © 2017年 zjyzbfxgxzh. All rights reserved. // import UIKit class Intro2TermsViewController: UITableViewController { var titles_contents: [[String:String]]! override func viewDidLoad() { super.viewDidLoad() let path = Bundle.main.path(forResource: "Intro2Terms", ofType: "plist") let Info = NSDictionary.init(contentsOfFile: path!) titles_contents = Info?["intro2terms"]! as! [NSDictionary] as! [[String:String]] // 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 didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source override func numberOfSections(in tableView: UITableView) -> Int { // #warning Incomplete implementation, return the number of sections return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete implementation, return the number of rows return titles_contents.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "Intro2TermsCell", for: indexPath) // Configure the cell... cell.textLabel?.text = titles_contents[indexPath.row]["title"] return cell } /* // Override to support conditional editing of the table view. override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { // Return false if you do not want the specified item to be editable. return true } */ /* // Override to support editing the table view. override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { if editingStyle == .delete { // Delete the row from the data source tableView.deleteRows(at: [indexPath], with: .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, moveRowAt fromIndexPath: IndexPath, to: IndexPath) { } */ /* // Override to support conditional rearranging of the table view. override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool { // Return false if you do not want the item to be re-orderable. return true } */ // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation 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. let detailVC = segue.destination as! DetailViewController let indexPath = tableView.indexPath(for: sender as! UITableViewCell)! let titleName = titles_contents[indexPath.row]["title"] detailVC.navigationItem.title = titleName detailVC.content = titles_contents[indexPath.row]["content"]! } }
unlicense
80b43eac04247c8bb1c23def62e340de
35.721154
136
0.674784
5.119303
false
false
false
false
benlangmuir/swift
test/SILGen/subclass_existentials.swift
2
27249
// RUN: %target-swift-emit-silgen -module-name subclass_existentials -Xllvm -sil-full-demangle -parse-as-library -primary-file %s -verify | %FileCheck %s // RUN: %target-swift-emit-ir -module-name subclass_existentials -parse-as-library -primary-file %s // Note: we pass -verify above to ensure there are no spurious // compiler warnings relating to casts. protocol Q {} class Base<T> : Q { required init(classInit: ()) {} func classSelfReturn() -> Self { return self } static func classSelfReturn() -> Self { return self.init(classInit: ()) } } protocol P { init(protocolInit: ()) func protocolSelfReturn() -> Self static func protocolSelfReturn() -> Self } class Derived : Base<Int>, P { required init(protocolInit: ()) { super.init(classInit: ()) } required init(classInit: ()) { super.init(classInit: ()) } func protocolSelfReturn() -> Self { return self } static func protocolSelfReturn() -> Self { return self.init(classInit: ()) } } protocol R {} // CHECK-LABEL: sil hidden [ossa] @$s21subclass_existentials11conversions8baseAndP7derived0fE1R0dE5PType0F4Type0fE5RTypeyAA1P_AA4BaseCySiGXc_AA7DerivedCAA1R_ANXcAaI_ALXcXpANmAaO_ANXcXptF : $@convention(thin) (@guaranteed any Base<Int> & P, @guaranteed Derived, @guaranteed any Derived & R, @thick any (Base<Int> & P).Type, @thick Derived.Type, @thick any (Derived & R).Type) -> () { // CHECK: bb0([[ARG0:%.*]] : @guaranteed $any Base<Int> & P, func conversions( baseAndP: Base<Int> & P, derived: Derived, derivedAndR: Derived & R, baseAndPType: (Base<Int> & P).Type, derivedType: Derived.Type, derivedAndRType: (Derived & R).Type) { // Values // CHECK: [[PAYLOAD:%.*]] = open_existential_ref [[ARG0]] : $any Base<Int> & P // CHECK: [[REF:%.*]] = copy_value [[PAYLOAD]] // CHECK: [[BASE:%.*]] = upcast [[REF]] : $@opened("{{.*}}", any Base<Int> & P) Self to $Base<Int> // CHECK: destroy_value [[BASE]] : $Base<Int> let _: Base<Int> = baseAndP // CHECK: [[PAYLOAD:%.*]] = open_existential_ref [[ARG0]] : $any Base<Int> & P // CHECK: [[RESULT:%.*]] = alloc_stack $any P // CHECK: [[RESULT_PAYLOAD:%.*]] = init_existential_addr [[RESULT]] : $*any P, $@opened("{{.*}}", any Base<Int> & P) Self // CHECK: [[REF:%.*]] = copy_value [[PAYLOAD]] // CHECK: store [[REF]] to [init] [[RESULT_PAYLOAD]] // CHECK: destroy_addr [[RESULT]] : $*any P // CHECK: dealloc_stack [[RESULT]] : $*any P let _: P = baseAndP // CHECK: [[PAYLOAD:%.*]] = open_existential_ref [[ARG0]] : $any Base<Int> & P // CHECK: [[RESULT:%.*]] = alloc_stack $any Q // CHECK: [[RESULT_PAYLOAD:%.*]] = init_existential_addr [[RESULT]] : $*any Q, $@opened("{{.*}}", any Base<Int> & P) Self // CHECK: [[REF:%.*]] = copy_value [[PAYLOAD]] // CHECK: store [[REF]] to [init] [[RESULT_PAYLOAD]] // CHECK: destroy_addr [[RESULT]] : $*any Q // CHECK: dealloc_stack [[RESULT]] : $*any Q let _: Q = baseAndP // CHECK: [[PAYLOAD:%.*]] = open_existential_ref [[ARG2:%.*]] : $any Derived & R // CHECK: [[REF:%.*]] = copy_value [[PAYLOAD]] // CHECK: [[RESULT:%.*]] = init_existential_ref [[REF]] : $@opened("{{.*}}", any Derived & R) Self : $@opened("{{.*}}", any Derived & R) Self, $any Base<Int> & P // CHECK: destroy_value [[RESULT]] let _: Base<Int> & P = derivedAndR // Metatypes // CHECK: [[PAYLOAD:%.*]] = open_existential_metatype %3 : $@thick any (Base<Int> & P).Type to $@thick (@opened("{{.*}}", any Base<Int> & P) Self).Type // CHECK: [[RESULT:%.*]] = upcast [[PAYLOAD]] : $@thick (@opened("{{.*}}", any Base<Int> & P) Self).Type to $@thick Base<Int>.Type let _: Base<Int>.Type = baseAndPType // CHECK: [[PAYLOAD:%.*]] = open_existential_metatype %3 : $@thick any (Base<Int> & P).Type to $@thick (@opened("{{.*}}", any Base<Int> & P) Self).Type // CHECK: [[RESULT:%.*]] = init_existential_metatype [[PAYLOAD]] : $@thick (@opened("{{.*}}", any Base<Int> & P) Self).Type, $@thick any P.Type let _: P.Type = baseAndPType // CHECK: [[PAYLOAD:%.*]] = open_existential_metatype %3 : $@thick any (Base<Int> & P).Type to $@thick (@opened("{{.*}}", any Base<Int> & P) Self).Type // CHECK: [[RESULT:%.*]] = init_existential_metatype [[PAYLOAD]] : $@thick (@opened("{{.*}}", any Base<Int> & P) Self).Type, $@thick any Q.Type let _: Q.Type = baseAndPType // CHECK: [[RESULT:%.*]] = init_existential_metatype %4 : $@thick Derived.Type, $@thick any (Base<Int> & P).Type let _: (Base<Int> & P).Type = derivedType // CHECK: [[PAYLOAD:%.*]] = open_existential_metatype %5 : $@thick any (Derived & R).Type to $@thick (@opened("{{.*}}", any Derived & R) Self).Type // CHECK: [[RESULT:%.*]] = init_existential_metatype [[PAYLOAD]] : $@thick (@opened("{{.*}}", any Derived & R) Self).Type, $@thick any (Base<Int> & P).Type let _: (Base<Int> & P).Type = derivedAndRType // CHECK: return } // CHECK-LABEL: sil hidden [ossa] @$s21subclass_existentials11methodCalls8baseAndP0eF5PTypeyAA1P_AA4BaseCySiGXc_AaE_AHXcXptF : $@convention(thin) (@guaranteed any Base<Int> & P, @thick any (Base<Int> & P).Type) -> () { func methodCalls( baseAndP: Base<Int> & P, baseAndPType: (Base<Int> & P).Type) { // CHECK: bb0([[ARG0:%.*]] : @guaranteed $any Base<Int> & P, // CHECK: [[PAYLOAD:%.*]] = open_existential_ref [[ARG0]] : $any Base<Int> & P to $@opened("{{.*}}", any Base<Int> & P) Self // CHECK: [[REF:%.*]] = copy_value [[PAYLOAD]] : $@opened("{{.*}}", any Base<Int> & P) Self // CHECK: [[CLASS_REF:%.*]] = upcast [[REF]] : $@opened("{{.*}}", any Base<Int> & P) Self to $Base<Int> // CHECK: [[METHOD:%.*]] = class_method [[CLASS_REF]] : $Base<Int>, #Base.classSelfReturn : <T> (Base<T>) -> () -> @dynamic_self Base<T>, $@convention(method) <τ_0_0> (@guaranteed Base<τ_0_0>) -> @owned Base<τ_0_0> // CHECK: [[RESULT_CLASS_REF:%.*]] = apply [[METHOD]]<Int>([[CLASS_REF]]) : $@convention(method) <τ_0_0> (@guaranteed Base<τ_0_0>) -> @owned Base<τ_0_0> // CHECK: destroy_value [[CLASS_REF]] : $Base<Int> // CHECK: [[RESULT_REF:%.*]] = unchecked_ref_cast [[RESULT_CLASS_REF]] : $Base<Int> to $@opened("{{.*}}", any Base<Int> & P) Self // CHECK: [[RESULT:%.*]] = init_existential_ref [[RESULT_REF]] : $@opened("{{.*}}", any Base<Int> & P) Self, $any Base<Int> & P // CHECK: destroy_value [[RESULT]] : $any Base<Int> & P let _: Base<Int> & P = baseAndP.classSelfReturn() // CHECK: [[PAYLOAD:%.*]] = open_existential_ref [[ARG0]] : $any Base<Int> & P to $@opened("{{.*}}", any Base<Int> & P) Self // CHECK: [[SELF_BOX:%.*]] = alloc_stack $@opened("{{.*}}", any Base<Int> & P) Self // CHECK: [[SB:%.*]] = store_borrow [[PAYLOAD]] to [[SELF_BOX]] : $*@opened("{{.*}}", any Base<Int> & P) Self // CHECK: [[METHOD:%.*]] = witness_method $@opened("{{.*}}", any Base<Int> & P) Self, #P.protocolSelfReturn : <Self where Self : P> (Self) -> () -> Self, [[PAYLOAD]] : $@opened("{{.*}}", any Base<Int> & P) Self : $@convention(witness_method: P) <τ_0_0 where τ_0_0 : P> (@in_guaranteed τ_0_0) -> @out τ_0_0 // CHECK: [[RESULT_BOX:%.*]] = alloc_box // CHECK: [[RESULT_LIFETIME:%[^,]+]] = begin_borrow [lexical] [[RESULT_BOX]] // CHECK: [[RESULT_BUF:%.*]] = project_box [[RESULT_LIFETIME]] // CHECK: apply [[METHOD]]<@opened("{{.*}}", any Base<Int> & P) Self>([[RESULT_BUF]], [[SB]]) : $@convention(witness_method: P) <τ_0_0 where τ_0_0 : P> (@in_guaranteed τ_0_0) -> @out τ_0_0 // end_borrow [[SB]] // CHECK: dealloc_stack [[SELF_BOX]] : $*@opened("{{.*}}", any Base<Int> & P) Self // CHECK: [[RESULT_REF:%.*]] = load [take] [[RESULT_BUF]] : $*@opened("{{.*}}", any Base<Int> & P) Self // CHECK: [[RESULT:%.*]] = init_existential_ref [[RESULT_REF]] : $@opened("{{.*}}", any Base<Int> & P) Self : $@opened("{{.*}}", any Base<Int> & P) Self, $any Base<Int> & P // CHECK: destroy_value [[RESULT]] : $any Base<Int> & P // CHECK: end_borrow [[RESULT_LIFETIME]] // CHECK: dealloc_box [[RESULT_BOX]] let _: Base<Int> & P = baseAndP.protocolSelfReturn() // CHECK: [[METATYPE:%.*]] = open_existential_metatype %1 : $@thick any (Base<Int> & P).Type to $@thick (@opened("{{.*}}", any Base<Int> & P) Self).Type // CHECK: [[METATYPE_REF:%.*]] = upcast [[METATYPE]] : $@thick (@opened("{{.*}}", any Base<Int> & P) Self).Type to $@thick Base<Int>.Type // CHECK: [[METHOD:%.*]] = function_ref @$s21subclass_existentials4BaseC15classSelfReturnACyxGXDyFZ : $@convention(method) <τ_0_0> (@thick Base<τ_0_0>.Type) -> @owned Base<τ_0_0> // CHECK: [[RESULT_REF2:%.*]] = apply [[METHOD]]<Int>([[METATYPE_REF]]) // CHECK: [[RESULT_REF:%.*]] = unchecked_ref_cast [[RESULT_REF2]] : $Base<Int> to $@opened("{{.*}}", any Base<Int> & P) Self // CHECK: [[RESULT:%.*]] = init_existential_ref [[RESULT_REF]] : $@opened("{{.*}}", any Base<Int> & P) Self : $@opened("{{.*}}", any Base<Int> & P) Self, $any Base<Int> & P // CHECK: destroy_value [[RESULT]] let _: Base<Int> & P = baseAndPType.classSelfReturn() // CHECK: [[METATYPE:%.*]] = open_existential_metatype %1 : $@thick any (Base<Int> & P).Type to $@thick (@opened("{{.*}}", any Base<Int> & P) Self).Type // CHECK: [[METHOD:%.*]] = witness_method $@opened("{{.*}}", any Base<Int> & P) Self, #P.protocolSelfReturn : <Self where Self : P> (Self.Type) -> () -> Self, [[METATYPE]] : $@thick (@opened("{{.*}}", any Base<Int> & P) Self).Type : $@convention(witness_method: P) <τ_0_0 where τ_0_0 : P> (@thick τ_0_0.Type) -> @out τ_0_0 // CHECK: [[RESULT_BOX:%.*]] = alloc_box // CHECK: [[RESULT_LIFETIME:%[^,]+]] = begin_borrow [lexical] [[RESULT_BOX]] // CHECK: [[RESULT_BUF:%.*]] = project_box // CHECK: apply [[METHOD]]<@opened("{{.*}}", any Base<Int> & P) Self>([[RESULT_BUF]], [[METATYPE]]) : $@convention(witness_method: P) <τ_0_0 where τ_0_0 : P> (@thick τ_0_0.Type) -> @out τ_0_0 // CHECK: [[RESULT_REF:%.*]] = load [take] [[RESULT_BUF]] : $*@opened("{{.*}}", any Base<Int> & P) Self // CHECK: [[RESULT_VALUE:%.*]] = init_existential_ref [[RESULT_REF]] : $@opened("{{.*}}", any Base<Int> & P) Self : $@opened("{{.*}}", any Base<Int> & P) Self, $any Base<Int> & P // CHECK: destroy_value [[RESULT_VALUE]] // CHECK: end_borrow [[RESULT_LIFETIME]] // CHECK: dealloc_box [[RESULT_BOX]] let _: Base<Int> & P = baseAndPType.protocolSelfReturn() // Partial applications let _: () -> (Base<Int> & P) = baseAndP.classSelfReturn let _: () -> (Base<Int> & P) = baseAndP.protocolSelfReturn let _: () -> (Base<Int> & P) = baseAndPType.classSelfReturn let _: () -> (Base<Int> & P) = baseAndPType.protocolSelfReturn let _: (()) -> (Base<Int> & P) = baseAndPType.init(classInit:) let _: (()) -> (Base<Int> & P) = baseAndPType.init(protocolInit:) // CHECK: return // CHECK-NEXT: } } // CHECK-LABEL: sil hidden [ossa] @$s21subclass_existentials29methodCallsOnProtocolMetatypeyyF : $@convention(thin) () -> () { // CHECK: metatype $@thin (any Base<Int> & P).Type // CHECK: function_ref @$[[THUNK1_NAME:[_a-zA-Z0-9]+]] // CHECK: } // end sil function '$s21subclass_existentials29methodCallsOnProtocolMetatypeyyF' // // CHECK: sil private [ossa] @$[[THUNK1_NAME]] : $@convention(thin) (@guaranteed any Base<Int> & P) -> @owned @callee_guaranteed () -> @owned any Base<Int> & P { // CHECK: bb0(%0 : @guaranteed $any Base<Int> & P): // CHECK: [[THUNK2:%[0-9]+]] = function_ref @$[[THUNK2_NAME:[_a-zA-Z0-9]+]] // CHECK: [[SELF_COPY:%[0-9]+]] = copy_value %0 // CHECK: [[RESULT:%[0-9]+]] = partial_apply [callee_guaranteed] [[THUNK2]]([[SELF_COPY]]) // CHECK: return [[RESULT]] // CHECK: } // end sil function '$[[THUNK1_NAME]]' // // CHECK: sil private [ossa] @$[[THUNK2_NAME]] : $@convention(thin) (@guaranteed any Base<Int> & P) -> @owned any Base<Int> & P { // CHECK: bb0(%0 : @guaranteed $any Base<Int> & P): // CHECK: [[OPENED:%[0-9]+]] = open_existential_ref %0 : $any Base<Int> & P to $[[OPENED_TY:@opened\("[-A-F0-9]+", any Base<Int> & P\) Self]] // CHECK: [[OPENED_COPY:%[0-9]+]] = copy_value [[OPENED]] // CHECK: [[CLASS:%[0-9]+]] = upcast [[OPENED_COPY]] : $[[OPENED_TY]] to $Base<Int> // CHECK: [[METHOD:%[0-9]+]] = class_method [[CLASS]] : $Base<Int>, #Base.classSelfReturn // CHECK: [[RESULT:%[0-9]+]] = apply [[METHOD]]<Int>([[CLASS]]) : $@convention(method) <τ_0_0> (@guaranteed Base<τ_0_0>) -> @owned Base<τ_0_0> // CHECK: destroy_value [[CLASS]] // CHECK: [[TO_OPENED:%[0-9]+]] = unchecked_ref_cast [[RESULT]] : $Base<Int> to $[[OPENED_TY]] // CHECK: [[ERASED:%[0-9]+]] = init_existential_ref [[TO_OPENED]] : $[[OPENED_TY]] // CHECK: return [[ERASED]] // CHECK: } // end sil function '$[[THUNK2_NAME]]' func methodCallsOnProtocolMetatype() { let _ = (Base<Int> & P).classSelfReturn } protocol PropertyP { var p: PropertyP & PropertyC { get set } subscript(key: Int) -> Int { get set } } class PropertyC { var c: PropertyP & PropertyC { get { return self as! PropertyP & PropertyC } set { } } subscript(key: (Int, Int)) -> Int { get { return 0 } set { } } } // CHECK-LABEL: sil hidden [ossa] @$s21subclass_existentials16propertyAccessesyyAA9PropertyP_AA0E1CCXcF : $@convention(thin) (@guaranteed any PropertyC & PropertyP) -> () { func propertyAccesses(_ x: PropertyP & PropertyC) { var xx = x xx.p.p = x xx.c.c = x propertyAccesses(xx.p) propertyAccesses(xx.c) _ = xx[1] xx[1] = 1 xx[1] += 1 _ = xx[(1, 2)] xx[(1, 2)] = 1 xx[(1, 2)] += 1 } // CHECK-LABEL: sil hidden [ossa] @$s21subclass_existentials19functionConversions15returnsBaseAndP0efG5PType0E7Derived0eI4Type0eiG1R0eiG5RTypeyAA1P_AA0F0CySiGXcyc_AaI_ALXcXpycAA0I0CycANmycAA1R_ANXcycAaO_ANXcXpyctF : $@convention(thin) (@guaranteed @callee_guaranteed () -> @owned any Base<Int> & P, @guaranteed @callee_guaranteed () -> @thick any (Base<Int> & P).Type, @guaranteed @callee_guaranteed () -> @owned Derived, @guaranteed @callee_guaranteed () -> @thick Derived.Type, @guaranteed @callee_guaranteed () -> @owned any Derived & R, @guaranteed @callee_guaranteed () -> @thick any (Derived & R).Type) -> () { func functionConversions( returnsBaseAndP: @escaping () -> (Base<Int> & P), returnsBaseAndPType: @escaping () -> (Base<Int> & P).Type, returnsDerived: @escaping () -> Derived, returnsDerivedType: @escaping () -> Derived.Type, returnsDerivedAndR: @escaping () -> Derived & R, returnsDerivedAndRType: @escaping () -> (Derived & R).Type) { let _: () -> Base<Int> = returnsBaseAndP let _: () -> Base<Int>.Type = returnsBaseAndPType let _: () -> P = returnsBaseAndP let _: () -> P.Type = returnsBaseAndPType let _: () -> (Base<Int> & P) = returnsDerived let _: () -> (Base<Int> & P).Type = returnsDerivedType let _: () -> Base<Int> = returnsDerivedAndR let _: () -> Base<Int>.Type = returnsDerivedAndRType let _: () -> (Base<Int> & P) = returnsDerivedAndR let _: () -> (Base<Int> & P).Type = returnsDerivedAndRType let _: () -> P = returnsDerivedAndR let _: () -> P.Type = returnsDerivedAndRType // CHECK: return % // CHECK-NEXT: } } // CHECK-LABEL: sil hidden [ossa] @$s21subclass_existentials9downcasts8baseAndP7derived0dE5PType0F4TypeyAA1P_AA4BaseCySiGXc_AA7DerivedCAaG_AJXcXpALmtF : $@convention(thin) (@guaranteed any Base<Int> & P, @guaranteed Derived, @thick any (Base<Int> & P).Type, @thick Derived.Type) -> () { func downcasts( baseAndP: Base<Int> & P, derived: Derived, baseAndPType: (Base<Int> & P).Type, derivedType: Derived.Type) { // CHECK: bb0([[ARG0:%.*]] : @guaranteed $any Base<Int> & P, [[ARG1:%.*]] : @guaranteed $Derived, [[ARG2:%.*]] : $@thick any (Base<Int> & P).Type, [[ARG3:%.*]] : $@thick Derived.Type): // CHECK: [[COPIED:%.*]] = copy_value [[ARG0]] : $any Base<Int> & P // CHECK-NEXT: checked_cast_br [[COPIED]] : $any Base<Int> & P to Derived let _ = baseAndP as? Derived // CHECK: [[COPIED:%.*]] = copy_value [[ARG0]] : $any Base<Int> & P // CHECK-NEXT: unconditional_checked_cast [[COPIED]] : $any Base<Int> & P to Derived let _ = baseAndP as! Derived // CHECK: [[COPIED:%.*]] = copy_value [[ARG0]] : $any Base<Int> & P // CHECK-NEXT: checked_cast_br [[COPIED]] : $any Base<Int> & P to any Derived & R let _ = baseAndP as? (Derived & R) // CHECK: [[COPIED:%.*]] = copy_value [[ARG0]] : $any Base<Int> & P // CHECK-NEXT: unconditional_checked_cast [[COPIED]] : $any Base<Int> & P to any Derived & R let _ = baseAndP as! (Derived & R) // CHECK: checked_cast_br %3 : $@thick Derived.Type to any (Derived & R).Type let _ = derivedType as? (Derived & R).Type // CHECK: unconditional_checked_cast %3 : $@thick Derived.Type to any (Derived & R).Type let _ = derivedType as! (Derived & R).Type // CHECK: checked_cast_br %2 : $@thick any (Base<Int> & P).Type to Derived.Type let _ = baseAndPType as? Derived.Type // CHECK: unconditional_checked_cast %2 : $@thick any (Base<Int> & P).Type to Derived.Type let _ = baseAndPType as! Derived.Type // CHECK: checked_cast_br %2 : $@thick any (Base<Int> & P).Type to any (Derived & R).Type let _ = baseAndPType as? (Derived & R).Type // CHECK: unconditional_checked_cast %2 : $@thick any (Base<Int> & P).Type to any (Derived & R).Type let _ = baseAndPType as! (Derived & R).Type // CHECK: return // CHECK-NEXT: } } // CHECK-LABEL: sil hidden [ossa] @$s21subclass_existentials16archetypeUpcasts9baseTAndP0E7IntAndP7derivedyq__q0_q1_tAA4BaseCyxGRb_AA1PR_AGySiGRb0_AaIR0_AA7DerivedCRb1_r2_lF : $@convention(thin) <T, BaseTAndP, BaseIntAndP, DerivedT where BaseTAndP : Base<T>, BaseTAndP : P, BaseIntAndP : Base<Int>, BaseIntAndP : P, DerivedT : Derived> (@guaranteed BaseTAndP, @guaranteed BaseIntAndP, @guaranteed DerivedT) -> () { func archetypeUpcasts<T, BaseTAndP : Base<T> & P, BaseIntAndP : Base<Int> & P, DerivedT : Derived>( baseTAndP: BaseTAndP, baseIntAndP : BaseIntAndP, derived : DerivedT) { // CHECK: bb0([[ARG0:%.*]] : @guaranteed $BaseTAndP, [[ARG1:%.*]] : @guaranteed $BaseIntAndP, [[ARG2:%.*]] : @guaranteed $DerivedT) // CHECK: [[COPIED:%.*]] = copy_value [[ARG0]] : $BaseTAndP // CHECK-NEXT: init_existential_ref [[COPIED]] : $BaseTAndP : $BaseTAndP, $any Base<T> & P let _: Base<T> & P = baseTAndP // CHECK: [[COPIED:%.*]] = copy_value [[ARG1]] : $BaseIntAndP // CHECK-NEXT: init_existential_ref [[COPIED]] : $BaseIntAndP : $BaseIntAndP, $any Base<Int> & P let _: Base<Int> & P = baseIntAndP // CHECK: [[COPIED:%.*]] = copy_value [[ARG2]] : $DerivedT // CHECK-NEXT: init_existential_ref [[COPIED]] : $DerivedT : $DerivedT, $any Base<Int> & P let _: Base<Int> & P = derived // CHECK: return // CHECK-NEXT: } } // CHECK-LABEL: sil hidden [ossa] @$s21subclass_existentials18archetypeDowncasts1s1t2pt5baseT0F3Int0f6TAndP_C00fg5AndP_C008derived_C00ji2R_C00fH10P_concrete0fgi2P_K0yx_q_q0_q1_q2_q3_q4_q5_AA1R_AA7DerivedCXcAA1P_AA4BaseCyq_GXcAaQ_ASySiGXctAaQR0_ATRb1_AURb2_ATRb3_AaQR3_AURb4_AaQR4_APRb5_r6_lF : $@convention(thin) <S, T, PT, BaseT, BaseInt, BaseTAndP, BaseIntAndP, DerivedT where PT : P, BaseT : Base<T>, BaseInt : Base<Int>, BaseTAndP : Base<T>, BaseTAndP : P, BaseIntAndP : Base<Int>, BaseIntAndP : P, DerivedT : Derived> (@in_guaranteed S, @in_guaranteed T, @in_guaranteed PT, @guaranteed BaseT, @guaranteed BaseInt, @guaranteed BaseTAndP, @guaranteed BaseIntAndP, @guaranteed DerivedT, @guaranteed any Derived & R, @guaranteed any Base<T> & P, @guaranteed any Base<Int> & P) -> () { func archetypeDowncasts<S, T, PT : P, BaseT : Base<T>, BaseInt : Base<Int>, BaseTAndP : Base<T> & P, BaseIntAndP : Base<Int> & P, DerivedT : Derived>( s: S, t: T, pt: PT, baseT : BaseT, baseInt : BaseInt, baseTAndP_archetype: BaseTAndP, baseIntAndP_archetype : BaseIntAndP, derived_archetype : DerivedT, derivedAndR_archetype : Derived & R, baseTAndP_concrete: Base<T> & P, baseIntAndP_concrete: Base<Int> & P) { // CHECK: ([[ARG0:%.*]] : $*S, [[ARG1:%.*]] : $*T, [[ARG2:%.*]] : $*PT, [[ARG3:%.*]] : @guaranteed $BaseT, [[ARG4:%.*]] : @guaranteed $BaseInt, [[ARG5:%.*]] : @guaranteed $BaseTAndP, [[ARG6:%.*]] : @guaranteed $BaseIntAndP, [[ARG7:%.*]] : @guaranteed $DerivedT, [[ARG8:%.*]] : @guaranteed $any Derived & R, [[ARG9:%.*]] : @guaranteed $any Base<T> & P, [[ARG10:%.*]] : @guaranteed $any Base<Int> & P) // CHECK: [[COPY:%.*]] = alloc_stack $S // CHECK-NEXT: copy_addr %0 to [initialization] [[COPY]] : $*S // CHECK-NEXT: [[RESULT:%.*]] = alloc_stack $any Base<T> & P // CHECK-NEXT: checked_cast_addr_br take_always S in [[COPY]] : $*S to any Base<T> & P in [[RESULT]] : $*any Base<T> & P let _ = s as? (Base<T> & P) // CHECK: [[COPY:%.*]] = alloc_stack $S // CHECK-NEXT: copy_addr [[ARG0]] to [initialization] [[COPY]] : $*S // CHECK-NEXT: [[RESULT:%.*]] = alloc_stack $any Base<T> & P // CHECK-NEXT: unconditional_checked_cast_addr S in [[COPY]] : $*S to any Base<T> & P in [[RESULT]] : $*any Base<T> & P let _ = s as! (Base<T> & P) // CHECK: [[COPY:%.*]] = alloc_stack $S // CHECK-NEXT: copy_addr [[ARG0]] to [initialization] [[COPY]] : $*S // CHECK-NEXT: [[RESULT:%.*]] = alloc_stack $any Base<Int> & P // CHECK-NEXT: checked_cast_addr_br take_always S in [[COPY]] : $*S to any Base<Int> & P in [[RESULT]] : $*any Base<Int> & P let _ = s as? (Base<Int> & P) // CHECK: [[COPY:%.*]] = alloc_stack $S // CHECK-NEXT: copy_addr [[ARG0]] to [initialization] [[COPY]] : $*S // CHECK-NEXT: [[RESULT:%.*]] = alloc_stack $any Base<Int> & P // CHECK-NEXT: unconditional_checked_cast_addr S in [[COPY]] : $*S to any Base<Int> & P in [[RESULT]] : $*any Base<Int> & P let _ = s as! (Base<Int> & P) // CHECK: [[COPIED:%.*]] = copy_value [[ARG5]] : $BaseTAndP // CHECK-NEXT: checked_cast_br [[COPIED]] : $BaseTAndP to any Derived & R let _ = baseTAndP_archetype as? (Derived & R) // CHECK: [[COPIED:%.*]] = copy_value [[ARG5]] : $BaseTAndP // CHECK-NEXT: unconditional_checked_cast [[COPIED]] : $BaseTAndP to any Derived & R let _ = baseTAndP_archetype as! (Derived & R) // CHECK: [[COPIED:%.*]] = copy_value [[ARG9]] : $any Base<T> & P // CHECK-NEXT: [[COPY:%.*]] = alloc_stack $any Base<T> & P // CHECK-NEXT: store [[COPIED]] to [init] [[COPY]] : $*any Base<T> & P // CHECK-NEXT: [[RESULT:%.*]] = alloc_stack $Optional<S> // CHECK-NEXT: [[PAYLOAD:%.*]] = init_enum_data_addr [[RESULT]] : $*Optional<S>, #Optional.some // CHECK-NEXT: checked_cast_addr_br take_always any Base<T> & P in [[COPY]] : $*any Base<T> & P to S in [[PAYLOAD]] : $*S let _ = baseTAndP_concrete as? S // CHECK: [[COPY:%.*]] = alloc_stack $any Base<T> & P // CHECK-NEXT: [[COPIED:%.*]] = copy_value [[ARG9]] : $any Base<T> & P // CHECK-NEXT: store [[COPIED]] to [init] [[COPY]] : $*any Base<T> & P // CHECK-NEXT: [[RESULT:%.*]] = alloc_stack $S // CHECK-NEXT: unconditional_checked_cast_addr any Base<T> & P in [[COPY]] : $*any Base<T> & P to S in [[RESULT]] : $*S let _ = baseTAndP_concrete as! S // CHECK: [[COPIED:%.*]] = copy_value [[ARG9]] : $any Base<T> & P // CHECK-NEXT: checked_cast_br [[COPIED]] : $any Base<T> & P to BaseT let _ = baseTAndP_concrete as? BaseT // CHECK: [[COPIED:%.*]] = copy_value [[ARG9]] : $any Base<T> & P // CHECK-NEXT: unconditional_checked_cast [[COPIED]] : $any Base<T> & P to BaseT let _ = baseTAndP_concrete as! BaseT // CHECK: [[COPIED:%.*]] = copy_value [[ARG9]] : $any Base<T> & P // CHECK-NEXT: checked_cast_br [[COPIED]] : $any Base<T> & P to BaseInt let _ = baseTAndP_concrete as? BaseInt // CHECK: [[COPIED:%.*]] = copy_value [[ARG9]] : $any Base<T> & P // CHECK-NEXT: unconditional_checked_cast [[COPIED]] : $any Base<T> & P to BaseInt let _ = baseTAndP_concrete as! BaseInt // CHECK: [[COPIED:%.*]] = copy_value [[ARG9]] : $any Base<T> & P // CHECK-NEXT: checked_cast_br [[COPIED]] : $any Base<T> & P to BaseTAndP let _ = baseTAndP_concrete as? BaseTAndP // CHECK: [[COPIED:%.*]] = copy_value [[ARG9]] : $any Base<T> & P // CHECK-NEXT: unconditional_checked_cast [[COPIED]] : $any Base<T> & P to BaseTAndP let _ = baseTAndP_concrete as! BaseTAndP // CHECK: [[COPIED:%.*]] = copy_value [[ARG6]] : $BaseIntAndP // CHECK-NEXT: checked_cast_br [[COPIED]] : $BaseIntAndP to any Derived & R let _ = baseIntAndP_archetype as? (Derived & R) // CHECK: [[COPIED:%.*]] = copy_value [[ARG6]] : $BaseIntAndP // CHECK-NEXT: unconditional_checked_cast [[COPIED]] : $BaseIntAndP to any Derived & R let _ = baseIntAndP_archetype as! (Derived & R) // CHECK: [[COPIED:%.*]] = copy_value [[ARG10]] : $any Base<Int> & P // CHECK-NEXT: [[COPY:%.*]] = alloc_stack $any Base<Int> & P // CHECK-NEXT: store [[COPIED]] to [init] [[COPY]] : $*any Base<Int> & P // CHECK-NEXT: [[RESULT:%.*]] = alloc_stack $Optional<S> // CHECK-NEXT: [[PAYLOAD:%.*]] = init_enum_data_addr [[RESULT]] : $*Optional<S>, #Optional.some // CHECK-NEXT: checked_cast_addr_br take_always any Base<Int> & P in [[COPY]] : $*any Base<Int> & P to S in [[PAYLOAD]] : $*S let _ = baseIntAndP_concrete as? S // CHECK: [[COPY:%.*]] = alloc_stack $any Base<Int> & P // CHECK-NEXT: [[COPIED:%.*]] = copy_value [[ARG10]] : $any Base<Int> & P // CHECK-NEXT: store [[COPIED]] to [init] [[COPY]] : $*any Base<Int> & P // CHECK-NEXT: [[RESULT:%.*]] = alloc_stack $S // CHECK-NEXT: unconditional_checked_cast_addr any Base<Int> & P in [[COPY]] : $*any Base<Int> & P to S in [[RESULT]] : $*S let _ = baseIntAndP_concrete as! S // CHECK: [[COPIED:%.*]] = copy_value [[ARG10]] : $any Base<Int> & P // CHECK-NEXT: checked_cast_br [[COPIED]] : $any Base<Int> & P to DerivedT let _ = baseIntAndP_concrete as? DerivedT // CHECK: [[COPIED:%.*]] = copy_value [[ARG10]] : $any Base<Int> & P // CHECK-NEXT: unconditional_checked_cast [[COPIED]] : $any Base<Int> & P to DerivedT let _ = baseIntAndP_concrete as! DerivedT // CHECK: [[COPIED:%.*]] = copy_value [[ARG10]] : $any Base<Int> & P // CHECK-NEXT: checked_cast_br [[COPIED]] : $any Base<Int> & P to BaseT let _ = baseIntAndP_concrete as? BaseT // CHECK: [[COPIED:%.*]] = copy_value [[ARG10]] : $any Base<Int> & P // CHECK-NEXT: unconditional_checked_cast [[COPIED]] : $any Base<Int> & P to BaseT let _ = baseIntAndP_concrete as! BaseT // CHECK: [[COPIED:%.*]] = copy_value [[ARG10]] : $any Base<Int> & P // CHECK-NEXT: checked_cast_br [[COPIED]] : $any Base<Int> & P to BaseInt let _ = baseIntAndP_concrete as? BaseInt // CHECK: [[COPIED:%.*]] = copy_value [[ARG10]] : $any Base<Int> & P // CHECK-NEXT: unconditional_checked_cast [[COPIED]] : $any Base<Int> & P to BaseInt let _ = baseIntAndP_concrete as! BaseInt // CHECK: [[COPIED:%.*]] = copy_value [[ARG10]] : $any Base<Int> & P // CHECK-NEXT: checked_cast_br [[COPIED]] : $any Base<Int> & P to BaseTAndP let _ = baseIntAndP_concrete as? BaseTAndP // CHECK: [[COPIED:%.*]] = copy_value [[ARG10]] : $any Base<Int> & P // CHECK-NEXT: unconditional_checked_cast [[COPIED]] : $any Base<Int> & P to BaseTAndP let _ = baseIntAndP_concrete as! BaseTAndP // CHECK: return // CHECK-NEXT: } }
apache-2.0
2174ff9c328bb9f4ac5e34aee4aaecab
52.796443
785
0.595827
3.12993
false
false
false
false
DaveWoodCom/XCGLogger
DemoApps/tvOSDemo/tvOSDemo/AppDelegate.swift
3
4748
// // AppDelegate.swift // tvOSDemo // // Created by Dave Wood on 2015-09-09. // Copyright © 2015 Cerebral Gardens. All rights reserved. // import UIKit import XCGLogger let appDelegate = UIApplication.shared.delegate as! AppDelegate let log: XCGLogger = { // Setup XCGLogger let log = XCGLogger.default #if USE_NSLOG // Set via Build Settings, under Other Swift Flags log.remove(logDestinationWithIdentifier: XCGLogger.Constants.baseConsoleLogDestinationIdentifier) log.add(logDestination: XCGNSLogDestination(identifier: XCGLogger.Constants.nslogDestinationIdentifier)) log.logAppDetails() #else let logPath: URL = appDelegate.cacheDirectory.appendingPathComponent("XCGLogger_Log.txt") log.setup(level: .debug, showThreadName: true, showLevel: true, showFileNames: true, showLineNumbers: true, writeToFile: logPath) // Add colour (using the ANSI format) to our file log, you can see the colour when `cat`ing or `tail`ing the file in Terminal on macOS // This is mostly useful when testing in the simulator, or if you have the app sending you log files remotely if let fileDestination: FileDestination = log.destination(withIdentifier: XCGLogger.Constants.fileDestinationIdentifier) as? FileDestination { let ansiColorLogFormatter: ANSIColorLogFormatter = ANSIColorLogFormatter() ansiColorLogFormatter.colorize(level: .verbose, with: .colorIndex(number: 244), options: [.faint]) ansiColorLogFormatter.colorize(level: .debug, with: .black) ansiColorLogFormatter.colorize(level: .info, with: .blue, options: [.underline]) ansiColorLogFormatter.colorize(level: .notice, with: .green, options: [.italic]) ansiColorLogFormatter.colorize(level: .warning, with: .red, options: [.faint]) ansiColorLogFormatter.colorize(level: .error, with: .red, options: [.bold]) ansiColorLogFormatter.colorize(level: .severe, with: .white, on: .red) ansiColorLogFormatter.colorize(level: .alert, with: .white, on: .red, options: [.bold]) ansiColorLogFormatter.colorize(level: .emergency, with: .white, on: .red, options: [.bold, .blink]) fileDestination.formatters = [ansiColorLogFormatter] } #endif return log }() @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? let documentsDirectory: URL = { let urls = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask) return urls[urls.endIndex - 1] }() let cacheDirectory: URL = { let urls = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask) return urls[urls.endIndex - 1] }() func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. // Display initial app info _ = log return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
mit
01417d196b2e08fee4eabb8856a26fe4
52.337079
285
0.720034
5.044633
false
false
false
false
SuperAwesomeLTD/sa-kws-app-demo-ios
KWSDemo/MainController.swift
1
1383
// // MainController.swift // KWSDemo // // Created by Gabriel Coman on 29/06/2017. // Copyright © 2017 Gabriel Coman. All rights reserved. // import UIKit class MainController: KWSBaseController { @IBOutlet weak var headerView: UIView! @IBOutlet weak var platformContainer: UIView! @IBOutlet weak var featuresContainer: UIView! @IBOutlet weak var docsContainer: UIView! override func viewDidLoad() { super.viewDidLoad() headerView.layer.masksToBounds = false headerView.layer.shadowOffset = CGSize(width: 0, height: 3.5) headerView.layer.shadowRadius = 1 headerView.layer.shadowOpacity = 0.125 } @IBAction func indexChanged(_ segmentedControl: UISegmentedControl) { switch segmentedControl.selectedSegmentIndex { case 0: platformContainer.isHidden = false featuresContainer.isHidden = true docsContainer.isHidden = true break case 1: platformContainer.isHidden = true featuresContainer.isHidden = false docsContainer.isHidden = true break case 2: platformContainer.isHidden = true featuresContainer.isHidden = true docsContainer.isHidden = false break default: break; } } }
gpl-3.0
c378ee0cb57481145dcc8ae17252e237
27.204082
73
0.622287
5.234848
false
false
false
false
LittlePeculiar/GMSearchTextWithDropdown
GMSearchTextWithDropdown/GMSearchTextDropdown/GMSearchText.swift
1
7462
// // GMSearchText.swift // GMSearchTextWithDropdown // // Created by Gina Mullins on 1/5/17. // Copyright © 2017 Gina Mullins. All rights reserved. // // 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 protocol GMSearchTextDelegate: class { // all optional func searchTextCancelButtonClicked(searchText: GMSearchText) func searchTextSearchButtonClicked(searchText: GMSearchText) func searchTextTextFieldShouldBeginEditing(searchText: GMSearchText) -> Bool func searchTextTextFieldDidBeginEditing(searchText: GMSearchText) func searchTextTextFieldDidEndEditing(searchText: GMSearchText) func textDidChange(searchText: String) } class GMSearchText: UIView, UITextFieldDelegate, GMSearchTextDelegate { // public weak var delegate: GMSearchTextDelegate? var textField = FloatingLabelTextField() var title: String? { didSet { if let title = title { self.textField.setFloatingLabelText(text: title) } } } var text: String { get { return self.textField.text ?? "" } set(newValue) { if newValue != text { self.textField.text = newValue } } } var placeholder: String? { didSet { if let placeholder = placeholder { self.textField.placeholder = placeholder } } } var font: UIFont? { didSet { if let font = font { self.textField.font = font } } } var textColor: UIColor? { didSet { if let textColor = textColor { self.textField.textColor = textColor } } } // private private var innerDelegate: GMSearchTextDelegate { return delegate ?? self } private var cancelButton = UIButton() private var cancelButtonHidden: Bool = true { didSet { self.cancelButton.isHidden = cancelButtonHidden } } private let kXMargin = 10 private let kYMargin = 5 private let kIconSize = 16 private let ksearchTextHeight = 50 /// - Initializers private func commonInit() { self.backgroundColor = UIColor.clear let boundsWidth = self.bounds.size.width let textFieldWidth = boundsWidth - CGFloat(2*kXMargin + 2*kIconSize) let textFieldHeight = self.bounds.size.height - CGFloat(kYMargin) let textFieldFrame = CGRect(x: CGFloat(2*kXMargin), y: CGFloat(kYMargin), width: CGFloat(textFieldWidth), height: CGFloat(textFieldHeight)) // TextField self.textField.frame = textFieldFrame self.textField.delegate = self; self.textField.returnKeyType = .search self.textField.autocapitalizationType = .none self.textField.autocorrectionType = .no self.textField.font = UIFont.systemFont(ofSize: 15.0) self.textField.textColor = UIColor.black self.textField.floatingLabelActiveTextColor = UIColor(red: 81/255.0, green: 160/255.0 , blue: 183/255.0, alpha: 1.0) self.addSubview(self.textField) // Cancel Button let cancelIcon = UIImage(named: "Cancel") let posX = Int(self.textField.frame.origin.x + self.textField.frame.size.width) - kIconSize - kXMargin let posY = Int(self.textField.frame.size.height) - kIconSize - kYMargin let buttonFrame = CGRect(x: CGFloat(posX), y: CGFloat(posY), width: CGFloat(kIconSize), height: CGFloat(kIconSize)) self.cancelButton = UIButton(frame: buttonFrame) self.cancelButton.setImage(cancelIcon, for: .normal) self.cancelButton.contentMode = .scaleAspectFit self.cancelButton.addTarget(self, action: #selector(cancelPressed), for: .touchUpInside) self.addSubview(self.cancelButton) cancelButtonHidden = true // Listen to text changes NotificationCenter.default.addObserver(self, selector: #selector(textChanged), name: .UITextFieldTextDidChange, object: self.textField) } @objc private func cancelPressed() { self.innerDelegate.searchTextCancelButtonClicked(searchText: self) self.text = ""; cancelButtonHidden = true } @objc private func textChanged() { self.innerDelegate.textDidChange(searchText: self.text) cancelButtonHidden = (self.text.isEmpty) ? true : false } /// - TextField Delegates internal func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool { return (self.innerDelegate.searchTextTextFieldShouldBeginEditing(searchText: self)) } internal func textFieldDidBeginEditing(_ textField: UITextField) { self.innerDelegate.searchTextTextFieldDidBeginEditing(searchText: self) } internal func textFieldDidEndEditing(_ textField: UITextField) { self.innerDelegate.searchTextTextFieldDidEndEditing(searchText: self) } internal func textFieldShouldReturn(_ textField: UITextField) -> Bool { self.innerDelegate.searchTextSearchButtonClicked(searchText: self) return true } override func draw(_ rect: CGRect) { let underlineColor = UIColor(red: 81/255.0, green: 160/255.0 , blue: 183/255.0, alpha: 1.0) let bottomBorder = CALayer() bottomBorder.frame = CGRect(x: self.textField.frame.origin.x, y: self.textField.frame.size.height+1, width: self.textField.frame.size.width, height: 1.0) bottomBorder.backgroundColor = underlineColor.cgColor self.layer .addSublayer(bottomBorder) } /// Default initializer override init(frame: CGRect) { var newFrame = frame newFrame.size.height = CGFloat(ksearchTextHeight) super.init(frame: newFrame) commonInit() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) commonInit() } } // for optional protocol methods extension GMSearchTextDelegate { func searchTextCancelButtonClicked(searchText: GMSearchText) {} func searchTextSearchButtonClicked(searchText: GMSearchText) {} func searchTextTextFieldShouldBeginEditing(searchText: GMSearchText) -> Bool {return true} func searchTextTextFieldDidBeginEditing(searchText: GMSearchText) {} func searchTextTextFieldDidEndEditing(searchText: GMSearchText) {} func textDidChange(searchText: String) {} }
mit
8d9f19bd68aaf71731553e6ccf3940c0
34.870192
161
0.682482
4.755258
false
false
false
false
CallMeDaKing/DouYuAPP
DouYuProject/DouYuProject/Classes/Main/Controller/BaseAnchorViewController.swift
1
4194
// // BaseAnchorViewController.swift // DouYuProject // // Created by li king on 2018/1/2. // Copyright © 2018年 li king. All rights reserved. // import UIKit //MARK --自定义常量 private let kItemMargin :CGFloat = 10 private let kItemW = (kScreenW - 3 * kItemMargin)/2 private let kItemH = kItemW * 3/4 private let kPrettyH = kItemW * 4/3 private let KHeaderViewH :CGFloat = 50 private let kCycleViewH :CGFloat = kScreenW * 3/8 private let kNormalCellID = "kNormalCellID" private let kHeaderViewID = "kHeaderViewID" private let kPrettyCellID = "PrettyCellID" private let kGameViewH :CGFloat = 90 //Mark:抽取的父类 class BaseAnchorViewController: UIViewController { //Mark:定义属性 因为对具体是哪一个viewmodel ,所以在父类就不进行赋值,让子类赋值 但是必须保一定有值, var baseVM : BaseViewModel! lazy var collectionView : UICollectionView = { //1. 创建collectionview的flowlayout let layout = UICollectionViewFlowLayout() layout.itemSize = CGSize(width: kItemW, height: kItemH) layout.minimumLineSpacing = 0 layout.minimumInteritemSpacing = kItemMargin layout.headerReferenceSize = CGSize(width: kScreenW, height: KHeaderViewH) layout.sectionInset = UIEdgeInsets(top: 0, left: kItemMargin, bottom: 0, right: kItemMargin) //2创建collectionview let collectionView = UICollectionView(frame: CGRect(x: 0, y: 0, width: kScreenW, height: kScreenH - kStateBarH - kNavigationBarH - kTabBarH - 40), collectionViewLayout: layout) collectionView.backgroundColor = UIColor.white collectionView.dataSource = self collectionView.delegate = self // collectionView.autoresizingMask = [.flexibleHeight,.flexibleWidth] collectionView.register(UINib(nibName:"CollectionNormalCell",bundle:nil), forCellWithReuseIdentifier: kNormalCellID) collectionView.register(UINib(nibName:"CollectionPrettyCell",bundle:nil), forCellWithReuseIdentifier: kPrettyCellID) //注册组头 collectionView.register(UINib.init(nibName: "CollectionHeaderView", bundle: nil), forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: kHeaderViewID) return collectionView }() //Mark:系统回调 override func viewDidLoad() { super.viewDidLoad() setUpUI() loadData() } } //Mark:设置UI界面 extension BaseAnchorViewController{ private func setUpUI(){ view.addSubview(collectionView) } } //Mark:请求数据 父类有加载数据的方法们但是方法不同,仅做一个空方法,具体有子类去实现 //extension BaseAnchorViewController{ // internal func loadData(){} //} //Mark:遵从数据源和代理协议 extension BaseAnchorViewController:UICollectionViewDataSource ,UICollectionViewDelegate{ func numberOfSections(in collectionView: UICollectionView) -> Int { return baseVM.anchorGroups.count } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return baseVM.anchorGroups[section].anchors.count //返回主笔的个数 } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { //取出cell let cell = collectionView.dequeueReusableCell(withReuseIdentifier: kNormalCellID, for: indexPath) as! CollectionNormalCell //2 给cell 设置数据 cell.anchor = baseVM.anchorGroups[indexPath.section].anchors[indexPath.item] return cell } //展示头视图数据 func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView { // 取出headerView let headerview = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: kHeaderViewID, for: indexPath) as! CollectionHeaderView //2 给headerView设置数据 headerview.group = baseVM.anchorGroups[indexPath.section] return headerview } }
mit
5c42339eee8a170897b878e74482db41
40.105263
191
0.724456
5.104575
false
false
false
false
octo-technology/AppResizer
Pod/Classes/AppResizer.swift
1
1560
public class AppResizer: NSObject { // MARK: - Shared Instance public static let sharedInstance = AppResizer() // MARK: - Properties private var mainWindow: UIWindow? private var sliderWindow: SliderWindow? // MARK: - Enable public func enable(mainWindow: UIWindow) { self.mainWindow = mainWindow self.addSliderWindow() } // MARK: - Update func updateWindow(horizontalSliderValue: Float, verticalSliderValue: Float) { if let baseFrame = self.sliderWindow?.frame, let window = self.mainWindow { window.frame = CGRect(x: 0, y: 0, width: CGFloat(horizontalSliderValue) * baseFrame.width, height: CGFloat(verticalSliderValue) * baseFrame.height) } } // MARK: - Private func addSliderWindow() { self.sliderWindow = { let newWindow = SliderWindow(frame: UIScreen.main.bounds) newWindow.rootViewController = UIViewController() newWindow.rootViewController?.view.backgroundColor = .clear newWindow.makeKeyAndVisible() return newWindow }() self.sliderWindow?.enableSliders() self.sliderWindow?.sliderValueDidChange = { self.updateWindow(horizontalSliderValue: $0, verticalSliderValue: $1) } self.sliderWindow?.windowDidRotate = { self.updateWindow(horizontalSliderValue: $0, verticalSliderValue: $1) } } }
mit
e52c495f874a9711c56806da51d801b9
25.440678
90
0.601282
5.114754
false
false
false
false
ksco/swift-algorithm-club-cn
Linked List/LinkedList.swift
1
3701
/* Doubly-linked list Most operations on the linked list have complexity O(n). */ public class LinkedListNode<T> { var value: T var next: LinkedListNode? weak var previous: LinkedListNode? public init(value: T) { self.value = value } } public class LinkedList<T> { public typealias Node = LinkedListNode<T> private var head: Node? public var isEmpty: Bool { return head == nil } public var first: Node? { return head } public var last: Node? { if var node = head { while case let next? = node.next { node = next } return node } else { return nil } } public var count: Int { if var node = head { var c = 1 while case let next? = node.next { node = next c += 1 } return c } else { return 0 } } public func nodeAtIndex(index: Int) -> Node? { if index >= 0 { var node = head var i = index while node != nil { if i == 0 { return node } i -= 1 node = node!.next } } return nil } public subscript(index: Int) -> T { let node = nodeAtIndex(index) assert(node != nil) return node!.value } public func append(value: T) { let newNode = Node(value: value) if let lastNode = last { newNode.previous = lastNode lastNode.next = newNode } else { head = newNode } } private func nodesBeforeAndAfter(index: Int) -> (Node?, Node?) { assert(index >= 0) var i = index var next = head var prev: Node? while next != nil && i > 0 { i -= 1 prev = next next = next!.next } assert(i == 0) // if > 0, then specified index was too large return (prev, next) } public func insert(value: T, atIndex index: Int) { let (prev, next) = nodesBeforeAndAfter(index) let newNode = Node(value: value) newNode.previous = prev newNode.next = next prev?.next = newNode next?.previous = newNode if prev == nil { head = newNode } } public func removeAll() { head = nil } public func removeNode(node: Node) -> T { let prev = node.previous let next = node.next if let prev = prev { prev.next = next } else { head = next } next?.previous = prev node.previous = nil node.next = nil return node.value } public func removeLast() -> T { assert(!isEmpty) return removeNode(last!) } public func removeAtIndex(index: Int) -> T { let node = nodeAtIndex(index) assert(node != nil) return removeNode(node!) } } extension LinkedList: CustomStringConvertible { public var description: String { var s = "[" var node = head while node != nil { s += "\(node!.value)" node = node!.next if node != nil { s += ", " } } return s + "]" } } extension LinkedList { public func reverse() { var node = head while let currentNode = node { node = currentNode.next swap(&currentNode.next, &currentNode.previous) head = currentNode } } } extension LinkedList { public func map<U>(transform: T -> U) -> LinkedList<U> { let result = LinkedList<U>() var node = head while node != nil { result.append(transform(node!.value)) node = node!.next } return result } public func filter(predicate: T -> Bool) -> LinkedList<T> { let result = LinkedList<T>() var node = head while node != nil { if predicate(node!.value) { result.append(node!.value) } node = node!.next } return result } }
mit
307cdd3993a11e4be5b2f8a011677d90
18.376963
66
0.554715
3.899895
false
false
false
false
jaynakus/Signals
SwiftSignalKit/Signal_Timing.swift
1
2100
import Foundation public func delay<T, E>(_ timeout: Double, queue: Queue) -> (_ signal: Signal<T, E>) -> Signal<T, E> { return { signal in return Signal<T, E> { subscriber in let disposable = MetaDisposable() let timer = Timer(timeout: timeout, repeat: false, completion: { disposable.set(signal.start(next: { next in subscriber.putNext(next) }, error: { error in subscriber.putError(error) }, completed: { subscriber.putCompletion() })) }, queue: queue) disposable.set(ActionDisposable { timer.invalidate() }) timer.start() return disposable } } } public func timeout<T, E>(_ timeout: Double, queue: Queue, alternate: Signal<T, E>) -> (Signal<T, E>) -> Signal<T, E> { return { signal in return Signal<T, E> { subscriber in let disposable = MetaDisposable() let timer = Timer(timeout: timeout, repeat: false, completion: { disposable.set(alternate.start(next: { next in subscriber.putNext(next) }, error: { error in subscriber.putError(error) }, completed: { subscriber.putCompletion() })) }, queue: queue) disposable.set(signal.start(next: { next in timer.invalidate() subscriber.putNext(next) }, error: { error in timer.invalidate() subscriber.putError(error) }, completed: { timer.invalidate() subscriber.putCompletion() })) timer.start() let disposableSet = DisposableSet() disposableSet.add(ActionDisposable { timer.invalidate() }) disposableSet.add(disposable) return disposableSet } } }
mit
bc213dc0573abfb77b07aa048c1ce1eb
34
119
0.484762
5.210918
false
false
false
false
felixjendrusch/Matryoshka
Matryoshka/OperationFactory.swift
1
827
// Copyright (c) 2015 Felix Jendrusch. All rights reserved. /// A closure-based operation factory. public struct OperationFactory<Input, Operation: OperationType>: OperationFactoryType { private let createClosure: Input -> Operation /// Creates a closure-based operation factory with the given closure. public init(_ create: Input -> Operation) { createClosure = create } public func create(input: Input) -> Operation { return createClosure(input) } } extension OperationFactory { /// Creates a closure-based operation factory that wraps the given operation /// factory. public init<F: OperationFactoryType where F.InputType == Input, F.OperationType == Operation>(_ factory: F) { self.init({ input in return factory.create(input) }) } }
mit
0d3766048e00ea7618fb9469d74b6680
32.08
113
0.681983
4.594444
false
false
false
false
takamashiro/XDYZB
XDYZB/XDYZB/Classes/Main/Model/AnchorModel.swift
1
814
// // AnchorModel.swift // XDYZB // // Created by takamashiro on 2016/9/29. // Copyright © 2016年 com.takamashiro. All rights reserved. // import UIKit class AnchorModel: NSObject { /// 房间ID var room_id : Int = 0 /// 房间图片对应的URLString var vertical_src : String = "" /// 判断是手机直播还是电脑直播 // 0 : 电脑直播 1 : 手机直播 var isVertical : Int = 0 /// 房间名称 var room_name : String = "" /// 主播昵称 var nickname : String = "" /// 观看人数 var online : Int = 0 /// 所在城市 var anchor_city : String = "" init(dict : [String : Any]) { super.init() setValuesForKeys(dict) } override func setValue(_ value: Any?, forUndefinedKey key: String) {} }
mit
f79fe43f54d109e898a8a01f1f814e94
19.542857
73
0.560501
3.613065
false
false
false
false
cherrywoods/swift-meta-serialization
Sources/Supporting/CodingKeys.swift
1
4706
// // CodingKeys.swift // meta-serialization // // Copyright 2018 cherrywoods // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // import Foundation /// A special coding key represents an index in an unkeyed container public struct IndexCodingKey: CodingKey { /// the index public let intValue: Int? /** construct a new IndexCodingKey by passing an index. This initalizer will fail, if intValue is not a valid index, i.e. is smaller than 0 - Paramter intValue: the index. Must be larger or equal than 0, otherwise the initalizer will fail */ public init?(intValue: Int) { guard intValue >= 0 else { return nil } self.intValue = intValue } // MARK: casting to and from strings /// will return the index as string value public var stringValue: String { return "\(intValue!)" } /** constructs a new IndexCodingKey from the given sting, that needs to be base 10 encoded intenger representation. this initalizer used Int(_ description: String) to convert stringValue see Int(_ description: String) for mere details about which strings will succeed */ public init?(stringValue string: String) { guard let index = Int(string) else { return nil } self.init(intValue: index) } } /// An enumeration of all special coding keys meta-serialization will use public enum SpecialCodingKey: StandardCodingKey { /// used by the super(Encoder|Decoder)() methods in MetaKeyed(Encoding|Decoding)Containers case `super` = "super,0" // documentation says, that the int value of a super key is 0 } /** A CodingKey type initalizable with any string or int value. This coding key type is exapressible by a string literal in the form `<stringValue>,<intValue>` where `<stringValue>` it the keys string value and `<intValue>` is the keys int value. You may ommit `,<intValue>`, in which case the coding key will have no int value. You may also ommit `<stringValue>` in which case coding keys stringValue will be "\(intValue)". Therefor valid string literals for a coding key are: * `<stringValue>,<intValue>` * `<stringValue>` * `,<intValue>` If the string literal includes more than one `,` sequence, only the string after the last occurence will be interpreted as int value. If <intValue> isn't convertible to Int, the coding key will be initalizes with the while string literal as stringValue and without an intValue. */ public struct StandardCodingKey: CodingKey, ExpressibleByStringLiteral, Equatable { // MARK: - CodingKey public var stringValue: String public var intValue: Int? public init(stringValue: String, intValue: Int) { self.stringValue = stringValue self.intValue = intValue } public init?(stringValue: String) { self.stringValue = stringValue } /// Sets stringValue to "\(intValue)" public init?(intValue: Int) { self.init(stringValue: "\(intValue)", intValue: intValue) } // MARK: - string literal expressible public typealias StringLiteralType = String public init(stringLiteral string: String) { let parts = string.split(separator: ",") guard let last = parts.last, let intValue = Int(last) else { self.stringValue = string return } self.intValue = intValue if parts.count == 1 { // this means no string value, literal is in form ",<intValue>" self.stringValue = "\(intValue)" } else { // set string value to the whole string before the last komma. self.stringValue = String( string.prefix(string.count - last.count /* do not include the ",": */- 1) ) } } // MARK: - Equatable public static func ==(lhs: StandardCodingKey, rhs: StandardCodingKey) -> Bool { return lhs.stringValue == rhs.stringValue && lhs.intValue == rhs.intValue } }
apache-2.0
98ed91fd232d451c1c82f42a36f12258
31.455172
144
0.643221
4.758342
false
false
false
false
jkolb/midnightbacon
MidnightBacon/Reddit/Request/LinksComments/VoteRequest.swift
1
2513
// // VoteRequest.swift // MidnightBacon // // Copyright (c) 2015 Justin Kolb - http://franticapparatus.net // // 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 ModestProposal import FranticApparatus import Common class VoteRequest : APIRequest { let prototype: NSURLRequest let id: String let direction: VoteDirection let apiType: APIType convenience init(prototype: NSURLRequest, link: Link, direction: VoteDirection, apiType: APIType = .JSON) { self.init(prototype: prototype, id: link.name, direction: direction, apiType: apiType) } init(prototype: NSURLRequest, id: String, direction: VoteDirection, apiType: APIType = .JSON) { self.prototype = prototype self.id = id self.direction = direction self.apiType = apiType } typealias ResponseType = Bool func parse(response: URLResponse) throws -> Bool { return try redditJSONMapper(response) { (object) -> Bool in return true } } func build() -> NSMutableURLRequest { var parameters = [String:String](minimumCapacity: 3) parameters["id"] = id parameters["dir"] = direction.stringValue parameters["api_type"] = apiType.rawValue return prototype.POST(path: "/api/vote", parameters: parameters) } var requiresModhash : Bool { return true } var scope : OAuthScope? { return .Vote } }
mit
a94ba22d24911860a697943d6d996801
34.394366
111
0.694787
4.627993
false
false
false
false
eure/RealmIncrementalStore
RealmIncrementalStore/RealmIncrementalStore.swift
1
12663
// // RealmIncrementalStore.swift // RealmIncrementalStore // // Copyright © 2016 eureka, Inc., John Rommel Estropia // // 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 CoreData import Realm import Realm.Private // MARK: - RealmIncrementalStore @objc(RealmIncrementalStore) public final class RealmIncrementalStore: NSIncrementalStore { public class var storeType: String { return NSStringFromClass(self) } internal private(set) var rootRealm: RLMRealm! // MARK: NSObject public override class func initialize() { NSPersistentStoreCoordinator.registerStoreClass(self, forStoreType:self.storeType) } // MARK: NSIncrementalStore public override func loadMetadata() throws { guard let coordinator = self.persistentStoreCoordinator else { throw RealmIncrementalStoreError.InvalidState } guard let fileURL = self.URL else { throw RealmIncrementalStoreError.PersistentStoreURLMissing } guard fileURL.fileURL else { throw RealmIncrementalStoreError.PersistentStoreURLInvalid } let model = coordinator.managedObjectModel let schema = self.createBackingClassesForModel(model) let rootRealm = try RLMRealm( path: fileURL.path!, key: nil, readOnly: false, inMemory: false, dynamic: false, schema: schema ) let versionHashes: [String: NSData] let storeIdentifier: String let sdkVersion = RealmIncrementalStoreMetadata.currentSDKVersion if let metadataObject = RealmIncrementalStoreMetadata(inRealm: rootRealm, forPrimaryKey: sdkVersion) { guard let plist = try NSPropertyListSerialization.propertyListWithData(metadataObject.versionHashes, options: .Immutable, format: nil) as? [String: NSData] else { throw RealmIncrementalStoreError.PersistentStoreCorrupted } versionHashes = plist storeIdentifier = metadataObject.storeIdentifier } else { versionHashes = model.entityVersionHashesByName storeIdentifier = RealmIncrementalStore.identifierForNewStoreAtURL(fileURL) as! String let plistData = try! NSPropertyListSerialization.dataWithPropertyList( versionHashes, format: .BinaryFormat_v1_0, options: 0 ) rootRealm.beginWriteTransaction() let metadataObject = RealmIncrementalStoreMetadata.createInRealm( rootRealm, withValue: [ RealmIncrementalStoreMetadata.primaryKey()!: sdkVersion ] ) metadataObject.storeIdentifier = storeIdentifier metadataObject.versionHashes = plistData rootRealm.addOrUpdateObject(metadataObject) try rootRealm.commitWriteTransaction() } let metadata: [String: AnyObject] = [ NSStoreUUIDKey: storeIdentifier, NSStoreTypeKey: RealmIncrementalStore.storeType, NSStoreModelVersionHashesKey: versionHashes ] self.rootRealm = rootRealm self.metadata = metadata } public override func executeRequest(request: NSPersistentStoreRequest, withContext context: NSManagedObjectContext?) throws -> AnyObject { switch (request.requestType, request) { case (.FetchRequestType, let request as NSFetchRequest): return try self.executeFetchRequest(request, inContext: context) case (.SaveRequestType, let request as NSSaveChangesRequest): return try self.executeSaveRequest(request, inContext: context) // TODO: // case (.BatchUpdateRequestType, _): // fatalError() // case (.BatchDeleteRequestType, _): // fatalError() default: throw RealmIncrementalStoreError.StoreRequestUnsupported } } public override func newValuesForObjectWithID(objectID: NSManagedObjectID, withContext context: NSManagedObjectContext) throws -> NSIncrementalStoreNode { let realm = self.rootRealm! let backingClass = objectID.entity.realmBackingClass let primaryKey = self.referenceObjectForObjectID(objectID) as! String guard let realmObject = backingClass.init(inRealm: realm, forPrimaryKey: primaryKey) else { throw RealmIncrementalStoreError.ObjectNotFound } let keyValues = realmObject.dictionaryWithValuesForKeys( objectID.entity.realmObjectSchema.properties .filter { $0.objectClassName == nil && realmObject[$0.name] != nil } .map { $0.getterName } ) return NSIncrementalStoreNode( objectID: objectID, withValues: keyValues, version: realmObject.realmObjectVersion ) } public override func newValueForRelationship(relationship: NSRelationshipDescription, forObjectWithID objectID: NSManagedObjectID, withContext context: NSManagedObjectContext?) throws -> AnyObject { guard let realmObject = objectID.realmObject(), let destinationEntity = relationship.destinationEntity else { return NSNull() } if relationship.toMany { if let relatedObjects = realmObject[relationship.name] as? RLMArray { return relatedObjects.flatMap { return self.newObjectIDForEntity( destinationEntity, referenceObject: $0.realmResourceID ) } } } else { if let relatedObject = realmObject[relationship.name] as? RLMObject { return self.newObjectIDForEntity( destinationEntity, referenceObject: relatedObject.realmResourceID ) } } return NSNull() } public override func obtainPermanentIDsForObjects(array: [NSManagedObject]) throws -> [NSManagedObjectID] { // TODO: cache? return array.map { guard $0.objectID.temporaryID else { return $0.objectID } return self.newObjectIDForEntity($0.entity, referenceObject: NSUUID().UUIDString) } } // public override func managedObjectContextDidRegisterObjectsWithIDs(objectIDs: [NSManagedObjectID]) { // // fatalError() // } // // public override func managedObjectContextDidUnregisterObjectsWithIDs(objectIDs: [NSManagedObjectID]) { // // fatalError() // } // MARK: Private private let objectIDCache = NSCache() private func createBackingClassesForModel(model: NSManagedObjectModel) -> RLMSchema { let metadataSchema = [RLMObjectSchema(forObjectClass: RealmIncrementalStoreMetadata.self)] let entitiesSchema = model.entities.loadObjectSchemas() let schema = RLMSchema() schema.objectSchema = metadataSchema + entitiesSchema return schema } private func executeFetchRequest(request: NSFetchRequest, inContext context: NSManagedObjectContext?) throws -> AnyObject { let entity = request.entity! let backingClass = entity.realmBackingClass let realm = self.rootRealm! var results = backingClass.objectsInRealm( realm, withPredicate: request.predicate?.realmPredicate() ) if let sortDescriptors = request.sortDescriptors { results = results.sortedResultsUsingDescriptors( sortDescriptors.map { RLMSortDescriptor(property: $0.key!, ascending: $0.ascending) } ) } switch request.resultType { case NSFetchRequestResultType.ManagedObjectResultType: return results.flatMap { object -> AnyObject? in let resourceID = object.realmResourceID let objectID = self.newObjectIDForEntity(entity, referenceObject: resourceID) return context?.objectWithID(objectID) } case NSFetchRequestResultType.ManagedObjectIDResultType: return results.flatMap { object -> AnyObject? in let resourceID = object.realmResourceID return self.newObjectIDForEntity(entity, referenceObject: resourceID) } case NSFetchRequestResultType.DictionaryResultType: return results.flatMap { object -> AnyObject? in let propertiesToFetch = request.propertiesToFetch ?? [] let keyValues = object.dictionaryWithValuesForKeys( propertiesToFetch.flatMap { switch $0 { case let string as String: return string case let property as NSPropertyDescription: return property.name default: return nil } } ) return keyValues } case NSFetchRequestResultType.CountResultType: return results.count default: fatalError() } } private func executeSaveRequest(request: NSSaveChangesRequest, inContext context: NSManagedObjectContext?) throws -> AnyObject { let realm = self.rootRealm! realm.beginWriteTransaction() try request.insertedObjects?.forEach { let backingClass = $0.entity.realmBackingClass let realmObject = backingClass.createBackingObjectInRealm( realm, referenceObject: self.referenceObjectForObjectID($0.objectID) ) try realmObject.setValuesFromManagedObject($0) realm.addOrUpdateObject(realmObject) } try request.updatedObjects?.forEach { let backingClass = $0.entity.realmBackingClass let realmObject = backingClass.init( inRealm: realm, forPrimaryKey: self.referenceObjectForObjectID($0.objectID) ) try realmObject?.setValuesFromManagedObject($0) } request.deletedObjects?.forEach { let backingClass = $0.entity.realmBackingClass let realmObject = backingClass.init( inRealm: realm, forPrimaryKey: self.referenceObjectForObjectID($0.objectID) ) _ = realmObject.flatMap(realm.deleteObject) } try realm.commitWriteTransaction() return [] } }
mit
47ff73fe7d8891465c8d69df0435288d
35.074074
202
0.594772
6.0468
false
false
false
false
segura2010/masmovilusage-ios
MasMovilUsage/LocalStorageManager.swift
1
2520
// // LocalStorageManager.swift // MasMovilUsage // // Created by Alberto on 12/10/16. // Copyright © 2016 Alberto. All rights reserved. // import Foundation class LocalStorageManager { static let sharedInstance = LocalStorageManager() let DEFAULTS_NAME = "group.masmovilusage.segura" func getUsername() -> String { let defaults = UserDefaults(suiteName: DEFAULTS_NAME) if let username = defaults?.string(forKey: "username") { return username } else{ return "" } } func getPassword() -> String { let defaults = UserDefaults(suiteName: DEFAULTS_NAME) if let password = defaults?.string(forKey: "password") { return password } else{ return "" } } func getToken() -> String { let defaults = UserDefaults(suiteName: DEFAULTS_NAME) if let token = defaults?.string(forKey: "token") { return token } else{ return "" } } func getDataLimit() -> Int { let defaults = UserDefaults(suiteName: DEFAULTS_NAME) if let d = defaults?.integer(forKey: "datalimit") { return d } else{ return 0 } } func saveDataLimit(_ data:Int) { let defaults = UserDefaults(suiteName: DEFAULTS_NAME) defaults?.setValue(data, forKey: "datalimit") defaults?.synchronize() } func getConsume() -> [String:AnyObject] { let defaults = UserDefaults(suiteName: DEFAULTS_NAME) if let d = defaults?.dictionary(forKey: "consume") { return d as [String : AnyObject] } else{ return [String : AnyObject]() } } func saveConsume(_ data:[String:AnyObject]) { let defaults = UserDefaults(suiteName: DEFAULTS_NAME) defaults?.setValue(data, forKey: "consume") defaults?.synchronize() } func saveUser(_ username:String, password:String, token:String) { let defaults = UserDefaults(suiteName: DEFAULTS_NAME) defaults?.setValue(username, forKey: "username") defaults?.setValue(password, forKey: "password") defaults?.setValue(token, forKey: "token") defaults?.synchronize() } }
gpl-2.0
1a7396420b886d200b44ffbaf1acaa7f
22.110092
67
0.534736
4.82567
false
false
false
false
DonMag/SWDynamicCenter
SWDynamicCenter/ViewController.swift
1
4028
// // ViewController.swift // SWDynamicCenter // // Created by DonMag on 9/14/16. // Copyright © 2016 DonMag. All rights reserved. // import UIKit class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { @IBOutlet weak var mainContainerView: UIView! @IBOutlet weak var contentContainerView: UIView! @IBOutlet weak var theTable: UITableView! @IBOutlet weak var buttonsContainerView: UIView! @IBOutlet weak var tableHeight: NSLayoutConstraint! var nRows = 8 override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. self.theTable.hidden = true #if DMDEBUG self.view.backgroundColor = UIColor.orangeColor() self.mainContainerView.backgroundColor = UIColor.blueColor() self.contentContainerView.backgroundColor = UIColor.cyanColor() self.buttonsContainerView.backgroundColor = UIColor.yellowColor() #else self.view.backgroundColor = UIColor.darkGrayColor() self.mainContainerView.backgroundColor = UIColor.clearColor() self.contentContainerView.backgroundColor = UIColor.clearColor() self.buttonsContainerView.backgroundColor = UIColor.clearColor() #endif let headerView = UIView(frame: CGRectMake(0, 0, 100, 40)) //was 40 headerView.backgroundColor = UIColor.redColor() let label = UILabel() label.text = "Tue, Sep 20 - 1 of 1 Events" label.textAlignment = .Center label.frame = headerView.frame label.textColor = UIColor.whiteColor().colorWithAlphaComponent(0.7) label.font = label.font.fontWithSize(14) headerView.addSubview(label) theTable.tableHeaderView = headerView label.translatesAutoresizingMaskIntoConstraints = false let leadingConstraint = NSLayoutConstraint(item: label, attribute: .Leading, relatedBy: .Equal, toItem: headerView, attribute: .Leading, multiplier: 1, constant: 0) let trailingConstraint = NSLayoutConstraint(item: label, attribute: .Trailing, relatedBy: .Equal, toItem: headerView, attribute: .Trailing, multiplier: 1, constant: 0) let topConstraint = NSLayoutConstraint(item: label, attribute: .Top, relatedBy: .Equal, toItem: headerView, attribute: .Top, multiplier: 1, constant: 0) let bottomConstraint = NSLayoutConstraint(item: label, attribute: .Bottom, relatedBy: .Equal, toItem: headerView, attribute: .Bottom, multiplier: 1, constant: 0) headerView.addConstraints([leadingConstraint, trailingConstraint, topConstraint, bottomConstraint]) } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) self.theTable.tableHeaderView?.frame.size.width = self.theTable.frame.size.width self.adjustTableHeight() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func adjustTableHeight() -> Void { dispatch_async(dispatch_get_main_queue(), { () -> Void in var h = CGFloat(44 * self.nRows) if let hh = self.theTable.tableHeaderView?.frame.size.height { h += hh } self.tableHeight.constant = h self.theTable.hidden = false }) } @IBAction func doGrow(sender: AnyObject) { nRows += 1 theTable.reloadData() self.adjustTableHeight() } @IBAction func doShrink(sender: AnyObject) { nRows -= 1 theTable.reloadData() self.adjustTableHeight() } func numberOfSectionsInTableView(tableView: UITableView) -> Int { // #warning Incomplete implementation, return the number of sections return 1 } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete implementation, return the number of rows return nRows } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("MyCell", forIndexPath: indexPath) // Configure the cell... cell.textLabel?.text = "Row \(indexPath.row)" return cell } }
mit
d38167c9f936ef5fce1ffa1e1c457e11
25.149351
169
0.73628
4.230042
false
false
false
false
kevinhankens/runalysis
Runalysis/WeekHeader.swift
1
2123
// // WeekHeader.swift // Runalysis // // Created by Kevin Hankens on 7/18/14. // Copyright (c) 2014 Kevin Hankens. All rights reserved. // import Foundation import UIKit /*! * @class WeekHeader * * Creates a view of the main header with the currently viewed week's date. */ class WeekHeader: UIView { // The date this week begins with. var beginDate: NSDate = NSDate() // The date this week ends with. var endDate: NSDate = NSDate() // The label containing the date. var dateLabel: UILabel? /*! * Factory method to create a WeekHeader. * * @param CGFloat cellHeight * @param CGFloat cellWidth * @param NSDate beginDate * @param NSDate endDate * * @return WeekHeader */ class func createHeader(cellHeight: CGFloat, cellWidth: CGFloat, beginDate: NSDate, endDate: NSDate)->WeekHeader { let loc = CGPointMake(0, 20) let header = WeekHeader(frame: CGRectMake(loc.x, loc.y, cellWidth, cellHeight)) let headerDate = UILabel(frame: CGRect(x: 0, y: 0, width: header.bounds.width, height: 50.0)) headerDate.textAlignment = NSTextAlignment.Center headerDate.textColor = UIColor.whiteColor() header.dateLabel = headerDate header.updateDate(beginDate, endDate: endDate) header.addSubview(headerDate) return header } /*! * Updates the header to contain a new begin and end date. * * This also updates the label accordingly. * * @param NSDate beginDate * @param NSDate endDate * * @return void */ func updateDate(beginDate: NSDate, endDate: NSDate) { self.beginDate = beginDate self.endDate = endDate self.updateLabel() } /*! * Updates the label containing the dates. * * @return void */ func updateLabel() { let v = self.dateLabel! let format = NSDateFormatter() format.dateFormat = "MMM d" v.text = "< \(format.stringFromDate(self.beginDate)) - \(format.stringFromDate(self.endDate)) >" } }
mit
32b802aca31a88be3937773bd5078165
25.5375
104
0.619407
4.27163
false
false
false
false
prolificinteractive/Yoshi
Yoshi/Yoshi/YoshiConfigurationManager.swift
1
5195
// // DebugConfigurationManager.swift // Yoshi // // Created by Michael Campbell on 12/22/15. // Copyright © 2015 Prolific Interactive. All rights reserved. // /// The configuration manager for the debug menu. final class YoshiConfigurationManager { /// The default instance. static let sharedInstance = YoshiConfigurationManager() private var yoshiMenuItems = [YoshiGenericMenu]() private var invocations: [YoshiInvocation]? private var presentingWindow: UIWindow? private weak var debugViewController: DebugViewController? /** Sets the debug options to use for presenting the debug menu. - parameter menuItems: The menu items for presentation. - parameter invocations: The invocation types. */ func setupDebugMenuOptions(_ menuItems: [YoshiGenericMenu], invocations: [YoshiInvocation]) { yoshiMenuItems = menuItems self.invocations = invocations } /** Allows client application to indicate it has restarted. Clears inertnal state. */ func restart() { presentingWindow = nil debugViewController = nil guard let invocations = invocations else { return } setupDebugMenuOptions(yoshiMenuItems, invocations: invocations) } /// Helper function to indicate if the given invocation should show Yoshi. /// /// - parameter invocation: Invocation method called. /// /// - returns: `true` if Yoshi should appear. `false` if not. func shouldShow(_ invocation: YoshiInvocation) -> Bool { guard let invocations = invocations else { return false } if invocations.contains(.all) { return true } return invocations.contains(invocation) } /** Invokes the display of the debug menu. */ func show() { guard presentingWindow == nil else { return } let window = UIWindow(frame: UIScreen.main.bounds) window.windowLevel = .normal // Use a dummy view controller with clear background. // This way, we can make the actual view controller we want to present a form sheet on the iPad. let rootViewController = UIViewController() rootViewController.view.backgroundColor = UIColor.clear window.rootViewController = rootViewController window.makeKeyAndVisible() presentingWindow = window // iOS doesn't like when modals are presented right away after a window's been made key and visible. // We need to delay presenting the debug controller a bit to suppress the warning. DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + Double(Int64(0 * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC)) { self.presentDebugViewController() } } /// Return a navigation controller presenting the debug view controller. /// /// - Returns: Debug navigation controller func debugNavigationController() -> UINavigationController { let navigationController = UINavigationController() let debugViewController = DebugViewController(options: yoshiMenuItems, isRootYoshiMenu: true, completion: { _ in navigationController.dismiss(animated: true) }) self.debugViewController = debugViewController navigationController.setViewControllers([debugViewController], animated: false) return navigationController } /** Dismisses the debug view controller, if possible. - parameter action: The action to take upon completion. */ func dismiss(_ action: VoidCompletionBlock? = nil) { if let completionHandler = debugViewController?.completionHandler { completionHandler(action) } presentingWindow = nil } private func presentDebugViewController() { if let rootViewController = presentingWindow?.rootViewController { let navigationController = UINavigationController() let debugViewController = DebugViewController(options: yoshiMenuItems, isRootYoshiMenu: true, completion: { [weak self] completionBlock in rootViewController .dismiss(animated: true, completion: { () -> Void in self?.presentingWindow = nil completionBlock?() }) }) navigationController.modalPresentationStyle = .formSheet navigationController.setViewControllers([debugViewController], animated: false) rootViewController.present(navigationController, animated: true, completion: nil) self.debugViewController = debugViewController } } }
mit
3e8c3e8e9a3731419be725ac5cf62abe
35.577465
120
0.603966
6.067757
false
false
false
false
bradleypj823/Swift-GithubToGo
Swift-GithubToGo/RepoSearchViewController.swift
1
2481
// // RepoSearchViewController.swift // Swift-GithubToGo // // Created by Bradley Johnson on 6/8/14. // Copyright (c) 2014 Bradley Johnson. All rights reserved. // import UIKit class RepoSearchViewController: UIViewController, UITableViewDataSource { var networkController : NetworkController? var searchRepos = Repo[]() @IBOutlet var tableView : UITableView = nil init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) // Custom initialization } init(coder aDecoder: NSCoder!) { super.init(coder: aDecoder) } override func viewDidLoad() { super.viewDidLoad() var appDelegate = UIApplication.sharedApplication().delegate as AppDelegate self.networkController = appDelegate.networkController // Do any additional setup after loading the view. } func tableView(tableView: UITableView!, numberOfRowsInSection section: Int) -> Int { return self.searchRepos.count } func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell! { let cell : RepoSearchTVCell = tableView.dequeueReusableCellWithIdentifier("repoSearchCell", forIndexPath: indexPath) as RepoSearchTVCell var repo : Repo = self.searchRepos[indexPath.row] cell.titleLabel.text = repo.name cell.descriptionLabel.text = repo.repoDescription return cell } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func searchForRepo(repoSearch : String) { self.networkController!.searchReposWithString(repoSearch) { (repos: Repo[]) in self.searchRepos = repos NSOperationQueue.mainQueue().addOperationWithBlock() { () in self.tableView.reloadData() } } } /* // #pragma mark - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue?, sender: AnyObject?) { // Get the new view controller using [segue destinationViewController]. // Pass the selected object to the new view controller. } */ }
mit
6c9c0c202b6f428fdaef2f9c788390b7
30.0125
144
0.653366
5.464758
false
false
false
false
ThePacielloGroup/CCA-OSX
Colour Contrast Analyser/CCALuminosityLevelField.swift
1
1211
// // NSLuminosityLevelField.swift // Colour Contrast Analyser // // Created by Cédric Trévisan on 02/02/2015. // Copyright (c) 2015 Cédric Trévisan. All rights reserved. // import Cocoa class CCALuminosityLevelField: NSTextField { @IBOutlet weak var statusImage:NSImageView! var currentStatus:Bool = false var level:String? var pass:Bool? { didSet { if pass == true { setPass() } else { setFail() } } } override func draw(_ dirtyRect: NSRect) { super.draw(dirtyRect) // Drawing code here. } func setFail() { if (currentStatus == true) { self.stringValue = NSLocalizedString("fail", comment:"Fail") + " " + level! self.statusImage.image = NSImage(named: NSImage.Name(rawValue: "No")) currentStatus = false; } } func setPass() { if (currentStatus == false) { self.stringValue = NSLocalizedString("pass", comment:"Pass") + " " + level! self.statusImage.image = NSImage(named: NSImage.Name(rawValue: "Yes")) currentStatus = true; } } }
gpl-3.0
d98631a39309fb98d9bd2d884fe6992b
25.23913
87
0.554267
4.280142
false
false
false
false
rajeshmud/CLChart
CLApp/CLCharts/CLCharts/Charts/Chart.swift
1
2387
// // Chart.swift // CLCharts // // Created by Rajesh Mudaliyar on 11/09/15. // Copyright © 2015 Rajesh Mudaliyar. All rights reserved. // import UIKit public class CLSettings { public var leading: CGFloat = 0 public var top: CGFloat = 0 public var trailing: CGFloat = 0 public var bottom: CGFloat = 0 public var labelsSpacing: CGFloat = 5 public var labelsToAxisSpacingX: CGFloat = 5 public var labelsToAxisSpacingY: CGFloat = 5 public var spacingBetweenAxesX: CGFloat = 15 public var spacingBetweenAxesY: CGFloat = 15 public var axisTitleLabelsToLabelsSpacing: CGFloat = 5 public var axisStrokeWidth: CGFloat = 1.0 public init() {} } public class Chart { public let view: ChartBaseView private let layers: [CLLayer] convenience public init(frame: CGRect, layers: [CLLayer]) { self.init(view: ChartBaseView(frame: frame), layers: layers) } public init(view: ChartBaseView, layers: [CLLayer]) { self.layers = layers self.view = view self.view.chart = self for layer in self.layers { layer.chartInitialized(chart: self) } self.view.setNeedsDisplay() } public required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } public func addSubview(view: UIView) { self.view.addSubview(view) } public var frame: CGRect { return self.view.frame } public var bounds: CGRect { return self.view.bounds } public func clearView() { self.view.removeFromSuperview() } private func drawRect(rect: CGRect) { let context = UIGraphicsGetCurrentContext() for layer in self.layers { layer.viewDrawing(context: context!, chart: self) } } } public class ChartBaseView: UIView { weak var chart: Chart? override public init(frame: CGRect) { super.init(frame: frame) self.sharedInit() } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.sharedInit() } func sharedInit() { self.backgroundColor = UIColor.clearColor() } override public func drawRect(rect: CGRect) { self.chart?.drawRect(rect) } }
mit
94e4c31d0b70ac18059be2cae0905ae1
22.87
68
0.617351
4.369963
false
false
false
false
dabing1022/AlgorithmRocks
LintCodeSwift/Playground/LintCode.playground/Pages/001 Fizz Buzz.xcplaygroundpage/Contents.swift
1
899
//: [Previous](@previous) //: ## [Fizz Buzz](http://www.lintcode.com/zh-cn/problem/fizz-buzz/) /*: 给你一个整数n. 从 1 到 n 按照下面的规则打印每个数: 如果这个数被3整除,打印fizz. 如果这个数被5整除,打印buzz. 如果这个数能同时被3和5整除,打印fizz buzz. 样例 比如 n = 15, 返回一个字符串数组: ["1", "2", "fizz", "4", "buzz", "fizz", "7", "8", "fizz", "buzz", "11", "fizz", "13", "14", "fizz buzz"] */ func fizzBuzz(number: Int) -> [String] { var result = [String]() for i in 1...number { if (i % 15 == 0) { result.append("fizz buzz") } else if (i % 5 == 0) { result.append("buzz") } else if (i % 3 == 0) { result.append("fizz") } else { result.append(String(i)) } } return result } fizzBuzz(15) //: [Next](@next)
mit
7221fbb095b9cf8d0a8c0b4bf08314ba
19.972222
104
0.504636
2.686833
false
false
false
false
bkase/BrightFutures
BrightFutures/Future.swift
1
12761
// The MIT License (MIT) // // Copyright (c) 2014 Thomas Visser // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. import Foundation public func future<T>(context c: ExecutionContext = Queue.global, task: (inout NSError?) -> T?) -> Future<T> { let promise = Promise<T>(); c.execute { var error: NSError? let result = task(&error) if let certainError = error { promise.error(certainError) } else if let certainResult = result { promise.success(certainResult) } } return promise.future } public func future<T>(context c: ExecutionContext = Queue.global, task: @autoclosure () -> T?) -> Future<T> { return future(context: c) { error in return task() } } public let NoSuchElementError = "NoSuchElementError" public class Future<T> { typealias CallbackInternal = (future: Future<T>) -> () typealias CompletionCallback = (result: TaskResult<T>) -> () typealias SuccessCallback = (T) -> () public typealias FailureCallback = (NSError) -> () let q = Queue() var result: TaskResult<T>? = nil var callbacks: [CallbackInternal] = Array<CallbackInternal>() let defaultCallbackExecutionContext = Queue() public func succeeded(fn: (T -> ())? = nil) -> Bool { if let res = self.result { return res.succeeded(fn) } return false } public func failed(fn: (NSError -> ())? = nil) -> Bool { if let res = self.result { return res.failed(fn) } return false } public func completed(success: (T->())? = nil, failure: (NSError->())? = nil) -> Bool{ if let res = self.result { res.handle(success: success, failure: failure) return true } return false } public class func succeeded(value: T) -> Future<T> { let res = Future<T>(); res.result = TaskResult(value) return res } public class func failed(error: NSError) -> Future<T> { let res = Future<T>(); res.result = TaskResult(error) return res } public class func completeAfter(delay: NSTimeInterval, withValue value: T) -> Future<T> { let res = Future<T>() dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(delay * NSTimeInterval(NSEC_PER_SEC))), Queue.global.queue) { res.success(value) } return res } /** * Returns a Future that will never succeed */ public class func never() -> Future<T> { return Future<T>() } func complete(result: TaskResult<T>) { let succeeded = tryComplete(result) assert(succeeded) } func tryComplete(result: TaskResult<T>) -> Bool { switch result { case .Success(let val): return self.trySuccess(val.value) case .Failure(let err): return self.tryError(err) } } func success(value: T) { let succeeded = self.trySuccess(value) assert(succeeded) } func trySuccess(value: T) -> Bool { return q.sync { if self.result != nil { return false; } self.result = TaskResult(value) self.runCallbacks() return true; }; } func error(error: NSError) { let succeeded = self.tryError(error) assert(succeeded) } func tryError(error: NSError) -> Bool { return q.sync { if self.result != nil { return false; } self.result = TaskResult(error) self.runCallbacks() return true; }; } public func forced() -> TaskResult<T> { return forced(Double.infinity)! } public func forced(time: NSTimeInterval) -> TaskResult<T>? { if let certainResult = self.result { return certainResult } else { let sema = dispatch_semaphore_create(0) var res: TaskResult<T>? = nil self.onComplete { res = $0 dispatch_semaphore_signal(sema) } var timeout: dispatch_time_t if time.isFinite { timeout = dispatch_time(DISPATCH_TIME_NOW, Int64(time * NSTimeInterval(NSEC_PER_SEC))) } else { timeout = DISPATCH_TIME_FOREVER } dispatch_semaphore_wait(sema, timeout) return res } } public func onComplete(callback: CompletionCallback) -> Future<T> { return self.onComplete(context: self.defaultCallbackExecutionContext, callback: callback) } public func onComplete(context c: ExecutionContext, callback: CompletionCallback) -> Future<T> { q.sync { let wrappedCallback : Future<T> -> () = { future in if let realRes = self.result { c.execute { callback(result: realRes) } } } if self.result == nil { self.callbacks.append(wrappedCallback) } else { wrappedCallback(self) } } return self } public func flatMap<U>(f: T -> Future<U>) -> Future<U> { return self.flatMap(context: self.defaultCallbackExecutionContext, f) } public func flatMap<U>(context c: ExecutionContext, f: T -> Future<U>) -> Future<U> { let p: Promise<U> = Promise() self.onComplete(context: c) { res in switch (res) { case .Failure(let e): p.error(e) case .Success(let v): p.completeWith(f(v.value)) } } return p.future } public func map<U>(f: (T, inout NSError?) -> U?) -> Future<U> { return self.map(context: self.defaultCallbackExecutionContext, f) } public func map<U>(context c: ExecutionContext, f: (T, inout NSError?) -> U?) -> Future<U> { let p = Promise<U>() self.onComplete(context: c, callback: { result in switch result { case .Success(let v): var err: NSError? = nil let res = f(v.value, &err) if let e = err { p.error(e) } else { p.success(res!) } break; case .Failure(let e): p.error(e) break; } }) return p.future } public func andThen(callback: TaskResult<T> -> ()) -> Future<T> { return self.andThen(context: self.defaultCallbackExecutionContext, callback: callback) } public func andThen(context c: ExecutionContext, callback: TaskResult<T> -> ()) -> Future<T> { let p = Promise<T>() self.onComplete(context: c) { result in callback(result) p.completeWith(self) } return p.future } public func onSuccess(callback: SuccessCallback) -> Future<T> { return self.onSuccess(context: self.defaultCallbackExecutionContext, callback) } public func onSuccess(context c: ExecutionContext, callback: SuccessCallback) -> Future<T> { self.onComplete(context: c) { result in switch result { case .Success(let val): callback(val.value) default: break } } return self } public func onFailure(callback: FailureCallback) -> Future<T> { return self.onFailure(context: self.defaultCallbackExecutionContext, callback) } public func onFailure(context c: ExecutionContext, callback: FailureCallback) -> Future<T> { self.onComplete(context: c) { result in switch result { case .Failure(let err): callback(err) default: break } } return self } public func recover(task: (NSError) -> T) -> Future<T> { return self.recover(context: self.defaultCallbackExecutionContext, task) } public func recover(context c: ExecutionContext, task: (NSError) -> T) -> Future<T> { return self.recoverWith(context: c) { error -> Future<T> in return Future.succeeded(task(error)) } } public func recoverWith(task: (NSError) -> Future<T>) -> Future<T> { return self.recoverWith(context: self.defaultCallbackExecutionContext, task: task) } public func recoverWith(context c: ExecutionContext, task: (NSError) -> Future<T>) -> Future<T> { let p = Promise<T>() self.onComplete(context: c) { result -> () in switch result { case .Failure(let err): p.completeWith(task(err)) case .Success(let val): p.completeWith(self) } } return p.future; } public func zip<U>(that: Future<U>) -> Future<(T,U)> { return self.flatMap { thisVal in return that.map { thatVal, _ in return (thisVal, thatVal) } } } public func filter(p: T -> Bool) -> Future<T> { let promise = Promise<T>() self.onComplete { result in switch result { case .Success(let val): if p(val.value) { promise.completeWith(self) } else { promise.error(NSError(domain: NoSuchElementError, code: 0, userInfo: nil)) } break case .Failure(let err): promise.error(err) } } return promise.future } private func runCallbacks() { q.async { for callback in self.callbacks { callback(future: self) } self.callbacks.removeAll() } } } public final class TaskResultValueWrapper<T> { public let value: T init(_ value: T) { self.value = value } } func ==<T: Equatable>(lhs: TaskResultValueWrapper<T>, rhs: T) -> Bool { return lhs.value == rhs } public enum TaskResult<T> { case Success(TaskResultValueWrapper<T>) case Failure(NSError) init(_ value: T) { self = .Success(TaskResultValueWrapper(value)) } init(_ error: NSError) { self = .Failure(error) } public func failed(fn: (NSError -> ())? = nil) -> Bool { switch self { case .Success(_): return false case .Failure(let err): if let fnn = fn { fnn(err) } return true } } public func succeeded(fn: (T -> ())? = nil) -> Bool { switch self { case .Success(let val): if let fnn = fn { fnn(val.value) } return true case .Failure(let err): return false } } public func handle(success: (T->())? = nil, failure: (NSError->())? = nil) { switch self { case .Success(let val): if let successCb = success { successCb(val.value) } case .Failure(let err): if let failureCb = failure { failureCb(err) } } } }
mit
f0acb091f98d716e4e68eef6ebbd8d1a
28.002273
123
0.53256
4.513972
false
false
false
false
mmoaay/MBNetwork
Example/Bamboots/Error/WeatherError.swift
1
763
// // WeatherError.swift // Bamboots // // Created by ZhengYidong on 03/01/2017. // Copyright © 2017 CocoaPods. All rights reserved. // import Foundation import Bamboots struct WeatherError: JSONErrorable { var rootPath: String? = "data" var successCodes: [String] = ["200"] var code: String? var message: String? enum CodingKeys : String, CodingKey { case code = "location" case message = "lacation" } } struct WeatherInformError: JSONErrorable { var rootPath: String? = "data" var successCodes: [String] = ["Toronto, Canada"] var code: String? var message: String? enum CodingKeys : String, CodingKey { case code = "location" case message = "lacation" } }
mit
19a127f9eee1c667643cf4bcd7add33c
19.594595
52
0.627297
3.791045
false
false
false
false
asm-products/giraff-ios
Fun/FunSession.swift
1
4887
import Foundation private let _sharedSession = FunSession() private let authentication_token_key = "authentication_token" class FunSession { class var sharedSession: FunSession { return _sharedSession } let apiUrl:String init() { var plist = NSBundle.mainBundle().pathForResource("configuration", ofType: "plist") var config = NSDictionary(contentsOfFile: plist!)! apiUrl = config["FUN_API_URL"] as! String } func signIn(email:String, password:String, callback: () -> Void) { request("POST", url: "/sessions", body:["email":email, "password":password]) {(data:NSData) in println("CALLED") let json = NSJSONSerialization.JSONObjectWithData(data, options: nil, error: nil) as! NSDictionary println(json) NSUserDefaults.standardUserDefaults().setObject(json[authentication_token_key], forKey: authentication_token_key) NSUserDefaults.standardUserDefaults().synchronize() callback() } } func fbSignIn(email:String, authToken:String, callback: () -> Void) { request("POST", url: "/fbcreate", body:["email":email, "fb_auth_token":authToken]) {(data:NSData) in let json = NSJSONSerialization.JSONObjectWithData(data, options: nil, error: nil) as! NSDictionary NSUserDefaults.standardUserDefaults().setObject(json[authentication_token_key], forKey: authentication_token_key) NSUserDefaults.standardUserDefaults().synchronize() callback() } } func fetchImages(callback: (NSArray) -> Void) { get("/images") {(json:NSDictionary) -> Void in let images = json["images"] as! NSArray callback(images) } } func fetchFaves(currentFavePage:Int,callback: (NSArray) -> Void) { get("/images/favorites?page=\(currentFavePage)") {(json:NSDictionary) -> Void in let images = json["images"] as! NSArray callback(images) } } func imagePassed(imageId:NSString) { post("/images/\(imageId)/passes") } func imageFaved(imageId:NSString) { post("/images/\(imageId)/favorites") } func imageFlaggedAsInappropriate(imageId:NSString) { post("/images/\(imageId)/inappropriate") } func get(url:String, callback: (NSDictionary) -> Void) { request("GET", url: url, body:nil) {(data:NSData) in let json = NSJSONSerialization.JSONObjectWithData(data, options: nil, error: nil) as! NSDictionary callback(json) } } func post(url:String) { request("POST", url: url, body:nil) {NSData in } } func request(httpMethod:String, url:String, body:NSDictionary?, callback: (NSData) -> Void) { let session = NSURLSession.sharedSession() let url = "".join([apiUrl, url]) let request = NSMutableURLRequest(URL: NSURL(string:url)!) request.HTTPMethod = httpMethod request.addValue("application/json", forHTTPHeaderField: "Content-Type") request.addValue("application/json", forHTTPHeaderField: "Accept") if let token = authenticationToken() { request.addValue(token, forHTTPHeaderField: "X-User-Token") } if let data = body { request.HTTPBody = NSJSONSerialization.dataWithJSONObject(data, options: NSJSONWritingOptions.allZeros, error: nil) } NSLog("%@ %@", httpMethod, url) let task = session.dataTaskWithRequest(request) {(data, response, error) in var httpResponse = response as! NSHTTPURLResponse? if error != nil { NSLog("Failed to connect to server: %@", error) } else if httpResponse!.statusCode != 200 { let message = NSHTTPURLResponse.localizedStringForStatusCode(httpResponse!.statusCode) NSLog("Server error: %d – %@", httpResponse!.statusCode, message) } else { println("\(httpMethod) \(url) - \(httpResponse!.statusCode)") callback(data) } } task.resume() } func authenticationToken() -> String? { if let token = NSUserDefaults.standardUserDefaults().stringForKey(authentication_token_key) { return token } return UIDevice.currentDevice().identifierForVendor.UUIDString } func deletePersistedAuthenticationToken() { NSUserDefaults.standardUserDefaults().setObject(nil, forKey: authentication_token_key) NSUserDefaults.standardUserDefaults().synchronize() } func authenticationTokenExists() -> Bool { if let token = NSUserDefaults.standardUserDefaults().stringForKey(authentication_token_key) { return true; } else { return false; } } }
agpl-3.0
ef6e0ad25c84d2695ce28c08f564453f
37.769841
127
0.622313
4.899699
false
false
false
false
wordpress-mobile/WordPress-iOS
WordPress/Classes/ViewRelated/Aztec/ViewControllers/AztecAttachmentViewController.swift
2
11178
import Foundation import UIKit import WordPressShared import Aztec class AztecAttachmentViewController: UITableViewController { @objc var attachment: ImageAttachment? { didSet { if let attachment = attachment { alignment = attachment.alignment alt = attachment.alt size = attachment.size } } } var alignment: ImageAttachment.Alignment? = nil var linkURL: URL? var size = ImageAttachment.Size.none @objc var alt: String? var caption: NSAttributedString? var onUpdate: ((_ alignment: ImageAttachment.Alignment?, _ size: ImageAttachment.Size, _ linkURL: URL?, _ altText: String?, _ caption: NSAttributedString?) -> Void)? @objc var onCancel: (() -> Void)? fileprivate var handler: ImmuTableViewHandler! // MARK: - Initialization override init(style: UITableView.Style) { super.init(style: style) navigationItem.title = NSLocalizedString("Media Settings", comment: "Media Settings Title") } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } required convenience init() { self.init(style: .grouped) } override func viewDidLoad() { super.viewDidLoad() ImmuTable.registerRows([ EditableTextRow.self, ], tableView: self.tableView) handler = ImmuTableViewHandler(takeOver: self) handler.viewModel = tableViewModel() WPStyleGuide.configureColors(view: view, tableView: tableView) let cancelButton = UIBarButtonItem(barButtonSystemItem: .cancel, target: self, action: #selector(AztecAttachmentViewController.handleCancelButtonTapped)) navigationItem.leftBarButtonItem = cancelButton let doneButton = UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(AztecAttachmentViewController.handleDoneButtonTapped)) navigationItem.rightBarButtonItem = doneButton } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) self.handler.viewModel = self.tableViewModel() } // MARK: - Model mapping func tableViewModel() -> ImmuTable { let displaySettingsHeader = NSLocalizedString("Web Display Settings", comment: "The title of the option group for editing an image's size, alignment, etc. on the image details screen.") let alignmentRow = EditableTextRow( title: NSLocalizedString("Alignment", comment: "Image alignment option title."), value: alignment?.localizedString ?? ImageAttachment.Alignment.none.localizedString, action: displayAlignmentSelector) let linkToRow = EditableTextRow( title: NSLocalizedString("Link To", comment: "Image link option title."), value: linkURL?.absoluteString ?? "", action: displayLinkTextfield) let sizeRow = EditableTextRow( title: NSLocalizedString("Size", comment: "Image size option title."), value: size.localizedString, action: displaySizeSelector) let altRow = EditableTextRow( title: NSLocalizedString("Alt Text", comment: "Image alt attribute option title."), value: alt ?? "", action: displayAltTextfield) let captionRow = EditableAttributedTextRow( title: NSLocalizedString("Caption", comment: "Image caption field label (for editing)"), value: caption ?? NSAttributedString(), action: displayCaptionTextfield) return ImmuTable(sections: [ ImmuTableSection( headerText: displaySettingsHeader, rows: [ alignmentRow, linkToRow, sizeRow, altRow, captionRow ], footerText: nil) ]) } // MARK: - Actions private func displayAltTextfield(row: ImmuTableRow) { let editableRow = row as! EditableTextRow let hint = NSLocalizedString("Image Alt", comment: "Hint for image alt on image settings.") pushSettingsController(for: editableRow, hint: hint, settingsTextMode: .text) { [weak self] value in guard let `self` = self else { return } self.alt = value self.tableView.reloadData() } } private func displayCaptionTextfield(row: ImmuTableRow) { let editableRow = row as! EditableAttributedTextRow let hint = NSLocalizedString("Image Caption", comment: "Hint for image caption on image settings.") pushSettingsController(for: editableRow, hint: hint) { [weak self] value in guard let `self` = self else { return } self.caption = value self.tableView.reloadData() } } private func displayLinkTextfield(row: ImmuTableRow) { let editableRow = row as! EditableTextRow let hint = NSLocalizedString("Image Link", comment: "Hint for image link on image settings.") pushSettingsController(for: editableRow, hint: hint, settingsTextMode: .URL) { [weak self] value in guard let `self` = self else { return } self.linkURL = URL(string: value) self.tableView.reloadData() } } func displayAlignmentSelector(row: ImmuTableRow) { let values: [ImageAttachment.Alignment] = [.left, .center, .right, .none] let titles = values.map { (value) in return value.localizedString } let currentValue = alignment let dict: [String: Any] = [ SettingsSelectionDefaultValueKey: alignment ?? ImageAttachment.Alignment.none, SettingsSelectionTitleKey: NSLocalizedString("Alignment", comment: "Title of the screen for choosing an image's alignment."), SettingsSelectionTitlesKey: titles, SettingsSelectionValuesKey: values, SettingsSelectionCurrentValueKey: currentValue ?? ImageAttachment.Alignment.none ] guard let vc = SettingsSelectionViewController(dictionary: dict) else { return } vc.onItemSelected = { (status: Any) in if let newAlignment = status as? ImageAttachment.Alignment { self.alignment = newAlignment } vc.dismiss() self.tableView.reloadData() } self.navigationController?.pushViewController(vc, animated: true) } func displaySizeSelector(row: ImmuTableRow) { let values: [ImageAttachment.Size] = [.thumbnail, .medium, .large, .full, .none] let titles = values.map { (value) in return value.localizedString } let currentValue = size let dict: [String: Any] = [ SettingsSelectionDefaultValueKey: size, SettingsSelectionTitleKey: NSLocalizedString("Image Size", comment: "Title of the screen for choosing an image's size."), SettingsSelectionTitlesKey: titles, SettingsSelectionValuesKey: values, SettingsSelectionCurrentValueKey: currentValue ] guard let vc = SettingsSelectionViewController(dictionary: dict) else { return } vc.onItemSelected = { (status: Any) in // do interesting work here... like updating the value of image meta. if let newSize = status as? ImageAttachment.Size { self.size = newSize } vc.dismiss() self.tableView.reloadData() } self.navigationController?.pushViewController(vc, animated: true) } // MARK: - Helper methods @objc func handleCancelButtonTapped(sender: UIBarButtonItem) { onCancel?() dismiss(animated: true) } @objc func handleDoneButtonTapped(sender: UIBarButtonItem) { let checkedAlt = alt == "" ? nil : alt onUpdate?(alignment, size, linkURL, checkedAlt, caption) dismiss(animated: true) } private func pushSettingsController(for row: EditableTextRow, hint: String? = nil, settingsTextMode: SettingsTextModes, onValueChanged: @escaping SettingsTextChanged) { let title = row.title let value = row.value let controller = SettingsTextViewController(text: value, placeholder: "\(title)...", hint: hint) controller.title = title controller.mode = settingsTextMode controller.onValueChanged = onValueChanged navigationController?.pushViewController(controller, animated: true) } private func pushSettingsController(for row: EditableAttributedTextRow, hint: String? = nil, onValueChanged: @escaping SettingsAttributedTextChanged) { // TODO: This shouldn't duplicate the styling from the Figcaption formatter. Try to unify. let defaultAttributes: [NSAttributedString.Key: Any] = [ .font: WPFontManager.notoRegularFont(ofSize: 14), .foregroundColor: UIColor.gray, ] let title = row.title let value = row.value let controller = SettingsTextViewController(attributedText: value, defaultAttributes: defaultAttributes, placeholder: "\(title)...", hint: hint) controller.title = title controller.onAttributedValueChanged = onValueChanged navigationController?.pushViewController(controller, animated: true) } } extension ImageAttachment.Alignment { var localizedString: String { switch self { case .left: return NSLocalizedString("Left", comment: "Left alignment for an image. Should be the same as in core WP.") case .center: return NSLocalizedString("Center", comment: "Center alignment for an image. Should be the same as in core WP.") case .right: return NSLocalizedString("Right", comment: "Right alignment for an image. Should be the same as in core WP.") case .none: return NSLocalizedString("None", comment: "No alignment for an image (default). Should be the same as in core WP.") } } } extension ImageAttachment.Size { var localizedString: String { switch self { case .thumbnail: return NSLocalizedString("Thumbnail", comment: "Thumbnail image size. Should be the same as in core WP.") case .medium: return NSLocalizedString("Medium", comment: "Medium image size. Should be the same as in core WP.") case .large: return NSLocalizedString("Large", comment: "Large image size. Should be the same as in core WP.") case .full: return NSLocalizedString("Full Size", comment: "Full size image. (default). Should be the same as in core WP.") case .none: return NSLocalizedString("None", comment: "No size class defined for the image. Should be the same as in core WP.") } } }
gpl-2.0
ff2cf306b0ff07fe732eb6aea3234ef4
36.763514
193
0.630793
5.353448
false
false
false
false
mlgoogle/viossvc
viossvc/General/Extension/UIViewEx.swift
1
1635
// // UIViewEx.swift // HappyTravel // // Created by 巩婧奕 on 2017/3/3. // Copyright © 2017年 陈奕涛. All rights reserved. // import Foundation import UIKit extension UIView { var Left:CGFloat { get { return self.frame.origin.x } set(left) { self.frame = CGRectMake(left, self.frame.origin.y, self.frame.size.width, self.frame.size.height) } } var Right:CGFloat { get { return self.frame.origin.x + self.frame.size.width } set(right) { self.frame = CGRectMake(self.frame.origin.x, self.frame.origin.y, right - self.Left, self.frame.size.height) } } var Top:CGFloat { get { return self.frame.origin.y } set(top) { self.frame = CGRectMake(self.frame.origin.x, top, self.frame.size.width, self.frame.size.height) } } var Bottom:CGFloat { get { return self.frame.size.height + self.Top } set(bottom) { self.frame = CGRectMake(self.Left, self.Top, self.frame.size.width, bottom - self.Top) } } var Width:CGFloat { get { return self.frame.size.width } set(width) { self.frame = CGRectMake(self.Left, self.Top, width, self.frame.size.height) } } var Height:CGFloat { get { return self.frame.size.height } set(height) { self.frame = CGRectMake(self.Left, self.Top, self.Width, height) } } }
apache-2.0
19761aa7b6ddf71f0d02dd2990c7bcdd
20.891892
120
0.521605
3.69863
false
false
false
false
chetca/Android_to_iOs
memuDemo/SideMenuSC/menuViewController.swift
1
8102
// // menuViewController.swift // memuDemo // // Created by Parth Changela on 09/10/16. // Copyright © 2016 Parth Changela. All rights reserved. // import UIKit class menuViewController: UIViewController,UITableViewDelegate,UITableViewDataSource { @IBOutlet weak var RandomTextUnderPict: UILabel! @IBOutlet weak var tblTableView: UITableView! @IBOutlet weak var imgProfile: UIImageView! @IBOutlet var imgXConstraint: NSLayoutConstraint! @IBOutlet var imgWidthConstraint: NSLayoutConstraint! var randFrazes = ["Да пребудет с вами Будда", "Пусть вам сопутствует удача", "Пусть вас защищают все боги", "Улыбнитесь, всё будет хорошо", "Будьте сильны духом", "Будьте в добром здравии"] var viewControllersDict: [String:String] = ["Новости":"ViewController", "Расписание хуралов":"KhuralScheduleViewController", "Астрологический прогноз":"AstrologicalForecastViewController", "Дацаны Сангхи":"DatsansTableViewController", "Историческая справка":"HistoryTableViewController", "Лекции буддийского университета":"LecturesTableViewController", "Фото":"PhotoAlbumTableViewController", "Видео":"VideoAlbumViewController", "РазРабы":"DevelopersViewController"] var randIndex = arc4random_uniform(5) var ManuNameArray:Array = [String]() var iconArray:Array = [UIImage]() var didLoadCalled = true func handleDissmis () { if let window = UIApplication.shared.keyWindow { //magic numbers ALERT !!! UIView.animate(withDuration: 0.68, delay: 0, usingSpringWithDamping: 0.7, initialSpringVelocity: 0.88, options: .curveEaseOut, animations: { blackView.frame = CGRect(x: 0, y: 0, width: window.frame.width, height: window.frame.height) blackView.alpha = 0 }, completion: nil) revealViewController().revealToggle(animated: true) } } func makeDark () { if let window = UIApplication.shared.keyWindow { blackView.backgroundColor = UIColor(white: 0, alpha: 0.5) blackView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(handleDissmis))) window.addSubview(blackView) blackView.frame = CGRect(x: 0, y: 0, width: window.frame.width, height: window.frame.height) blackView.alpha = 0 //magic numbers ALERT !!! UIView.animate(withDuration: 0.725, delay: 0, usingSpringWithDamping: 1.1, initialSpringVelocity: 0.8, options: .curveEaseOut, animations: { blackView.alpha = 1 blackView.frame = CGRect(x: window.frame.width*0.8, y: 0, width: window.frame.width, height: window.frame.height) }, completion: nil) } } override func viewDidLoad() { super.viewDidLoad() JSONTaker.shared.setStatusBarColorOrange() self.view.layer.shadowRadius = 10; revealViewController().toggleAnimationType = SWRevealToggleAnimationType.spring revealViewController().toggleAnimationDuration = 0.725 //magic numbers ALERT !!! if let window = UIApplication.shared.keyWindow { revealViewController().rearViewRevealWidth = window.frame.width * 0.8 revealViewController().draggableBorderWidth = window.frame.width * 0.05 imgXConstraint.constant = window.frame.width * 0.4 - imgWidthConstraint.constant*0.5 } //var recon = UIScreenEdgePanGestureRecognizer() ManuNameArray = [ "Новости", "Расписание хуралов", "Астрологический прогноз", "Дацаны Сангхи", "Историческая справка", "Лекции буддийского университета", "Фото", "Видео", "РазРабы" ] iconArray = [UIImage(named:"news")!, UIImage(named:"hurals")!, UIImage(named:"zurkhai")!, UIImage(named:"datsans")!, UIImage(named:"history")!, UIImage(named:"lectures")!, UIImage(named:"album")!, UIImage(named:"video")!, UIImage(named:"settings")! ] imgProfile.layer.masksToBounds = false imgProfile.clipsToBounds = true // Do any additional setup after loading the view. } override func viewDidAppear(_ animated: Bool) { let randIndex = arc4random_uniform(5) RandomTextUnderPict.text = randFrazes[Int(randIndex)] makeDark() JSONTaker.shared.setStatusBarColorOrange() if (didLoadCalled == true) { (self.tblTableView.cellForRow(at: IndexPath(row: 0, section: 0)) as! MenuCell).setSelected(true, animated: true) } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return ManuNameArray.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "MenuCell", for: indexPath) as! MenuCell cell.lblMenuname.text! = ManuNameArray[indexPath.row] cell.imgIcon.image = iconArray[indexPath.row] cell.frame.size = CGSize(width: cell.frame.size.width, height: 200) return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { handleDissmis() let _:SWRevealViewController = self.revealViewController() let cell:MenuCell = tableView.cellForRow(at: indexPath) as! MenuCell print(cell.lblMenuname.text!) if (didLoadCalled == true) { if (indexPath.row != 0) { (self.tblTableView.cellForRow(at: IndexPath(row: 0, section: 0)) as! MenuCell).setSelected(false, animated: true) } didLoadCalled = false } callViewController(controllerName: cell.lblMenuname.text!) } private func callViewController (controllerName: String) { for i in 0...ManuNameArray.count-1 { if ManuNameArray[i] == controllerName { JSONTaker.shared.location = i } } print(JSONTaker.shared.location) let mainstoryboard:UIStoryboard = UIStoryboard(name: "Main", bundle: nil) let newViewcontroller = mainstoryboard.instantiateViewController(withIdentifier: viewControllersDict[controllerName]!) let newFrontController = UINavigationController.init(rootViewController: newViewcontroller) revealViewController().pushFrontViewController(newFrontController, animated: true) } }
mit
b2a800c8064066ab181261fc8d372953
42.666667
208
0.57226
4.873266
false
false
false
false
cotkjaer/Silverback
Silverback/Float.swift
1
4544
// // Float.swift // SilverbackFramework // // Created by Christian Otkjær on 20/04/15. // Copyright (c) 2015 Christian Otkjær. All rights reserved. // import Foundation public extension Float { /** Absolute value. - returns: fabs(self) */ public var abs: Float { return fabsf(self) } /** Squareroot. - returns: sqrtf(self) */ public var sqrt: Float { return sqrtf(self) } /** Round to largest integral value not greater than self - returns: floorf(self) */ public var floor: Float { return floorf(self) } /** Round to smallest integral value not less than self - returns: ceilf(self) */ public var ceil: Float { return ceilf(self) } /** Rounds self to the nearest integral value - returns: roundf(self) */ public var round: Float { return roundf(self) } /** Clamps self to a specified range. - parameter min: Lower bound - parameter max: Upper bound - returns: Clamped value */ public func clamp (lower: Float, _ upper: Float) -> Float { return Swift.max(lower, Swift.min(upper, self)) } public static func random() -> Float { return random(lower: 0.0, upper: HUGE) } /** Create a random Float between lower and upper bounds (inclusive) - parameter lower: number Float - parameter upper: number Float :return: random number Float */ public static func random(lower lower: Float, upper: Float) -> Float { if lower > upper { return random(lower: upper, upper: lower) } let r = Float(arc4random(UInt32)) / Float(UInt32.max) return (r * (upper - lower)) + lower } } public extension Float { public func format(format: String? = "") -> String { return String(format: "%\(format)f", self) } } public func rms(xs: Float...) { } ///The root mean square (abbreviated RMS or rms), also known as the quadratic mean, in statistics is a statistical measure defined as the square root of the mean of the squares of a sample /// - Note: With large numbers this may overrun @warn_unused_result public func rms<S: SequenceType where S.Generator.Element == Float>(xs: S) -> Float { let count = xs.count{ _ in true } guard count > 0 else { return 0 } let sum = xs.reduce(Float(0), combine: { $0 + $1*$1 }) return sqrtf(sum / Float(count)) } public func rms(xs: [Float], firstIndex: Int, lastIndex: Int) -> Float { return rms(xs[firstIndex...lastIndex]) } ///The simplest (and by no means ideal) low-pass filter is given by the following difference equation: ///```swift /// y(n) = x(n) + x(n - 1) ///``` ///where `x(n)` is the filter input amplitude at time (or sample) `n` , and `y(n)` is the output amplitude at time `n` //func lowpass(x: [Float], inout y: [Float], xm1: Float, m: Int, offset: Int) -> Float //{ // y[offset] = x[offset] + xm1 // // for var n = 1; n < m ; n++ // { // y[offset + n] = x[offset + n] + x[offset + n-1] // } // // return x[offset + m-1] //} public func lowpass(xs: [Float]) -> [Float] { let M = xs.count guard M > 0 else { return [] } var ys = Array<Float>(count: xs.count, repeatedValue: Float(0)) ys[0] = xs[0] for var n = 1; n < M; n++ { ys[n] = xs[n] + xs[n-1] } return ys } // MARK: - Int interoperability public func * (rhs: Float, lhs: Int) -> Float { return rhs * Float(lhs) } public func * (rhs: Int, lhs: Float) -> Float { return Float(rhs) * lhs } public func *= (inout rhs: Float, lhs: Int) { rhs *= Float(lhs) } public func / (rhs: Float, lhs: Int) -> Float { return rhs / Float(lhs) } public func / (rhs: Int, lhs: Float) -> Float { return Float(rhs) / lhs } public func /= (inout rhs: Float, lhs: Int) { rhs /= Float(lhs) } public func + (rhs: Float, lhs: Int) -> Float { return rhs + Float(lhs) } public func + (rhs: Int, lhs: Float) -> Float { return Float(rhs) + lhs } public func += (inout rhs: Float, lhs: Int) { rhs += Float(lhs) } public func - (rhs: Float, lhs: Int) -> Float { return rhs - Float(lhs) } public func - (rhs: Int, lhs: Float) -> Float { return Float(rhs) - lhs } public func -= (inout rhs: Float, lhs: Int) { rhs -= Float(lhs) }
mit
f8fc8d7c732a65a8eaeea5c2ecf4c9e7
18.834061
188
0.564289
3.412472
false
false
false
false
eBardX/XestiMonitors
Examples/XestiMonitorsDemo-iOS/XestiMonitorsDemo/AppDelegate.swift
1
1669
// // AppDelegate.swift // XestiMonitorsDemo-iOS // // Created by J. G. Pusey on 2016-11-23. // // © 2016 J. G. Pusey (see LICENSE.md) // import UIKit @UIApplicationMain public class AppDelegate: UIResponder, UIApplicationDelegate, UISplitViewControllerDelegate { // MARK: Public Instance Properties public var window: UIWindow? // MARK: UIApplicationDelegate Methods public func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { guard let svc = window?.rootViewController as? UISplitViewController else { return false } svc.delegate = self svc.preferredDisplayMode = .allVisible guard let nc = svc.viewControllers[svc.viewControllers.count - 1] as? UINavigationController else { return false } nc.topViewController?.navigationItem.leftBarButtonItem = svc.displayModeButtonItem return true } public func applicationDidBecomeActive(_ application: UIApplication) { } public func applicationDidEnterBackground(_ application: UIApplication) { } public func applicationWillEnterForeground(_ application: UIApplication) { } public func applicationWillResignActive(_ application: UIApplication) { } public func applicationWillTerminate(_ application: UIApplication) { } // MARK: UISplitViewControllerDelegate Methods public func targetDisplayModeForAction(in splitViewController: UISplitViewController) -> UISplitViewControllerDisplayMode { return .allVisible } }
mit
87c30a39014c6355e0e378570ffb55ea
27.271186
127
0.701439
5.914894
false
false
false
false
RedMadRobot/input-mask-ios
Source/InputMask/InputMaskTests/Classes/Mask/SillyEllipticalCase.swift
1
9769
// // Project «InputMask» // Created by Jeorge Taflanidi // import XCTest @testable import InputMask class SillyEllipticalCase: MaskTestCase { override func format() -> String { return "[0…][AAA]" } func testInit_correctFormat_maskInitialized() { XCTAssertNotNil(try self.mask()) } func testInit_correctFormat_measureTime() { self.measure { var masks: [Mask] = [] for _ in 1...1000 { masks.append( try! self.mask() ) } } } func testGetOrCreate_correctFormat_measureTime() { self.measure { var masks: [Mask] = [] for _ in 1...1000 { masks.append( try! Mask.getOrCreate(withFormat: self.format()) ) } } } func testGetPlaceholder_allSet_returnsCorrectPlaceholder() { let placeholder: String = try! self.mask().placeholder XCTAssertEqual(placeholder, "0") } func testAcceptableTextLength_allSet_returnsCorrectCount() { let acceptableTextLength: Int = try! self.mask().acceptableTextLength XCTAssertEqual(acceptableTextLength, 2) } func testTotalTextLength_allSet_returnsCorrectCount() { let totalTextLength: Int = try! self.mask().totalTextLength XCTAssertEqual(totalTextLength, 2) } func testAcceptableValueLength_allSet_returnsCorrectCount() { let acceptableValueLength: Int = try! self.mask().acceptableValueLength XCTAssertEqual(acceptableValueLength, 2) } func testTotalValueLength_allSet_returnsCorrectCount() { let totalValueLength: Int = try! self.mask().totalValueLength XCTAssertEqual(totalValueLength, 2) } func testApply_J_returns_emptyString() { let inputString: String = "J" let inputCaret: String.Index = inputString.endIndex let expectedString: String = "" let expectedCaret: String.Index = expectedString.endIndex let expectedValue: String = expectedString let result: Mask.Result = try! self.mask().apply( toText: CaretString( string: inputString, caretPosition: inputCaret, caretGravity: .forward(autocomplete: false) ) ) XCTAssertEqual(expectedString, result.formattedText.string) XCTAssertEqual(expectedCaret, result.formattedText.caretPosition) XCTAssertEqual(expectedValue, result.extractedValue) XCTAssertEqual(false, result.complete) } func testApply_Je_returns_emptyString() { let inputString: String = "Je" let inputCaret: String.Index = inputString.endIndex let expectedString: String = "" let expectedCaret: String.Index = expectedString.endIndex let expectedValue: String = expectedString let result: Mask.Result = try! self.mask().apply( toText: CaretString( string: inputString, caretPosition: inputCaret, caretGravity: .forward(autocomplete: false) ) ) XCTAssertEqual(expectedString, result.formattedText.string) XCTAssertEqual(expectedCaret, result.formattedText.caretPosition) XCTAssertEqual(expectedValue, result.extractedValue) XCTAssertEqual(false, result.complete) } func testApply_Jeo_returns_emptyString() { let inputString: String = "Jeo" let inputCaret: String.Index = inputString.endIndex let expectedString: String = "" let expectedCaret: String.Index = expectedString.endIndex let expectedValue: String = expectedString let result: Mask.Result = try! self.mask().apply( toText: CaretString( string: inputString, caretPosition: inputCaret, caretGravity: .forward(autocomplete: false) ) ) XCTAssertEqual(expectedString, result.formattedText.string) XCTAssertEqual(expectedCaret, result.formattedText.caretPosition) XCTAssertEqual(expectedValue, result.extractedValue) XCTAssertEqual(false, result.complete) } func testApply_1_returns_1() { let inputString: String = "1" let inputCaret: String.Index = inputString.endIndex let expectedString: String = "1" let expectedCaret: String.Index = expectedString.endIndex let expectedValue: String = expectedString let result: Mask.Result = try! self.mask().apply( toText: CaretString( string: inputString, caretPosition: inputCaret, caretGravity: .forward(autocomplete: false) ) ) XCTAssertEqual(expectedString, result.formattedText.string) XCTAssertEqual(expectedCaret, result.formattedText.caretPosition) XCTAssertEqual(expectedValue, result.extractedValue) XCTAssertEqual(true, result.complete) } func testApply_12_returns_12() { let inputString: String = "12" let inputCaret: String.Index = inputString.endIndex let expectedString: String = "12" let expectedCaret: String.Index = expectedString.endIndex let expectedValue: String = expectedString let result: Mask.Result = try! self.mask().apply( toText: CaretString( string: inputString, caretPosition: inputCaret, caretGravity: .forward(autocomplete: false) ) ) XCTAssertEqual(expectedString, result.formattedText.string) XCTAssertEqual(expectedCaret, result.formattedText.caretPosition) XCTAssertEqual(expectedValue, result.extractedValue) XCTAssertEqual(true, result.complete) } func testApply_123_returns_123() { let inputString: String = "123" let inputCaret: String.Index = inputString.endIndex let expectedString: String = "123" let expectedCaret: String.Index = expectedString.endIndex let expectedValue: String = expectedString let result: Mask.Result = try! self.mask().apply( toText: CaretString( string: inputString, caretPosition: inputCaret, caretGravity: .forward(autocomplete: false) ) ) XCTAssertEqual(expectedString, result.formattedText.string) XCTAssertEqual(expectedCaret, result.formattedText.caretPosition) XCTAssertEqual(expectedValue, result.extractedValue) XCTAssertEqual(true, result.complete) } func testApply_1Jeorge2_returns_12() { let inputString: String = "1Jeorge2" let inputCaret: String.Index = inputString.endIndex let expectedString: String = "12" let expectedCaret: String.Index = expectedString.endIndex let expectedValue: String = expectedString let result: Mask.Result = try! self.mask().apply( toText: CaretString( string: inputString, caretPosition: inputCaret, caretGravity: .forward(autocomplete: false) ) ) XCTAssertEqual(expectedString, result.formattedText.string) XCTAssertEqual(expectedCaret, result.formattedText.caretPosition) XCTAssertEqual(expectedValue, result.extractedValue) XCTAssertEqual(true, result.complete) } func testApply_1Jeorge23_returns_123() { let inputString: String = "1Jeorge23" let inputCaret: String.Index = inputString.endIndex let expectedString: String = "123" let expectedCaret: String.Index = expectedString.endIndex let expectedValue: String = expectedString let result: Mask.Result = try! self.mask().apply( toText: CaretString( string: inputString, caretPosition: inputCaret, caretGravity: .forward(autocomplete: false) ) ) XCTAssertEqual(expectedString, result.formattedText.string) XCTAssertEqual(expectedCaret, result.formattedText.caretPosition) XCTAssertEqual(expectedValue, result.extractedValue) XCTAssertEqual(true, result.complete) } func testApply_1234Jeorge56_returns_123456() { let inputString: String = "1234Jeorge56" let inputCaret: String.Index = inputString.endIndex let expectedString: String = "123456" let expectedCaret: String.Index = expectedString.endIndex let expectedValue: String = expectedString let result: Mask.Result = try! self.mask().apply( toText: CaretString( string: inputString, caretPosition: inputCaret, caretGravity: .forward(autocomplete: false) ) ) XCTAssertEqual(expectedString, result.formattedText.string) XCTAssertEqual(expectedCaret, result.formattedText.caretPosition) XCTAssertEqual(expectedValue, result.extractedValue) XCTAssertEqual(true, result.complete) } }
mit
ed62c9ac296e98b07d1539fd271ea1a3
34.509091
79
0.597849
5.605626
false
true
false
false
chromatic-seashell/weibo
新浪微博/新浪微博/classes/category/ProgressView/ProgressImageView.swift
1
1450
// // ProgressImageView.swift // 01-进度条View // // Created by xiaomage on 15/11/16. // Copyright © 2015年 xiaomage. All rights reserved. // import UIKit class ProgressImageView: UIImageView { /// 进度 0~1 var progregss: CGFloat = 0.0 { didSet{ progressView.progregss = progregss } } init() { super.init(frame: CGRectZero) setupUI() } override init(frame: CGRect) { super.init(frame: frame) setupUI() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setupUI() } private func setupUI() { // 1.清空进度背景 progressView.backgroundColor = UIColor.clearColor() // 2.添加进度视图 addSubview(progressView) //3.添加约束 progressView.translatesAutoresizingMaskIntoConstraints = false var cons = NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[progressView]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["progressView": progressView]) cons += NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[progressView]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["progressView": progressView]) addConstraints(cons) } // MAKR: - 懒加载 private lazy var progressView: ProgressView = ProgressView() }
apache-2.0
c2c6184dc0838b0b16ff05f013a7e286
24.907407
191
0.617584
4.601974
false
false
false
false
ubi-naist/SenStick
ios/SenStickViewer/SenStickViewer/SensorDataViewController.swift
1
6539
// // SensorDataViewController.swift // SenStickViewer // // Created by AkihiroUehara on 2016/05/22. // Copyright © 2016年 AkihiroUehara. All rights reserved. // import UIKit import SenStickSDK import CoreMotion // センサデバイスの、センサデータ一覧を提供します。 class SensorDataViewController : UITableViewController, SenStickDeviceDelegate { @IBOutlet var deviceInformationButton: UIBarButtonItem! var device: SenStickDevice? var statusCell: SensorStatusCellView? var accelerationDataModel: AccelerationDataModel? var gyroDataModel: GyroDataModel? var magneticFieldDataModel: MagneticFieldDataModel? var brightnessDataModel: BrightnessDataModel? var uvDataModel: UVDataModel? var humidityDataModel: HumidityDataModel? var pressureDataModel: PressureDataModel? // MARK: - View life cycle override func viewDidLoad() { super.viewDidLoad() accelerationDataModel = AccelerationDataModel() gyroDataModel = GyroDataModel() magneticFieldDataModel = MagneticFieldDataModel() brightnessDataModel = BrightnessDataModel() uvDataModel = UVDataModel() humidityDataModel = HumidityDataModel() pressureDataModel = PressureDataModel() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) device?.delegate = self device?.connect() if device != nil { didServiceFound(device!) } // 右上のバーボタンアイテムのenable設定。ログ停止中のみ遷移可能 /* if let control = device?.controlService { self.deviceInformationButton.enabled = (control.command == .Stopping) } else { self.deviceInformationButton.enabled = false }*/ } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) device?.delegate = nil // リスト表示に戻る場合は、デバイスとのBLE接続を切る if let backToListView = self.navigationController?.viewControllers.contains(self) { // ListViewに戻る時、ナビゲーションに自身が含まれていない。 if backToListView == false { device?.cancelConnection() } } } // MARK: - Public methods func clearGraph() { accelerationDataModel?.clearPlot() gyroDataModel?.clearPlot() magneticFieldDataModel?.clearPlot() brightnessDataModel?.clearPlot() uvDataModel?.clearPlot() humidityDataModel?.clearPlot() pressureDataModel?.clearPlot() } // MARK: - SenStickDeviceDelegate func didServiceFound(_ sender: SenStickDevice) { self.statusCell?.name = device?.name self.statusCell?.service = device?.controlService accelerationDataModel?.service = device?.accelerationSensorService gyroDataModel?.service = device?.gyroSensorService magneticFieldDataModel?.service = device?.magneticFieldSensorService brightnessDataModel?.service = device?.brightnessSensorService uvDataModel?.service = device?.uvSensorService humidityDataModel?.service = device?.humiditySensorService pressureDataModel?.service = device?.pressureSensorService } func didConnected(_ sender:SenStickDevice) { } func didDisconnected(_ sender:SenStickDevice) { _ = self.navigationController?.popToRootViewController(animated: true) } // MARK: - Private methods override func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) { switch ((indexPath as NSIndexPath).row) { case 0: self.statusCell = cell as? SensorStatusCellView self.statusCell?.controller = self case 1: accelerationDataModel?.cell = cell as? SensorDataCellView case 2: gyroDataModel?.cell = cell as? SensorDataCellView case 3: magneticFieldDataModel?.cell = cell as? SensorDataCellView case 4: brightnessDataModel?.cell = cell as? SensorDataCellView case 5: uvDataModel?.cell = cell as? SensorDataCellView case 6: humidityDataModel?.cell = cell as? SensorDataCellView case 7: pressureDataModel?.cell = cell as? SensorDataCellView default: break } } // MARK: - Segues override func shouldPerformSegue(withIdentifier identifier: String, sender: Any?) -> Bool { // デバイス詳細情報表示に遷移 if identifier == "deviceInformation" { return (device?.deviceInformationService != nil) } // 詳細表示遷移できるのはログ停止時だけ if let control = device?.controlService { return (control.command == .stopping) } else { return false } } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if let vc = segue.destination as? DeviceInformationViewController { vc.device = self.device } if let vc = segue.destination as? LogListViewController { vc.device = self.device } // debugPrint(" \(segue.destinationViewController)") if let vc = segue.destination as? SamplingDurationViewController { let indexPath = self.tableView.indexPathForSelectedRow! switch((indexPath as NSIndexPath).row) { case 1: vc.target = device?.accelerationSensorService case 2: vc.target = device?.gyroSensorService case 3: vc.target = device?.magneticFieldSensorService case 4: vc.target = device?.brightnessSensorService case 5: vc.target = device?.uvSensorService case 6: vc.target = device?.humiditySensorService case 7: vc.target = device?.pressureSensorService default: break } } } }
mit
bb31a54ac257fb594ce14c0d04c1e0e2
31.86911
119
0.605925
5.046624
false
false
false
false
Michaelyb520/PhotoBrowser
PhotoBrowser/DisplayVC.swift
1
2221
// // DisplayVC.swift // PhotoBrowser // // Created by 冯成林 on 15/8/14. // Copyright (c) 2015年 冯成林. All rights reserved. // import UIKit class DisplayVC: UIViewController { var langType: LangType = LangType.Chinese var photoType: PhotoType = PhotoType.Local var showType: PhotoBrowser.ShowType = PhotoBrowser.ShowType.ZoomAndDismissWithSingleTap lazy var localImages: [String] = {["1.jpg","2.jpg","3.jpg","4.jpg","5.jpg","6.jpg","7.jpg","8.jpg","9.jpg"]}() let displayView = DisplayView() lazy var hostThumbNailImageUrls: [String] = { return [ "http://ios-android.cn/PB/ThumbNail/1.jpg", "http://ios-android.cn/PB/ThumbNail/2.jpg", "http://ios-android.cn/PB/ThumbNail/3.jpg", "http://ios-android.cn/PB/ThumbNail/4.jpg", "http://ios-android.cn/PB/ThumbNail/5.jpg", "http://ios-android.cn/PB/ThumbNail/6.jpg", "http://ios-android.cn/PB/ThumbNail/7.jpg", "http://ios-android.cn/PB/ThumbNail/8.jpg", "http://ios-android.cn/PB/ThumbNail/9.jpg", ] }() } extension DisplayVC{ override func viewDidLoad() { super.viewDidLoad() self.view.backgroundColor = UIColor.whiteColor() self.navigationItem.title = langType == LangType.Chinese ? "照片浏览器终结者" : "Photo Browser Terminator" if photoType == PhotoType.Local { //本地 displayView.imgsPrepare(localImages, isLocal: true) }else{ //网络 displayView.imgsPrepare(hostThumbNailImageUrls, isLocal: false) } view.addSubview(displayView) let wh = min(UIScreen.mainScreen().bounds.size.width, UIScreen.mainScreen().bounds.size.height) displayView.make_center(offsest: CGPointZero, width: wh, height: wh) displayView.tapedImageV = {[unowned self] index in if self.photoType == PhotoType.Local { //本地 self.showLocal(index) }else{ //网络 self.showHost(index) } } } }
mit
8a7c040e21fcfdfb48deac1098b132a7
26.884615
114
0.572414
3.911871
false
false
false
false
OlenaPianykh/Garage48KAPU
KAPU/IssuesViewController.swift
1
2777
// // IssuesViewController.swift // KAPU // // Created by Andrii Verbovetskyi on 3/4/17. // Copyright © 2017 Vasyl Khmil. All rights reserved. // import UIKit class IssuesViewController: UIViewController { @IBOutlet var table: UITableView! let kapus = KapuLoader() var selectedKapuIndex: Int = 0 override func viewDidLoad() { super.viewDidLoad() setUpNotificationCenter() kapus.getKapusFromFB{ self.table.reloadData() } } override func viewWillAppear(_ animated: Bool) { kapus.getKapusFromFB { self.table.reloadData() } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } func setUpNotificationCenter() { NotificationCenter.default.addObserver(self, selector: #selector(IssuesViewController.updateKapus), name: NSNotification.Name(rawValue: "KapusWereUpdated"), object:nil) } func updateKapus() { self.table.reloadData() } } extension IssuesViewController :UITableViewDelegate{ func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat{ return 187 } } extension IssuesViewController :UITableViewDataSource{ func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int{ return kapus.allKapus.count } public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{ let cell = tableView.dequeueReusableCell(withIdentifier: "IssueCell", for: indexPath) as! IssueTableViewCell let kapu = kapus.allKapus[indexPath.row] cell.categoryLabel.text = kapu.categoryName cell.issueDescriptionLabel.text = kapu.title cell.authorLabel.text = kapu.creatorName cell.dateLabel.text = kapu.creationDate cell.issuePicture.image = kapu.image return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { // goToKapuDetails self.selectedKapuIndex = indexPath.row // performSegue(withIdentifier: "goToKapuDetails", sender: nil) } // This function is called before the segue override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // get a reference to the second view controller let secondViewController = segue.destination as! KapuViewController // set a variable in the second view controller with the data to pass secondViewController.kapu = self.kapus.allKapus[self.selectedKapuIndex] } }
mit
d5ac6285b1a49e4a9d0e9ba5e1701a55
30.191011
116
0.643372
4.729131
false
false
false
false
blstream/StudyBox_iOS
StudyBox_iOS/DecksViewCell.swift
1
1255
// // DecksViewCell.swift // StudyBox_iOS // // Created by Piotr Zielinski on 07.03.2016. // Copyright © 2016 BLStream. All rights reserved. // import UIKit class DecksViewCell: UICollectionViewCell { @IBOutlet weak var deckNameLabel: UILabel! @IBOutlet weak var deckFlashcardsCountLabel: UILabel! private(set) var borderLayer: CAShapeLayer? = nil func setupBorderLayer() { if borderLayer == nil { borderLayer = CAShapeLayer() if let borderLayer = borderLayer { contentView.layer.insertSublayer(borderLayer, below: deckNameLabel.layer) } borderLayer?.strokeColor = UIColor.sb_Graphite().CGColor borderLayer?.fillColor = nil borderLayer?.lineDashPattern = [10, 5] } reloadBorderLayer(forCellSize: bounds.size) } func reloadBorderLayer(forCellSize size: CGSize) { let rect = CGRect(origin: CGPoint(x: 0, y: 0), size: size) borderLayer?.path = UIBezierPath(rect: rect).CGPath borderLayer?.frame = rect borderLayer?.setNeedsDisplay() } func removeBorderLayer() { borderLayer?.removeFromSuperlayer() borderLayer = nil } }
apache-2.0
b617a618093c45afe1c8bf4b8cc12549
28.162791
89
0.628389
4.78626
false
false
false
false
erndev/BeaconsHouse
BeaconsHouse/ViewController.swift
1
4833
// // ViewController.swift // BeaconsHouse // // Created by Ernesto García on 01/11/15. // Copyright © 2015 erndev. All rights reserved. // import UIKit enum HouseRoomMinor : UInt, CustomStringConvertible { case LivingRoom = 5 case BedRoom = 6 case Kitchen = 7 var description:String { var str = "" switch self { case .LivingRoom: str = "Living Room" case .BedRoom: str = "Bedroom" case .Kitchen: str = "Kitchen" } return str } } class ViewController: UITableViewController { struct Constants { static let BeaconSection = 1 static let LocationRow = 0 static let MinorRow = 1 } @IBOutlet var locationImageView:UIImageView! @IBOutlet var locationTextField:UILabel! @IBOutlet var swithButton:UISwitch! let beaconManager = HouseBeaconsManager() var shouldAutoStartAfterAuthorization = false var currentRoom:HouseRoomMinor? override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. tableView.separatorInset = UIEdgeInsetsZero tableView.layoutMargins = UIEdgeInsetsZero beaconManager.delegate = self updateInfo() } func updateMinorText(text:String ) { updateDetailText(text, inRow: Constants.MinorRow, section: Constants.BeaconSection ) } func updateDetailText( text:String, inRow row:Int, section:Int ) { if let cell = tableView.cellForRowAtIndexPath(NSIndexPath(forRow: row, inSection: section) ) { cell.detailTextLabel?.text = text } } @IBAction func switchToggled( sender:UISwitch ) { if( swithButton.on ) { if beaconManager.authorization() == .NotDetermined { beaconManager.requestAuthorization() shouldAutoStartAfterAuthorization = true sender.on = false return } start() } else { stop() } } func start() { beaconManager.start() } func stop() { beaconManager.stop() swithButton.on = false updateInfo() } func updateInfo(room:HouseRoomMinor?=nil) { var minorText = "" var roomImage = UIImage(named: swithButton.on ? "walk" : "switch" ) var roomName = swithButton.on ? "Walk to find Beacons" : "Enable scanning to find Beacons" if let room = room { minorText = String(room.rawValue) roomName = room.description roomImage = UIImage(named: "room-" + minorText ) } updateMinorText(minorText) UIView.transitionWithView(locationImageView, duration:0.4, options: .TransitionCrossDissolve, animations: { () -> Void in self.locationImageView.image = roomImage }, completion: nil) locationTextField.text = roomName currentRoom = room tableView .beginUpdates() tableView.endUpdates() } override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { if( indexPath.row == Constants.MinorRow && currentRoom == nil ) { return 0 } return super.tableView(tableView , heightForRowAtIndexPath: indexPath) } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = super.tableView(tableView, cellForRowAtIndexPath: indexPath) cell.layoutMargins = UIEdgeInsetsZero return cell } } extension ViewController : HouseBeaconsDelegate { func errorScanning(error: NSError) { NSOperationQueue.mainQueue().addOperationWithBlock { () -> Void in self.swithButton.on = false self.stop() let errorController = UIAlertController(title: "Error scanning", message: error.localizedDescription, preferredStyle: .Alert) errorController.addAction(UIAlertAction(title: "Ok", style: .Default, handler: nil)) self.presentViewController(errorController, animated: true, completion: nil) } } func foundBeacons(beacons: [UInt]) { NSOperationQueue.mainQueue().addOperationWithBlock { () -> Void in var room:HouseRoomMinor? // Just get the first known beacon for beacon in beacons { if let beaconRoom = HouseRoomMinor(rawValue: beacon) { print("Found beacon in \(beaconRoom.description)") room = beaconRoom break } } self.updateInfo(room) } } func coreLocationAuthorization( status:Status ) { NSOperationQueue.mainQueue().addOperationWithBlock { () -> Void in self.swithButton.enabled = (status != .NotAuthorized) if( status == .Authorized && self.shouldAutoStartAfterAuthorization ) { self.start() } self.shouldAutoStartAfterAuthorization = false } } }
mit
2f6aa0d6db28a08e4b08a9a997fd7069
23.774359
132
0.657421
4.654143
false
false
false
false
practicalswift/swift
benchmark/single-source/TwoSum.swift
22
3882
//===--- TwoSum.swift -----------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // This test is solves 2SUM problem: // Given an array and a number C, find elements A and B such that A+B = C import TestsUtils public let TwoSum = BenchmarkInfo( name: "TwoSum", runFunction: run_TwoSum, tags: [.validation, .api, .Dictionary, .Array, .algorithm], legacyFactor: 2) let array = [ 959, 81, 670, 727, 416, 171, 401, 398, 707, 596, 200, 9, 414, 98, 43, 352, 752, 158, 593, 418, 240, 912, 542, 445, 429, 456, 993, 618, 52, 649, 759, 190, 126, 306, 966, 37, 787, 981, 606, 372, 597, 901, 158, 284, 809, 820, 173, 538, 644, 428, 932, 967, 962, 959, 233, 467, 220, 8, 729, 889, 277, 494, 554, 670, 91, 657, 606, 248, 644, 8, 366, 815, 567, 993, 696, 763, 800, 531, 301, 863, 680, 703, 279, 388, 871, 124, 302, 617, 410, 366, 813, 599, 543, 508, 336, 312, 212, 86, 524, 64, 641, 533, 207, 893, 146, 534, 104, 888, 534, 464, 423, 583, 365, 420, 642, 514, 336, 974, 846, 437, 604, 121, 180, 794, 278, 467, 818, 603, 537, 167, 169, 704, 9, 843, 555, 154, 598, 566, 676, 682, 828, 128, 875, 445, 918, 505, 393, 571, 3, 406, 719, 165, 505, 750, 396, 726, 404, 391, 532, 403, 728, 240, 89, 917, 665, 561, 282, 302, 438, 714, 6, 290, 939, 200, 788, 128, 773, 900, 934, 772, 130, 884, 60, 870, 812, 750, 349, 35, 155, 905, 595, 806, 771, 443, 304, 283, 404, 905, 861, 820, 338, 380, 709, 927, 42, 478, 789, 656, 106, 218, 412, 453, 262, 864, 701, 686, 770, 34, 624, 597, 843, 913, 966, 230, 942, 112, 991, 299, 669, 399, 630, 943, 934, 448, 62, 745, 917, 397, 440, 286, 875, 22, 989, 235, 732, 906, 923, 643, 853, 68, 48, 524, 86, 89, 688, 224, 546, 73, 963, 755, 413, 524, 680, 472, 19, 996, 81, 100, 338, 626, 911, 358, 887, 242, 159, 731, 494, 985, 83, 597, 98, 270, 909, 828, 988, 684, 622, 499, 932, 299, 449, 888, 533, 801, 844, 940, 642, 501, 513, 735, 674, 211, 394, 635, 372, 213, 618, 280, 792, 487, 605, 755, 584, 163, 358, 249, 784, 153, 166, 685, 264, 457, 677, 824, 391, 830, 310, 629, 591, 62, 265, 373, 195, 803, 756, 601, 592, 843, 184, 220, 155, 396, 828, 303, 553, 778, 477, 735, 430, 93, 464, 306, 579, 828, 759, 809, 916, 759, 336, 926, 776, 111, 746, 217, 585, 441, 928, 236, 959, 417, 268, 200, 231, 181, 228, 627, 675, 814, 534, 90, 665, 1, 604, 479, 598, 109, 370, 719, 786, 700, 591, 536, 7, 147, 648, 864, 162, 404, 536, 768, 175, 517, 394, 14, 945, 865, 490, 630, 963, 49, 904, 277, 16, 349, 301, 840, 817, 590, 738, 357, 199, 581, 601, 33, 659, 951, 640, 126, 302, 632, 265, 894, 892, 587, 274, 487, 499, 789, 954, 652, 825, 512, 170, 882, 269, 471, 571, 185, 364, 217, 427, 38, 715, 950, 808, 270, 746, 830, 501, 264, 581, 211, 466, 970, 395, 610, 930, 885, 696, 568, 920, 487, 764, 896, 903, 241, 894, 773, 896, 341, 126, 22, 420, 959, 691, 207, 745, 126, 873, 341, 166, 127, 108, 426, 497, 681, 796, 430, 367, 363 ] @inline(never) public func run_TwoSum(_ N: Int) { var i1: Int? var i2: Int? var Dict: Dictionary<Int, Int> = [:] for _ in 1...N { for Sum in 500..<600 { Dict = [:] i1 = nil i2 = nil for n in 0..<array.count { if let m = Dict[Sum-array[n]] { i1 = m i2 = n break } Dict[array[n]] = n } CheckResults(i1 != nil && i2 != nil) CheckResults(Sum == array[i1!] + array[i2!]) } } }
apache-2.0
69f9b75ce6d342c2305536660cdbb138
46.341463
80
0.556157
2.486867
false
false
false
false
practicalswift/swift
test/SILGen/apply_abstraction_nested.swift
6
1068
// RUN: %target-swift-frontend -enable-sil-ownership -emit-silgen %s | %FileCheck %s infix operator ~> protocol P { } func bar<T:P>(_: inout T) -> (()) -> () { return {_ in ()} } func baz<T:P>(_: inout T) -> (Int) -> () { return {_ in ()} } func ~> <T: P, Args, Result>( x: inout T, m: (_ x: inout T) -> ((Args) -> Result) ) -> ((Args) -> Result) { return m(&x) } struct X : P {} var a = X() (a~>bar)(()) // CHECK: [[CHAINED_FUNC:%.*]] = apply {{%.*}}<X, (), ()>({{%.*}}, {{%.*}}) : $@convention(thin) <τ_0_0, τ_0_1, τ_0_2 where τ_0_0 : P> (@inout τ_0_0, @noescape @callee_guaranteed (@inout τ_0_0) -> @owned @callee_guaranteed (@in_guaranteed τ_0_1) -> @out τ_0_2) -> @owned @callee_guaranteed (@in_guaranteed τ_0_1) -> @out τ_0_2 // CHECK: [[REABSTRACT:%.*]] = function_ref @$sytytIegnr_Ieg_TR // CHECK: [[CHAINED_FUNC_REABSTRACTED:%.*]] = partial_apply [callee_guaranteed] [[REABSTRACT]]([[CHAINED_FUNC]]) // CHECK: [[BORROW:%.*]] = begin_borrow [[CHAINED_FUNC_REABSTRACTED]] // CHECK: apply [[BORROW]]() : $@callee_guaranteed () -> ()
apache-2.0
3ccd42fa96f3da5bdbc6e3e285af2345
38.185185
327
0.549149
2.81383
false
false
false
false
nathantannar4/Parse-Dashboard-for-iOS-Pro
Parse Dashboard for iOS/ViewControllers/Core/Server/ServerDetailViewController.swift
1
5123
// // ServerDetailViewController.swift // Parse Dashboard for iOS // // Copyright © 2017 Nathan Tannar. // // 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. // // Created by Nathan Tannar on 9/5/17. // import UIKit class ServerDetailViewController: TableViewController { // MARK: - Properties var server: PFServer enum ViewStyle { case json, formatted } var viewStyle = ViewStyle.formatted // MARK: - Initialization init(_ server: PFServer) { self.server = server super.init(nibName: nil, bundle: nil) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: - View Life Cycle override func viewDidLoad() { super.viewDidLoad() setupTableView() setupNavigationBar() } // MARK: Data Refresh @objc func handleRefresh() { ParseLite.shared.get("/serverInfo") { [weak self] (result, json) in defer { self?.tableView.refreshControl?.endRefreshing() } guard result.success, let json = json else { self?.handleError(result.error) return } self?.server = PFServer(json) self?.tableView.reloadData() } } // MARK: - Setup private func setupTableView() { tableView.contentInset.top = 10 tableView.contentInset.bottom = 30 tableView.backgroundColor = .lightBlueBackground tableView.separatorStyle = .singleLine tableView.rowHeight = UITableViewAutomaticDimension tableView.estimatedRowHeight = 100 tableView.tableFooterView = UIView() tableView.register(FieldCell.self, forCellReuseIdentifier: FieldCell.reuseIdentifier) let rc = UIRefreshControl() rc.tintColor = .white rc.attributedTitle = NSAttributedString(string: "Pull to Refresh", attributes: [.foregroundColor : UIColor.white, .font: UIFont.boldSystemFont(ofSize: 12)]) rc.addTarget(self, action: #selector(handleRefresh), for: .valueChanged) tableView.refreshControl = rc } private func setupNavigationBar() { title = ParseLite.shared.currentConfiguration?.name ?? "Current Configuration" subtitle = "Server Info" navigationItem.rightBarButtonItem = UIBarButtonItem(image: UIImage(named: "Raw"), style: .plain, target: self, action: #selector(toggleView(sender:))) } // MARK: - User Actions @objc func toggleView(sender: UIBarButtonItem) { switch viewStyle { case .json: sender.image = UIImage(named: "Raw") viewStyle = .formatted tableView.reloadSections([0], with: .automatic) case .formatted: sender.image = UIImage(named: "Raw_Filled") viewStyle = .json tableView.reloadSections([0], with: .automatic) } } // MARK: - UITableViewDatasource override func numberOfSections(in tableView: UITableView) -> Int { return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return viewStyle == .formatted ? server.keys.count : 1 } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { guard let cell = tableView.dequeueReusableCell(withIdentifier: FieldCell.reuseIdentifier, for: indexPath) as? FieldCell else { fatalError() } if viewStyle == .formatted { cell.key = server.keys[indexPath.row] cell.value = server.values[indexPath.row] return cell } else { cell.key = "JSON" cell.value = server.json } return cell } }
mit
fd8f1e70544002e83685c12c29735703
34.082192
164
0.618508
5.081349
false
false
false
false
fthomasmorel/insapp-iOS
Insapp/TutorialPageViewController.swift
1
1675
// // TutorialPageViewController.swift // Insapp // // Created by Florent THOMAS-MOREL on 9/20/16. // Copyright © 2016 Florent THOMAS-MOREL. All rights reserved. // import Foundation import UIKit class TutorialPageViewController: UIViewController{ @IBOutlet weak var titleLabel: UILabel! @IBOutlet weak var descriptionLabel: UILabel! @IBOutlet weak var imageView: UIImageView! @IBOutlet weak var button: UIButton! var completion:Optional<((String)->())> = nil var pageName: String! var index:Int! override func viewDidLoad() { super.viewDidLoad() } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) guard button != nil else { return } let animation = CABasicAnimation(keyPath: "transform.rotation.z") animation.duration = 0.08 animation.repeatCount = 5 animation.autoreverses = true animation.fromValue = NSNumber(value: -5 * Float.pi / 180 ) animation.toValue = NSNumber(value: 5 * Float.pi / 180 ) animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut) button.layer.add(animation, forKey: "position") UIView.animate(withDuration: 0.5, animations: { self.button.transform = CGAffineTransform(scaleX: 1.5, y: 1.5) }) { (finished) in UIView.animate(withDuration: 0.5, animations: { self.button.transform = CGAffineTransform(scaleX: 1, y: 1) }) } } @IBAction func completionAction(_ sender: AnyObject) { self.completion?(self.pageName) } }
mit
93d8ca4640227d9182922e074aead071
31.823529
99
0.643369
4.61157
false
false
false
false
zmian/xcore.swift
Sources/Xcore/Cocoa/Extensions/FileManager+Extensions.swift
1
4288
// // Xcore // Copyright © 2014 Xcore // MIT license, see LICENSE file for details // import Foundation extension FileManager { public struct CreationOptions { public let resourceValue: URLResourceValues? public let attributes: [FileAttributeKey: Any]? public init(resourceValue: URLResourceValues?, attributes: [FileAttributeKey: Any]? = nil) { self.resourceValue = resourceValue self.attributes = attributes } public static var none: Self { .init(resourceValue: nil, attributes: nil) } /// Excluded from iCloud Backup with `nil` attributes. public static var excludedFromBackup: Self { // Exclude from iCloud Backup var resourceValue = URLResourceValues() resourceValue.isExcludedFromBackup = true return .init(resourceValue: resourceValue) } /// Excluded from iCloud Backup with file protection of type `.complete`. /// /// The file is stored in an encrypted format on disk and cannot be read from or /// written to while the device is locked or booting. public static var secure: Self { // Exclude from iCloud Backup var resourceValue = URLResourceValues() resourceValue.isExcludedFromBackup = true return .init( resourceValue: resourceValue, attributes: [.protectionKey: FileProtectionType.complete] ) } } /// Returns a `URL` constructed by appending the given path component relative /// to the specified directory. /// /// - Parameters: /// - path: The path component to add. /// - directory: The directory in which the given `path` is constructed. /// - options: The options that are applied to when appending path. See /// `FileManager.Options` for possible values. The default value is `.none`. /// - Returns: Returns a `URL` constructed by appending the given path component /// relative to the specified directory. open func appending( path: String, relativeTo directory: SearchPathDirectory, options: CreationOptions ) throws -> URL { var directoryUrl = try url( for: directory, in: .userDomainMask, appropriateFor: nil, create: true ) .appendingPathComponent(path, isDirectory: true) try createDirectory( at: directoryUrl, withIntermediateDirectories: true, attributes: options.attributes ) if let resourceValue = options.resourceValue { try directoryUrl.setResourceValues(resourceValue) } return directoryUrl } } extension FileManager { open func url(path: String, relativeTo directory: SearchPathDirectory, isDirectory: Bool = true) -> URL? { url(for: directory)? .appendingPathComponent(path, isDirectory: isDirectory) } /// Removes the file or directory relative to the given directory. @discardableResult open func removeItem(_ path: String, relativeTo directory: SearchPathDirectory, isDirectory: Bool = true) -> Bool { guard var directoryUrl = url(for: directory) else { // No need to remove as it doesn't exists. return true } directoryUrl = directoryUrl.appendingPathComponent(path, isDirectory: isDirectory) do { try removeItem(at: directoryUrl) return true } catch { return false } } /// Returns the first URL for the specified common directory in the user domain. open func url(for directory: SearchPathDirectory) -> URL? { urls(for: directory, in: .userDomainMask).first } /// Remove all cached data from `cachesDirectory`. public func removeAllCache() throws { try urls(for: .cachesDirectory, in: .userDomainMask).forEach { directory in try removeItem(at: directory) } } } extension FileManager { var xcoreCacheDirectory: URL? { try? appending( path: "com.xcore", relativeTo: .cachesDirectory, options: .secure ) } }
mit
105b3beea3419c435292d101f7eb2cc5
32.232558
119
0.619314
5.35875
false
false
false
false
Skyscanner/SkyFloatingLabelTextField
SkyFloatingLabelTextField/SkyFloatingLabelTextFieldExample/Example4b/AppearanceViewController.swift
1
2195
// Copyright 2016-2019 Skyscanner 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 UIKit class AppearanceViewController: UIViewController { @IBOutlet weak var label: SkyFloatingLabelTextField! @IBOutlet weak var iconLabel: SkyFloatingLabelTextFieldWithIcon! @IBOutlet weak var addErrorButton: UIButton! override func viewDidLoad() { super.viewDidLoad() iconLabel.iconText = "\u{f072}" } @IBAction func resignFirstResponder(_ sender: UIButton) { label.resignFirstResponder() } @IBAction func addError(_ sender: UIButton) { let localizedAddError = NSLocalizedString( "Add error", tableName: "SkyFloatingLabelTextField", comment: "add error button title" ) if addErrorButton?.title(for: .normal) == localizedAddError { label.errorMessage = NSLocalizedString( "error message", tableName: "SkyFloatingLabelTextField", comment: "error message" ) addErrorButton.setTitle( NSLocalizedString( "Clear error", tableName: "SkyFloatingLabelTextField", comment: "clear errors button title" ), for: .normal ) } else { label.errorMessage = "" addErrorButton?.setTitle( NSLocalizedString( "Add error", tableName: "SkyFloatingLabelTextField", comment: "add error button title" ), for: .normal ) } } }
apache-2.0
49b1e535fa72492df97184effde125b8
33.84127
94
0.599544
5.176887
false
false
false
false
newlix/swift-callapi
CallAPI.swift
1
2306
import Foundation private let JWT_KEY = "CALLAPI.JWT_KEY" public class CallAPI { public let URL:NSURL public let settings:[String:AnyObject]? public var JWT:String? { get { return NSUserDefaults.standardUserDefaults().stringForKey(JWT_KEY) } set { NSUserDefaults.standardUserDefaults().setValue(newValue, forKey: JWT_KEY) } } public init(URLString:String, settings:[String:AnyObject]? = nil) { self.URL = NSURL(string: URLString)! self.settings = settings } public func call(name:String, params: [String:AnyObject]) throws -> AnyObject? { let semaphore = dispatch_semaphore_create(0) let request = NSMutableURLRequest(URL: NSURL(string: name, relativeToURL: URL)!) print(request.URL) request.cachePolicy = .ReloadIgnoringLocalCacheData request.HTTPBody = try NSJSONSerialization.dataWithJSONObject(params, options: NSJSONWritingOptions()) request.HTTPMethod = "POST" request.addValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type") request.addValue("json", forHTTPHeaderField:"Data-Type") if let JWT = JWT { request.addValue("Bearer \(JWT)", forHTTPHeaderField: "Authorization") } let session = NSURLSession(configuration: NSURLSessionConfiguration.defaultSessionConfiguration()) var data:NSData? var error:NSError? var response:NSURLResponse? let task = session.dataTaskWithRequest(request) { (_data, _response, _error) -> Void in print(data) data = _data response = _response error = _error dispatch_semaphore_signal(semaphore) } task.resume() dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER) let statusCode = (response as? NSHTTPURLResponse)?.statusCode if error == nil && statusCode == 200 { if let data = data { return try? NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions()) } else { return nil } } throw APIError( request: request, response: response, statusCode: statusCode, error: error) } }
mit
4790734bc8ac1c28b0b3311df0819d68
36.803279
110
0.628361
5.079295
false
false
false
false
zhiquan911/chance_btc_wallet
chance_btc_wallet/Pods/ESPullToRefresh/Sources/ESRefreshComponent.swift
3
7435
// // ESRefreshComponent.swift // // Created by egg swift on 16/4/7. // Copyright (c) 2013-2016 ESPullToRefresh (https://github.com/eggswift/pull-to-refresh) // // 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 UIKit public typealias ESRefreshHandler = (() -> ()) open class ESRefreshComponent: UIView { open weak var scrollView: UIScrollView? /// @param handler Refresh callback method open var handler: ESRefreshHandler? /// @param animator Animated view refresh controls, custom must comply with the following two protocol open var animator: (ESRefreshProtocol & ESRefreshAnimatorProtocol)! /// @param refreshing or not fileprivate var _isRefreshing = false open var isRefreshing: Bool { get { return self._isRefreshing } } /// @param auto refreshing or not fileprivate var _isAutoRefreshing = false open var isAutoRefreshing: Bool { get { return self._isAutoRefreshing } } /// @param tag observing fileprivate var isObservingScrollView = false fileprivate var isIgnoreObserving = false public override init(frame: CGRect) { super.init(frame: frame) autoresizingMask = [.flexibleLeftMargin, .flexibleWidth, .flexibleRightMargin] } public convenience init(frame: CGRect, handler: @escaping ESRefreshHandler) { self.init(frame: frame) self.handler = handler self.animator = ESRefreshAnimator.init() } public convenience init(frame: CGRect, handler: @escaping ESRefreshHandler, animator: ESRefreshProtocol & ESRefreshAnimatorProtocol) { self.init(frame: frame) self.handler = handler self.animator = animator } public required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } deinit { removeObserver() } open override func willMove(toSuperview newSuperview: UIView?) { super.willMove(toSuperview: newSuperview) /// Remove observer from superview immediately self.removeObserver() DispatchQueue.main.async { [weak self, newSuperview] in /// Add observer to new superview in next runloop self?.addObserver(newSuperview) } } open override func didMoveToSuperview() { super.didMoveToSuperview() self.scrollView = self.superview as? UIScrollView if let _ = animator { let v = animator.view if v.superview == nil { let inset = animator.insets self.addSubview(v) v.frame = CGRect.init(x: inset.left, y: inset.right, width: self.bounds.size.width - inset.left - inset.right, height: self.bounds.size.height - inset.top - inset.bottom) v.autoresizingMask = [ .flexibleWidth, .flexibleTopMargin, .flexibleHeight, .flexibleBottomMargin ] } } } // MARK: - Action public final func startRefreshing(isAuto: Bool = false) -> Void { guard isRefreshing == false && isAutoRefreshing == false else { return } _isRefreshing = !isAuto _isAutoRefreshing = isAuto self.start() } public final func stopRefreshing() -> Void { guard isRefreshing == true || isAutoRefreshing == true else { return } self.stop() } public func start() { } public func stop() { _isRefreshing = false _isAutoRefreshing = false } // ScrollView contentSize change action public func sizeChangeAction(object: AnyObject?, change: [NSKeyValueChangeKey : Any]?) { } // ScrollView offset change action public func offsetChangeAction(object: AnyObject?, change: [NSKeyValueChangeKey : Any]?) { } } extension ESRefreshComponent /* KVO methods */ { fileprivate static var context = "ESRefreshKVOContext" fileprivate static let offsetKeyPath = "contentOffset" fileprivate static let contentSizeKeyPath = "contentSize" public func ignoreObserver(_ ignore: Bool = false) { if let scrollView = scrollView { scrollView.isScrollEnabled = !ignore } isIgnoreObserving = ignore } fileprivate func addObserver(_ view: UIView?) { if let scrollView = view as? UIScrollView, !isObservingScrollView { scrollView.addObserver(self, forKeyPath: ESRefreshComponent.offsetKeyPath, options: [.initial, .new], context: &ESRefreshComponent.context) scrollView.addObserver(self, forKeyPath: ESRefreshComponent.contentSizeKeyPath, options: [.initial, .new], context: &ESRefreshComponent.context) isObservingScrollView = true } } fileprivate func removeObserver() { if let scrollView = superview as? UIScrollView, isObservingScrollView { scrollView.removeObserver(self, forKeyPath: ESRefreshComponent.offsetKeyPath, context: &ESRefreshComponent.context) scrollView.removeObserver(self, forKeyPath: ESRefreshComponent.contentSizeKeyPath, context: &ESRefreshComponent.context) isObservingScrollView = false } } override open func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) { if context == &ESRefreshComponent.context { guard isUserInteractionEnabled == true && isHidden == false else { return } if keyPath == ESRefreshComponent.contentSizeKeyPath { if isIgnoreObserving == false { sizeChangeAction(object: object as AnyObject?, change: change) } } else if keyPath == ESRefreshComponent.offsetKeyPath { if isIgnoreObserving == false { offsetChangeAction(object: object as AnyObject?, change: change) } } } else { } } }
mit
5a631d66ffb65a69c7f60919e3b3412a
34.574163
156
0.627976
5.284293
false
false
false
false
SunLiner/Floral
Floral/Floral/Classes/Malls/Address/Controller/AddressListViewController.swift
1
6731
// // AddressListViewController.swift // Floral // // Created by 孙林 on 16/6/4. // Copyright © 2016年 ALin. All rights reserved. // import UIKit // 地址改变通知 let AddressChangeNotify = "AddressChangeNotify" // 地址改变通知useinfo的key let AddressChangeNotifyKey = "address" // 重用标识符 private let AddressCellReuseIdentifier = "AddressCellReuseIdentifier" class AddressListViewController: UITableViewController, UIAlertViewDelegate { // 上一页已经选中了的地址ID var selectedID : String? var refresh : Bool = false { didSet{ if refresh { getAddressList() } } } var addresses : [Address]? { didSet{ if let _ = addresses { tableView.reloadData() } } } // 正在操作的地址 private var selectedAddress : Address? override func viewDidLoad() { super.viewDidLoad() getAddressList() setup() } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) KeyWindow.addSubview(addAddressBtn) addAddressBtn.snp_makeConstraints { (make) in make.centerX.equalTo(KeyWindow) make.bottom.equalTo(-15) } } override func viewWillDisappear(animated: Bool) { super.viewWillDisappear(animated) addAddressBtn.removeFromSuperview() } // 获取地址列表 private func getAddressList() { showHudInView(view, hint: "正在加载...", yOffset: 0) NetworkTool.sharedTools.getAddressList { [unowned self](addresses, error) in self.hideHud() if error != nil{ self.showHint("网络异常", duration: 2.0, yOffset: 0) }else{ self.addresses = addresses } } } static var g_self : AddressListViewController? // 基本设置 private func setup() { AddressListViewController.g_self = self navigationItem.title = "收货地址" tableView.registerClass(AddressViewCell.self, forCellReuseIdentifier: AddressCellReuseIdentifier) tableView.tableFooterView = UIView() tableView.separatorColor = .None // 添加新增按钮 tableView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: 50, right: 0) } // MARK: - Table view data source override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return addresses?.count ?? 0 } override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return (addresses?.count ?? 0)>0 ? addresses![indexPath.row].cellHeight : 83 } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier(AddressCellReuseIdentifier) as! AddressViewCell let count = addresses?.count ?? 0 if count > 0{ let address = addresses![indexPath.row] cell.selectedAddress = selectedID == address.fnId cell.address = address } return cell } // MARK: - Table view data delegate override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { let count = addresses?.count ?? 0 if indexPath.row == count - 1 { // 自提地址不能删除, 系统默认的地址 return false } return true } override func tableView(tableView: UITableView, editActionsForRowAtIndexPath indexPath: NSIndexPath) -> [UITableViewRowAction]? { let address = self.addresses![indexPath.row] selectedAddress = address let delete = UITableViewRowAction(style: .Destructive, title: "删除") { (_, indexpath) in // 删除地址 NetworkTool.sharedTools.deleteAddress(address.fnId!, finished: { (isDelete) in if isDelete{ self.showHint("删除成功", duration: 2.0, yOffset: 0) // 重新请求地址列表 self.getAddressList() }else{ self.showHint("操作失败", duration: 2.0, yOffset: 0) } }) } delete.backgroundColor = UIColor.redColor() let update = UITableViewRowAction(style: .Normal, title: "修改") { (_, indexpath) in self.toAddVc(true) } update.backgroundColor = UIColor.blueColor() let setDefault = UITableViewRowAction(style: .Default, title: "设置成默认") { (_, indexpath) in UIAlertView(title: "花田小憩", message: "是否设置成默认地址?", delegate: self, cancelButtonTitle: "取消", otherButtonTitles: "设置").show() } setDefault.backgroundColor = UIColor.greenColor() return [delete, update, setDefault] } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { NSNotificationCenter.defaultCenter().postNotificationName(AddressChangeNotify, object: nil, userInfo: [AddressChangeNotifyKey : addresses![indexPath.row]]) navigationController?.popViewControllerAnimated(false) } // MARK: - UIAlertViewDelegate func alertView(alertView: UIAlertView, clickedButtonAtIndex buttonIndex: Int) { if buttonIndex == 1 { // 设置成默认的地址 NetworkTool.sharedTools.setDefaultAddress(selectedAddress!.fnId!, finished: { (isOk) in isOk ? self.showHint("操作成功", duration: 2.0, yOffset: 0) : self.showHint("操作失败", duration: 2.0, yOffset: 0) // 左滑动自动消失 self.tableView.reloadData() }) } } // MARK: - 懒加载 /// 新增地址按钮 private lazy var addAddressBtn = UIButton(title: nil, imageName: "f_addAdress_278x35", target: g_self!, selector: #selector(AddressListViewController.clickAdd), font: nil, titleColor: nil) /// 点击新增按钮 @objc private func clickAdd() { toAddVc(false) } private func toAddVc(isUpdate: Bool) { let addVc = AddAddressViewController() if isUpdate { addVc.updateAddress = selectedAddress! } navigationController?.pushViewController(addVc, animated: true) } }
mit
a53c39cb8627675f865e76cc167464f6
31.313131
192
0.601282
4.902682
false
false
false
false
kesun421/firefox-ios
Client/Frontend/Browser/NightModeHelper.swift
2
2082
/* 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 WebKit import Shared struct NightModePrefsKey { static let NightModeButtonIsInMenu = PrefsKeys.KeyNightModeButtonIsInMenu static let NightModeStatus = PrefsKeys.KeyNightModeStatus } class NightModeHelper: TabHelper { fileprivate weak var tab: Tab? required init(tab: Tab) { self.tab = tab if let path = Bundle.main.path(forResource: "NightModeHelper", ofType: "js"), let source = try? NSString(contentsOfFile: path, encoding: String.Encoding.utf8.rawValue) as String { let userScript = WKUserScript(source: source, injectionTime: WKUserScriptInjectionTime.atDocumentStart, forMainFrameOnly: true) tab.webView!.configuration.userContentController.addUserScript(userScript) } } static func name() -> String { return "NightMode" } func scriptMessageHandlerName() -> String? { return "NightMode" } func userContentController(_ userContentController: WKUserContentController, didReceiveScriptMessage message: WKScriptMessage) { // Do nothing. } static func toggle(_ prefs: Prefs, tabManager: TabManager) { let isActive = prefs.boolForKey(NightModePrefsKey.NightModeStatus) ?? false setNightMode(prefs, tabManager: tabManager, enabled: !isActive) } static func setNightMode(_ prefs: Prefs, tabManager: TabManager, enabled: Bool) { prefs.setBool(enabled, forKey: NightModePrefsKey.NightModeStatus) for tab in tabManager.tabs { tab.setNightMode(enabled) } } static func isActivated(_ prefs: Prefs) -> Bool { return prefs.boolForKey(NightModePrefsKey.NightModeStatus) ?? false } } class NightModeAccessors { static func isNightMode(_ prefs: Prefs) -> Bool { return prefs.boolForKey(NightModePrefsKey.NightModeStatus) ?? false } }
mpl-2.0
791d45db0671596b863a0f596b426517
34.896552
187
0.702209
4.853147
false
false
false
false
Visual-Engineering/HiringApp
HiringApp/HiringAppCore/Providers/APIProvider.swift
1
3596
// // APIProvider.swift // Pods // // Created by Alba Luján on 21/6/17. // // import Foundation import BSWFoundation import Deferred import Decodable import KeychainSwift enum APIError: Error { case badStatusCode(errorCode: Int) case errorWhileParsing case responseUnexpected } protocol DroskyType { func performRequest(forEndpoint endpoint: Endpoint) -> Task<DroskyResponse> } extension Drosky: DroskyType {} protocol APIProviderType { func retrieveTechnologies() -> Task<[TechnologyModel]> } class APIProvider: APIProviderType { let drosky: DroskyType init(drosky: DroskyType = Drosky(environment: EnvironmentType.development)) { self.drosky = drosky } func retrieveTechnologies() -> Task<[TechnologyModel]> { let statusCodeTask = performRequest(endpoint: AppEndpoints.technologies) let modelTask: Task<[TechnologyModel]> = statusCodeTask.andThen(upon: .global(), start: parse) return modelTask } func performLogin() -> Task<String> { let statusCodeTask = performRequest(endpoint: AppEndpoints.authenticate) let modelTask = statusCodeTask.andThen(upon: .global()) { (data) -> Task<String> in guard let json = try JSONSerialization.jsonObject(with: data, options: []) as? Dictionary<String, Any>, let token = json["authToken"] as? String else { return Task(failure: APIError.errorWhileParsing) } let keychain = KeychainSwift() keychain.set(token, forKey: "userToken") return Task(success: token) } return modelTask } func performContact(candidate: CandidateModel) -> Task<(Data)> { let statusCodeTask = performRequest(endpoint: AppEndpoints.candidate(parameters: candidate.dict as [String : AnyObject])) return statusCodeTask } func retrieveTopics(technologyId: Int) -> Task<[TopicModel]> { let statusCodeTask = performRequest(endpoint: AppEndpoints.topics(technologyId: technologyId)) let modelTask: Task<[TopicModel]> = statusCodeTask.andThen(upon: .global(), start: parse) return modelTask } func performRequest(endpoint: Endpoint) -> Task<Data> { //perform a request let droskyTask = drosky.performRequest(forEndpoint: endpoint) //check the status code of the response let statusCodeTask = droskyTask.andThen(upon: .global(), start: checkStatusCode) return statusCodeTask } func checkStatusCode(fromDroskyResponse droskyResponse: DroskyResponse) -> Task<Data> { //Check if status code is in range od 200s guard droskyResponse.statusCode >= 200 && droskyResponse.statusCode < 300 else { return Task(failure: APIError.badStatusCode(errorCode: droskyResponse.statusCode)) } return Task(success: droskyResponse.data) } func parse<T:Decodable>(data: Data) -> Task<T> { guard let json = try? JSONSerialization.jsonObject(with: data, options: []), let data = try? T.decode(json) else { return Task(failure: APIError.errorWhileParsing) } return Task(success: data) } func parse<T: Decodable>(data: Data) -> Task<[T]> { guard let json = try? JSONSerialization.jsonObject(with: data, options: []), let data = try? [T].decode(json) else { return Task(failure: APIError.errorWhileParsing) } return Task(success: data) } }
apache-2.0
40ea9011bbd71148fe6700ba650255c7
32.915094
129
0.649513
4.394866
false
false
false
false
raymondshadow/SwiftDemo
SwiftApp/Pods/RxSwift/RxSwift/Observables/Concat.swift
4
4824
// // Concat.swift // RxSwift // // Created by Krunoslav Zaher on 3/21/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // extension ObservableType { /** Concatenates the second observable sequence to `self` upon successful termination of `self`. - seealso: [concat operator on reactivex.io](http://reactivex.io/documentation/operators/concat.html) - parameter second: Second observable sequence. - returns: An observable sequence that contains the elements of `self`, followed by those of the second sequence. */ public func concat<O: ObservableConvertibleType>(_ second: O) -> Observable<E> where O.E == E { return Observable.concat([self.asObservable(), second.asObservable()]) } } extension ObservableType { /** Concatenates all observable sequences in the given sequence, as long as the previous observable sequence terminated successfully. This operator has tail recursive optimizations that will prevent stack overflow. Optimizations will be performed in cases equivalent to following: [1, [2, [3, .....].concat()].concat].concat() - seealso: [concat operator on reactivex.io](http://reactivex.io/documentation/operators/concat.html) - returns: An observable sequence that contains the elements of each given sequence, in sequential order. */ public static func concat<S: Sequence >(_ sequence: S) -> Observable<E> where S.Iterator.Element == Observable<E> { return Concat(sources: sequence, count: nil) } /** Concatenates all observable sequences in the given collection, as long as the previous observable sequence terminated successfully. This operator has tail recursive optimizations that will prevent stack overflow. Optimizations will be performed in cases equivalent to following: [1, [2, [3, .....].concat()].concat].concat() - seealso: [concat operator on reactivex.io](http://reactivex.io/documentation/operators/concat.html) - returns: An observable sequence that contains the elements of each given sequence, in sequential order. */ public static func concat<S: Collection >(_ collection: S) -> Observable<E> where S.Iterator.Element == Observable<E> { return Concat(sources: collection, count: Int64(collection.count)) } /** Concatenates all observable sequences in the given collection, as long as the previous observable sequence terminated successfully. This operator has tail recursive optimizations that will prevent stack overflow. Optimizations will be performed in cases equivalent to following: [1, [2, [3, .....].concat()].concat].concat() - seealso: [concat operator on reactivex.io](http://reactivex.io/documentation/operators/concat.html) - returns: An observable sequence that contains the elements of each given sequence, in sequential order. */ public static func concat(_ sources: Observable<E> ...) -> Observable<E> { return Concat(sources: sources, count: Int64(sources.count)) } } final private class ConcatSink<S: Sequence, O: ObserverType> : TailRecursiveSink<S, O> , ObserverType where S.Iterator.Element: ObservableConvertibleType, S.Iterator.Element.E == O.E { typealias Element = O.E override init(observer: O, cancel: Cancelable) { super.init(observer: observer, cancel: cancel) } func on(_ event: Event<Element>){ switch event { case .next: self.forwardOn(event) case .error: self.forwardOn(event) self.dispose() case .completed: self.schedule(.moveNext) } } override func subscribeToNext(_ source: Observable<E>) -> Disposable { return source.subscribe(self) } override func extract(_ observable: Observable<E>) -> SequenceGenerator? { if let source = observable as? Concat<S> { return (source._sources.makeIterator(), source._count) } else { return nil } } } final private class Concat<S: Sequence>: Producer<S.Iterator.Element.E> where S.Iterator.Element: ObservableConvertibleType { typealias Element = S.Iterator.Element.E fileprivate let _sources: S fileprivate let _count: IntMax? init(sources: S, count: IntMax?) { self._sources = sources self._count = count } override func run<O: ObserverType>(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == Element { let sink = ConcatSink<S, O>(observer: observer, cancel: cancel) let subscription = sink.run((self._sources.makeIterator(), self._count)) return (sink: sink, subscription: subscription) } }
apache-2.0
c6fe6232dc34a7eb43702dc6e3b9766f
35.816794
144
0.674062
4.6375
false
false
false
false
TENDIGI/Obsidian-iOS-SDK
Obsidian-iOS-SDK/Response.swift
1
1025
// // Response.swift // ObsidianSDK // // Created by Nick Lee on 7/1/15. // Copyright (c) 2015 TENDIGI, LLC. All rights reserved. // import Foundation /// The Response enum defines three possible states for a request's completion public enum Response<T: Mappable> { /// The request was completed successfully case Success(Results<T>) /// The request failed with a server-side error case ServerError(Results<Error>) /// The request failed with a locally-generated error case LocalError(NSError) internal init(dict: [String : AnyObject], headers: [String : String]) { let results = Results<T>(dict: dict, headers: headers) self = .Success(results) } internal init(serverError: [String : AnyObject], headers: [String : String]) { let results = Results<Error>(dict: serverError, headers: headers) self = .ServerError(results) } internal init(localError: NSError) { self = .LocalError(localError) } }
mit
b5e5a94edba137b8596dd9d8ff0d002b
26.702703
82
0.646829
4.166667
false
false
false
false
ifeherva/HSTracker
HSTracker/Logging/CoreManager.swift
1
14070
/* * This file is part of the HSTracker package. * (c) Benjamin Michotte <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. * * Created on 13/02/16. */ import Foundation //import HearthAssets import HearthMirror enum HearthstoneLogError: Error { case canNotCreateDir, canNotReadFile, canNotCreateFile } struct HearthstoneRunState { var isRunning = false var isActive = false init(isRunning: Bool, isActive: Bool) { self.isRunning = isRunning self.isActive = isActive } } final class CoreManager: NSObject { static let applicationName = "Hearthstone" var logReaderManager: LogReaderManager! //static var assetGenerator: HearthAssets? // watchers let packWatcher = PackWatcher() let game: Game var queue = DispatchQueue(label: "be.michotte.hstracker.readers", attributes: []) override init() { self.game = Game(hearthstoneRunState: HearthstoneRunState(isRunning: CoreManager.isHearthstoneRunning(), isActive: CoreManager.isHearthstoneActive())) super.init() logReaderManager = LogReaderManager(logPath: Settings.hearthstonePath, coreManager: self) /*if CoreManager.assetGenerator == nil && Settings.useHearthstoneAssets { let path = Settings.hearthstonePath CoreManager.assetGenerator = try? HearthAssets(path: path) CoreManager.assetGenerator?.locale = (Settings.hearthstoneLanguage ?? .enUS).rawValue }*/ } static func validatedHearthstonePath(_ path: String = "\(Settings.hearthstonePath)/Hearthstone.app") -> Bool { let exists = FileManager.default.fileExists(atPath: path) AppHealth.instance.setHSInstalled(flag: exists) return exists } // MARK: - Initialisation func start() { startListeners() if CoreManager.isHearthstoneRunning() { logger.info("Hearthstone is running, starting trackers now.") startTracking() } } /** Configures Hearthstone app logging so we can read them */ func setup() throws -> Bool { let fileManager = FileManager.default let requireVerbose = [LogLineNamespace.power] // make sure the path exists let dir = NSString(string: configPath).deletingLastPathComponent logger.verbose("Check if \(dir) exists") var isDir: ObjCBool = false if !fileManager.fileExists(atPath: dir, isDirectory: &isDir) || !isDir.boolValue { do { logger.verbose("Creating \(dir)") try fileManager.createDirectory(atPath: dir, withIntermediateDirectories: true, attributes: nil) } catch let error as NSError { AppHealth.instance.setLoggerWorks(flag: false) logger.error("\(error.description)") throw HearthstoneLogError.canNotCreateDir } } let zones = LogLineNamespace.usedValues() var missingZones: [LogLineZone] = [] logger.verbose("Check if \(configPath) exists") if !fileManager.fileExists(atPath: configPath) { for zone in zones { missingZones.append(LogLineZone(namespace: zone)) } } else { var fileContent: String? do { fileContent = try String(contentsOfFile: configPath) } catch { logger.error("\(error)") } if let fileContent = fileContent { var zonesFound: [LogLineZone] = [] let splittedZones = fileContent.components(separatedBy: "[") .map { $0.replacingOccurrences(of: "]", with: "") .components(separatedBy: "\n") .filter { !$0.isEmpty } } .filter { !$0.isEmpty } for splittedZone in splittedZones { var zoneData = splittedZone.filter { !$0.isBlank } if zoneData.count < 1 { continue } let zone = zoneData.removeFirst() if let currentZone = LogLineNamespace(rawValue: zone) { let logLineZone = LogLineZone(namespace: currentZone) logLineZone.requireVerbose = requireVerbose.contains(currentZone) for line in zoneData { let kv = line.components(separatedBy: "=") if let key = kv.first, let value = kv.last { switch key { case "LogLevel": logLineZone.logLevel = Int(value) ?? 1 case "FilePrinting": logLineZone.filePrinting = value case "ConsolePrinting": logLineZone.consolePrinting = value case "ScreenPrinting": logLineZone.screenPrinting = value case "Verbose": logLineZone.verbose = value == "true" default: break } } } zonesFound.append(logLineZone) } } logger.verbose("Zones found : \(zonesFound)") for zone in zones { var currentZoneFound: LogLineZone? for zoneFound in zonesFound where zoneFound.namespace == zone { currentZoneFound = zoneFound break } if let currentZone = currentZoneFound { logger.verbose("Is \(currentZone.namespace) valid ? " + "\(currentZone.isValid())") if !currentZone.isValid() { missingZones.append(currentZone) } } else { logger.verbose("Zone \(zone) is missing") missingZones.append(LogLineZone(namespace: zone)) } } } } logger.verbose("Missing zones : \(missingZones)") if !missingZones.isEmpty { var fileContent: String = "" for zone in zones { let logZone = LogLineZone(namespace: zone) logZone.requireVerbose = requireVerbose.contains(zone) fileContent += logZone.toString() } do { try fileContent.write(toFile: configPath, atomically: true, encoding: .utf8) } catch { logger.error("\(error)") throw HearthstoneLogError.canNotCreateFile } if CoreManager.isHearthstoneRunning() { AppHealth.instance.setLoggerWorks(flag: false) return false } } AppHealth.instance.setLoggerWorks(flag: true) return true } func startTracking() { // Starting logreaders after short delay is as game might be still in loading state let time = DispatchTime.now() + .seconds(1) DispatchQueue.main.asyncAfter(deadline: time) { [unowned(unsafe) self] in logger.info("Start Tracking") self.logReaderManager.start() } } func stopTracking() { logger.info("Stop Tracking") logReaderManager.stop(eraseLogFile: !CoreManager.isHearthstoneRunning()) DeckWatcher.stop() ArenaDeckWatcher.stop() MirrorHelper.destroy() } // MARK: - Events func startListeners() { let notificationCenter = NSWorkspace.shared.notificationCenter let notifications = [ NSWorkspace.activeSpaceDidChangeNotification: #selector(spaceChange), NSWorkspace.didLaunchApplicationNotification: #selector(appLaunched(_:)), NSWorkspace.didTerminateApplicationNotification: #selector(appTerminated(_:)), NSWorkspace.didActivateApplicationNotification: #selector(appActivated(_:)), NSWorkspace.didDeactivateApplicationNotification: #selector(appDeactivated(_:)) ] for (name, selector) in notifications { notificationCenter.addObserver(self, selector: selector, name: name, object: nil) } } @objc func spaceChange() { logger.verbose("Receive space changed event") NotificationCenter.default .post(name: Notification.Name(rawValue: Events.space_changed), object: nil) } @objc func appLaunched(_ notification: Notification) { if let app = notification.userInfo!["NSWorkspaceApplicationKey"] as? NSRunningApplication, app.localizedName == CoreManager.applicationName { logger.verbose("Hearthstone is now launched") self.startTracking() self.game.setHearthstoneRunning(flag: true) NotificationCenter.default.post(name: Notification.Name(rawValue: Events.hearthstone_running), object: nil) } } @objc func appTerminated(_ notification: Notification) { if let app = notification.userInfo!["NSWorkspaceApplicationKey"] as? NSRunningApplication, app.localizedName == CoreManager.applicationName { logger.verbose("Hearthstone is now closed") self.stopTracking() self.game.setHearthstoneRunning(flag: false) AppHealth.instance.setHearthstoneRunning(flag: false) if Settings.quitWhenHearthstoneCloses { NSApplication.shared.terminate(self) } else { logger.info("Not closing app since setting says so.") } } } @objc func appActivated(_ notification: Notification) { if let app = notification.userInfo!["NSWorkspaceApplicationKey"] as? NSRunningApplication { if app.localizedName == CoreManager.applicationName { NotificationCenter.default.post(name: Notification.Name(rawValue: Events.hearthstone_active), object: nil) // TODO: add observer here as well self.game.setHearthstoneActived(flag: true) self.game.setSelfActivated(flag: false) } if app.bundleIdentifier == Bundle.main.bundleIdentifier { self.game.setSelfActivated(flag: true) } } } @objc func appDeactivated(_ notification: Notification) { if let app = notification.userInfo!["NSWorkspaceApplicationKey"] as? NSRunningApplication { if app.localizedName == CoreManager.applicationName { self.game.setHearthstoneActived(flag: false) } if app.bundleIdentifier == Bundle.main.bundleIdentifier { self.game.setSelfActivated(flag: false) } } } static func bringHSToFront() { if let hsapp = CoreManager.hearthstoneApp { hsapp.activate(options: NSApplication.ActivationOptions.activateIgnoringOtherApps) } } // MARK: - Paths / Utils var configPath: String { return NSString(string: "~/Library/Preferences/Blizzard/Hearthstone/log.config") .expandingTildeInPath } private static func isHearthstoneRunning() -> Bool { return CoreManager.hearthstoneApp != nil } static var hearthstoneApp: NSRunningApplication? { let apps = NSWorkspace.shared.runningApplications return apps.first { $0.bundleIdentifier == "unity.Blizzard Entertainment.Hearthstone" } } static func isHearthstoneActive() -> Bool { return CoreManager.hearthstoneApp?.isActive ?? false } // MARK: - Deck detection static func autoDetectDeck(mode: Mode) -> Deck? { let selectedModes: [Mode] = [.tavern_brawl, .tournament, .friendly, .adventure, .gameplay] if selectedModes.contains(mode) { logger.info("Trying to import deck from Hearthstone") var selectedDeckId: Int64 = 0 if let selectedId = MirrorHelper.getSelectedDeck() { selectedDeckId = selectedId logger.info("Found selected deck id via mirror: \(selectedDeckId)") } else { selectedDeckId = DeckWatcher.selectedDeckId logger.info("Found selected deck id via watcher: \(selectedDeckId)") } if selectedDeckId <= 0 { if mode != .tavern_brawl { return nil } } if let decks = MirrorHelper.getDecks() { guard let selectedDeck = decks.first(where: { $0.id as? Int64 ?? 0 == selectedDeckId }) else { logger.warning("No deck with id=\(selectedDeckId) found") return nil } logger.info("Found selected deck : \(selectedDeck.name)") if let deck = RealmHelper.checkAndUpdateDeck(deckId: selectedDeckId, selectedDeck: selectedDeck) { return deck } // deck does not exist, add it return RealmHelper.add(mirrorDeck: selectedDeck) } else { logger.warning("Mirror returned no decks") return nil } } else if mode == .draft { logger.info("Trying to import arena deck from Hearthstone") var hsMirrorDeck: MirrorDeck? if let mDeck = MirrorHelper.getArenaDeck()?.deck { hsMirrorDeck = mDeck } else { hsMirrorDeck = ArenaDeckWatcher.selectedDeck } guard let hsDeck = hsMirrorDeck else { logger.warning("Can't get arena deck") return nil } return RealmHelper.checkOrCreateArenaDeck(mirrorDeck: hsDeck) } logger.error("Auto-importing deck of \(mode) is not supported") return nil } }
mit
77f3bc2f2b79a5b6c97ebfb46a5856e6
36.026316
122
0.581095
5.107078
false
false
false
false
qvacua/vimr
Commons/Sources/Commons/ConditionVariable.swift
1
746
/** * Tae Won Ha - http://taewon.de - @hataewon * See LICENSE */ import Foundation public final class ConditionVariable { private(set) var posted: Bool public init(posted: Bool = false) { self.posted = posted } public func wait(for seconds: TimeInterval, then fn: (() -> Void)? = nil) { self.condition.lock() defer { self.condition.unlock() } while !self.posted { self.condition.wait(until: Date(timeIntervalSinceNow: seconds)) self.posted = true } fn?() } public func broadcast(then fn: (() -> Void)? = nil) { self.condition.lock() defer { self.condition.unlock() } self.posted = true self.condition.broadcast() fn?() } private let condition = NSCondition() }
mit
dfb340004117f5634520831a1fc183ac
18.631579
77
0.624665
3.825641
false
false
false
false
Carthage/Commandant
Tests/CommandantTests/OptionsWithEnumProtocolSpec.swift
2
10261
// // OptionsWithEnumProtocolSpec.swift // Commandant // // Created by Vitalii Budnik on 11/22/17. // Copyright © 2017 Carthage. All rights reserved. // @testable import Commandant import Foundation import Nimble import Quick class OptionsWithEnumProtocolSpec: QuickSpec { override func spec() { describe("CommandMode.Arguments") { func tryArguments(_ arguments: String...) -> Result<TestEnumOptions, CommandantError<Never>> { return TestEnumOptions.evaluate(.arguments(ArgumentParser(arguments))) } it("should fail if a required argument is missing") { expect(tryArguments().value).to(beNil()) } it("should fail if an option is missing a value") { expect(tryArguments("required", "--strictIntValue").value).to(beNil()) } it("should fail if an option is missing a value") { expect(tryArguments("required", "--strictStringValue", "drop").value).to(beNil()) } it("should fail if an optional strict int parameter is wrong") { expect(tryArguments("required", "256").value).to(beNil()) } it("should succeed without optional string arguments") { let value = tryArguments("required").value let expected = TestEnumOptions(strictIntValue: .theAnswerToTheUltimateQuestionOfLifeTheUniverseAndEverything, strictStringValue: .foobar, strictStringsArray: [], optionalStrictStringsArray: nil, optionalStrictStringValue: nil, optionalStrictInt: .min, requiredName: "required", arguments: []) expect(value).to(equal(expected)) } it("should succeed without optional strict int value") { let value = tryArguments("required", "5").value let expected = TestEnumOptions(strictIntValue: .theAnswerToTheUltimateQuestionOfLifeTheUniverseAndEverything, strictStringValue: .foobar, strictStringsArray: [], optionalStrictStringsArray: nil, optionalStrictStringValue: nil, optionalStrictInt: .giveFive, requiredName: "required", arguments: []) expect(value).to(equal(expected)) } it("should succeed with some strings array arguments separated by comma") { let value = tryArguments("required", "--strictIntValue", "3", "--optionalStrictStringValue", "baz", "255", "--strictStringsArray", "a,b,c").value let expected = TestEnumOptions(strictIntValue: .three, strictStringValue: .foobar, strictStringsArray: [.a, .b, .c], optionalStrictStringsArray: nil, optionalStrictStringValue: .baz, optionalStrictInt: .max, requiredName: "required", arguments: []) expect(value).to(equal(expected)) } it("should succeed with some strings array arguments separated by space") { let value = tryArguments("required", "--strictIntValue", "3", "--optionalStrictStringValue", "baz", "--strictStringsArray", "a b c", "255").value let expected = TestEnumOptions(strictIntValue: .three, strictStringValue: .foobar, strictStringsArray: [.a, .b, .c], optionalStrictStringsArray: nil, optionalStrictStringValue: .baz, optionalStrictInt: .max, requiredName: "required", arguments: []) expect(value).to(equal(expected)) } it("should succeed with some strings array arguments separated by comma and space") { let value = tryArguments("required", "--strictIntValue", "3", "--optionalStrictStringValue", "baz", "--strictStringsArray", "a, b, c", "255").value let expected = TestEnumOptions(strictIntValue: .three, strictStringValue: .foobar, strictStringsArray: [.a, .b, .c], optionalStrictStringsArray: nil, optionalStrictStringValue: .baz, optionalStrictInt: .max, requiredName: "required", arguments: []) expect(value).to(equal(expected)) } it("should succeed with some optional string arguments") { let value = tryArguments("required", "--strictIntValue", "3", "--optionalStrictStringValue", "baz", "255").value let expected = TestEnumOptions(strictIntValue: .three, strictStringValue: .foobar, strictStringsArray: [], optionalStrictStringsArray: nil, optionalStrictStringValue: .baz, optionalStrictInt: .max, requiredName: "required", arguments: []) expect(value).to(equal(expected)) } it("should succeed without optional array arguments") { let value = tryArguments("required").value let expected = TestEnumOptions(strictIntValue: .theAnswerToTheUltimateQuestionOfLifeTheUniverseAndEverything, strictStringValue: .foobar, strictStringsArray: [], optionalStrictStringsArray: nil, optionalStrictStringValue: nil, optionalStrictInt: .min, requiredName: "required", arguments: []) expect(value).to(equal(expected)) } it("should succeed with some optional array arguments") { let value = tryArguments("required", "--strictIntValue", "3", "--optionalStrictStringsArray", "one, two", "255").value let expected = TestEnumOptions(strictIntValue: .three, strictStringValue: .foobar, strictStringsArray: [], optionalStrictStringsArray: [.one, .two], optionalStrictStringValue: nil, optionalStrictInt: .max, requiredName: "required", arguments: []) expect(value).to(equal(expected)) } it("should override previous optional arguments") { let value = tryArguments("required", "--strictIntValue", "3", "--strictStringValue", "fuzzbuzz", "--strictIntValue", "5", "--strictStringValue", "bazbuzz").value let expected = TestEnumOptions(strictIntValue: .giveFive, strictStringValue: .bazbuzz, strictStringsArray: [], optionalStrictStringsArray: nil, optionalStrictStringValue: nil, optionalStrictInt: .min, requiredName: "required", arguments: []) expect(value).to(equal(expected)) } it("should consume the rest of positional arguments") { let value = tryArguments("required", "255", "value1", "value2").value let expected = TestEnumOptions(strictIntValue: .theAnswerToTheUltimateQuestionOfLifeTheUniverseAndEverything, strictStringValue: .foobar, strictStringsArray: [], optionalStrictStringsArray: nil, optionalStrictStringValue: nil, optionalStrictInt: .max, requiredName: "required", arguments: [ "value1", "value2" ]) expect(value).to(equal(expected)) } it("should treat -- as the end of valued options") { let value = tryArguments("--", "--strictIntValue").value let expected = TestEnumOptions(strictIntValue: .theAnswerToTheUltimateQuestionOfLifeTheUniverseAndEverything, strictStringValue: .foobar, strictStringsArray: [], optionalStrictStringsArray: nil, optionalStrictStringValue: nil, optionalStrictInt: .min, requiredName: "--strictIntValue", arguments: []) expect(value).to(equal(expected)) } } describe("CommandMode.Usage") { it("should return an error containing usage information") { let error = TestEnumOptions.evaluate(.usage).error expect(error?.description).to(contain("strictIntValue")) expect(error?.description).to(contain("strictStringValue")) expect(error?.description).to(contain("name you're required to")) expect(error?.description).to(contain("optionally specify")) } } } } struct TestEnumOptions: OptionsProtocol, Equatable { let strictIntValue: StrictIntValue let strictStringValue: StrictStringValue let strictStringsArray: [StrictStringValue] let optionalStrictStringsArray: [StrictStringValue]? let optionalStrictStringValue: StrictStringValue? let optionalStrictInt: StrictIntValue let requiredName: String let arguments: [String] typealias ClientError = Never static func create(_ a: StrictIntValue) -> (StrictStringValue) -> ([StrictStringValue]) -> ([StrictStringValue]?) -> (StrictStringValue?) -> (String) -> (StrictIntValue) -> ([String]) -> TestEnumOptions { return { b in { c in { d in { e in { f in { g in { h in return self.init(strictIntValue: a, strictStringValue: b, strictStringsArray: c, optionalStrictStringsArray: d, optionalStrictStringValue: e, optionalStrictInt: g, requiredName: f, arguments: h) } } } } } } } } static func evaluate(_ m: CommandMode) -> Result<TestEnumOptions, CommandantError<Never>> { return create <*> m <| Option(key: "strictIntValue", defaultValue: .theAnswerToTheUltimateQuestionOfLifeTheUniverseAndEverything, usage: "`0` - zero, `255` - max, `3` - three, `5` - five or `42` - The Answer") <*> m <| Option(key: "strictStringValue", defaultValue: .foobar, usage: "`foobar`, `bazbuzzz`, `a`, `b`, `c`, `one`, `two`, `c`") <*> m <| Option<[StrictStringValue]>(key: "strictStringsArray", defaultValue: [], usage: "Some array of arguments") <*> m <| Option<[StrictStringValue]?>(key: "optionalStrictStringsArray", defaultValue: nil, usage: "Some array of arguments") <*> m <| Option<StrictStringValue?>(key: "optionalStrictStringValue", defaultValue: nil, usage: "Some string value") <*> m <| Argument(usage: "A name you're required to specify") <*> m <| Argument(defaultValue: .min, usage: "A number that you can optionally specify") <*> m <| Argument(defaultValue: [], usage: "An argument list that consumes the rest of positional arguments") } } func ==(lhs: TestEnumOptions, rhs: TestEnumOptions) -> Bool { return lhs.strictIntValue == rhs.strictIntValue && lhs.strictStringValue == rhs.strictStringValue && lhs.strictStringsArray == rhs.strictStringsArray && lhs.optionalStrictStringsArray == rhs.optionalStrictStringsArray && lhs.optionalStrictStringValue == rhs.optionalStrictStringValue && lhs.optionalStrictInt == rhs.optionalStrictInt && lhs.requiredName == rhs.requiredName && lhs.arguments == rhs.arguments } extension TestEnumOptions: CustomStringConvertible { var description: String { return "{ strictIntValue: \(strictIntValue), strictStringValue: \(strictStringValue), strictStringsArray: \(strictStringsArray), optionalStrictStringsArray: \(String(describing: optionalStrictStringsArray)), optionalStrictStringValue: \(String(describing: optionalStrictStringValue)), optionalStrictInt: \(optionalStrictInt), requiredName: \(requiredName), arguments: \(arguments) }" } } enum StrictStringValue: String, ArgumentProtocol { static var name: String = "Strict string value: `foobar`, `bazbuzz`, `one`, `two`, `baz`, `a`, `b` or `c`" case foobar case bazbuzz case one case two case baz case a case b case c } enum StrictIntValue: UInt8, ArgumentProtocol { static var name: String = "Strict int value: `3`, `5`, `42`, `0`, `255`" case min = 0 case three = 3 case giveFive = 5 case theAnswerToTheUltimateQuestionOfLifeTheUniverseAndEverything = 42 case max = 255 }
mit
4db7c30a622e9efac51167681d10516a
56.640449
408
0.736355
4.020376
false
true
false
false
cdmx/MiniMancera
miniMancera/Model/Option/WhistlesVsZombies/Points/MOptionWhistlesVsZombiesPointsItemStrategyWait.swift
1
1189
import Foundation class MOptionWhistlesVsZombiesPointsItemStrategyWait:MGameStrategy< MOptionWhistlesVsZombiesPointsItem, MOptionWhistlesVsZombies> { private var startingTime:TimeInterval? private let kDuration:TimeInterval = 1.5 override func update( elapsedTime:TimeInterval, scene:ViewGameScene<MOptionWhistlesVsZombies>) { if let startingTime:TimeInterval = self.startingTime { let deltaTime:TimeInterval = elapsedTime - startingTime if deltaTime > kDuration { model.fade() } } else { startingTime = elapsedTime addView(scene:scene) } } //MARK: private private func addView(scene:ViewGameScene<MOptionWhistlesVsZombies>) { guard let scene:VOptionWhistlesVsZombiesScene = scene as? VOptionWhistlesVsZombiesScene, let modelZombie:MOptionWhistlesVsZombiesZombieItem = model.modelZombie else { return } scene.addPoints(model:model, modelZombie:modelZombie) } }
mit
c57ba430a91431fad0d6f574d7d80087
24.847826
94
0.607233
5.688995
false
false
false
false
alexsosn/ConvNetSwift
ConvNetSwiftTests/UtilTests.swift
1
4195
// // UtilTests.swift // ConvNetSwift // // Created by Alex on 11/24/15. // Copyright © 2015 OWL. All rights reserved. // import XCTest class UtilTests: XCTestCase { func testImageConversion() { guard let image = UIImage(named: "Nyura.png") else { print("error: no image found on provided path") XCTAssert(false) return } let vol = image.toVol()! let newImage = vol.toImage() XCTAssertNotNil(newImage) let newVol = newImage!.toVol()! XCTAssertEqual(vol.w.count, newVol.w.count) for i: Int in 0 ..< vol.w.count { let equals = vol.w[i] == newVol.w[i] XCTAssert(equals) if !equals { print(vol.w[i], i) print(newVol.w[i], i) break } } } func testImgToArrayAndBackAgain() { guard let img = UIImage(named: "Nyura.png") else { print("error: no image found on provided path") XCTAssert(false) return } guard let image = img.cgImage else { print("error: no image found") XCTAssert(false) return } let width = image.width let height = image.height let components = 4 let bytesPerRow = (components * width) let bitsPerComponent: Int = 8 let pixels = calloc(height * width, MemoryLayout<UInt32>.size) let bitmapInfo: CGBitmapInfo = CGBitmapInfo(rawValue: CGImageAlphaInfo.premultipliedLast.rawValue | CGBitmapInfo.byteOrder32Big.rawValue) let colorSpace = CGColorSpaceCreateDeviceRGB() let context = CGContext( data: pixels, width: width, height: height, bitsPerComponent: bitsPerComponent, bytesPerRow: bytesPerRow, space: colorSpace, bitmapInfo: bitmapInfo.rawValue) context?.draw(image, in: CGRect(x: 0, y: 0, width: CGFloat(width), height: CGFloat(height))) let dataCtxt = context?.data let data = Data(bytesNoCopy: UnsafeMutableRawPointer(dataCtxt)!, count: width*height*components, deallocator: .free) var pixelMem = [UInt8](repeating: 0, count: data.count) (data as NSData).getBytes(&pixelMem, length: data.count) let doubleNormArray = pixelMem.map { (elem: UInt8) -> Double in return Double(elem)/255.0 } let vol = Vol(width: width, height: height, depth: components, array: doubleNormArray) //=========================// for i in 0..<vol.sx { for j in 0..<vol.sy{ if i<vol.sx/2 && j<vol.sy/2 { vol.set(x: i, y: j, d: 0, v: 0.75) } if i>vol.sx/2 && j<vol.sy/2 { vol.set(x: i, y: j, d: 1, v: 0.75) } if i<vol.sx/2 && j>vol.sy/2 { vol.set(x: i, y: j, d: 2, v: 0.75) } if i>vol.sx/2 && j>vol.sy/2 { vol.set(x: i, y: j, d: 3, v: 0.5) } } } let intDenormArray: [UInt8] = vol.w.map { (elem: Double) -> UInt8 in return UInt8(elem * 255.0) } let bitsPerPixel = bitsPerComponent * components let providerRef = CGDataProvider( data: Data(bytes: UnsafePointer<UInt8>(intDenormArray), count: intDenormArray.count * components) as CFData ) let cgim = CGImage( width: width, height: height, bitsPerComponent: bitsPerComponent, bitsPerPixel: bitsPerPixel, bytesPerRow: bytesPerRow, space: colorSpace, bitmapInfo: bitmapInfo, provider: providerRef!, decode: nil, shouldInterpolate: false, intent: .defaultIntent ) let newImage = UIImage(cgImage: cgim!) print(newImage) } }
mit
41a9356f6ca1714e1c30499792a96638
30.772727
145
0.505484
4.400839
false
false
false
false
temoki/TortoiseGraphics
PlaygroundBook/Sources/Core/Color+Palette.swift
1
1413
import Foundation extension Color { // https://material.io/guidelines/style/color.html public static let black = Color("000000", name: "black") public static let white = Color("FFFFFF", name: "white") public static let red = Color("F44336", name: "red") public static let pink = Color("E91E63", name: "pink") public static let purple = Color("9C27B0", name: "purple") public static let deepPurple = Color("673AB7", name: "deepPurple") public static let indigo = Color("3F51B5", name: "indigo") public static let blue = Color("2196F3", name: "blue") public static let lightBlue = Color("03A9F4", name: "lightBlue") public static let cyan = Color("00BCD4", name: "cyan") public static let teal = Color("009688", name: "teal") public static let green = Color("4CAF50", name: "green") public static let lightGreen = Color("8BC34A", name: "lightGreen") public static let lime = Color("CDDC39", name: "lime") public static let yellow = Color("FFEB3B", name: "yellow") public static let amber = Color("FFC107", name: "amber") public static let orange = Color("FF9800", name: "orange") public static let deepOrange = Color("FF5722", name: "deepOrange") public static let brown = Color("795548", name: "brown") public static let grey = Color("9E9E9E", name: "grey") public static let blueGrey = Color("607D8B", name: "blueGrey") }
mit
46039b58c68bbd769b91eccabf5d5fc1
49.464286
70
0.66879
3.632391
false
false
false
false
xiabob/ZhiHuDaily
ZhiHuDaily/Pods/SwiftDate/Sources/SwiftDate/Commons.swift
2
7987
// // SwiftDate, Full featured Swift date library for parsing, validating, manipulating, and formatting dates and timezones. // Created by: Daniele Margutti // Main contributors: Jeroen Houtzager // // // 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 /// This define the weekdays /// /// - sunday: sunday /// - monday: monday /// - tuesday: tuesday /// - wednesday: wednesday /// - thursday: thursday /// - friday: friday /// - saturday: saturday public enum WeekDay: Int { case sunday = 1 case monday = 2 case tuesday = 3 case wednesday = 4 case thursday = 5 case friday = 6 case saturday = 7 } /// Provide a mechanism to create and return local-thread object you can share. /// /// Basically you assign a key to the object and return the initializated instance in `create` /// block. Again this code is used internally to provide a common way to create local-thread date /// formatter as like `NSDateFormatter` (which is expensive to create) or /// `NSDateComponentsFormatter`. /// Instance is saved automatically into current thread own dictionary. /// /// - parameter key: identification string of the object /// - parameter create: creation block. At the end of the block you need to provide the instance you /// want to save. /// /// - returns: the instance you have created into the current thread internal func localThreadSingleton<T: AnyObject>(key: String, create: (Void) -> T) -> T { if let cachedObj = Thread.current.threadDictionary[key] as? T { return cachedObj } else { let newObject = create() Thread.current .threadDictionary[key] = newObject return newObject } } /// This is the list of all possible errors you can get from the library /// /// - FailedToParse: Failed to parse a specific date using provided format /// - FailedToCalculate: Failed to calculate new date from passed parameters /// - MissingCalTzOrLoc: Provided components does not include a valid TimeZone or Locale /// - DifferentCalendar: Provided dates are expressed in different calendars and cannot be compared /// - MissingRsrcBundle: Missing SwiftDate resource bundle /// - FailedToSetComponent: Failed to set a calendar com public enum DateError: Error { case FailedToParse case FailedToCalculate case MissingCalTzOrLoc case DifferentCalendar case MissingRsrcBundle case FailedToSetComponent(Calendar.Component) case InvalidLocalizationFile } /// Available date formats used to parse strings and format date into string /// /// - custom: custom format expressed in Unicode tr35-31 (see http://www.unicode.org/reports/tr35/tr35-31/tr35-dates.html#Date_Format_Patterns and Apple's Date Formatting Guide). Formatter uses heuristics to guess the date if it's invalid. /// This may end in a wrong parsed date. Use `strict` to disable heuristics parsing. /// - strict: strict format is like custom but does not apply heuristics to guess at the date which is intended by the string. /// So, if you pass an invalid date (like 1999-02-31) formatter fails instead of returning guessing date (in our case /// 1999-03-03). /// - iso8601: iso8601 date format (see https://en.wikipedia.org/wiki/ISO_8601) /// - extended: extended date format ("eee dd-MMM-yyyy GG HH:mm:ss.SSS zzz") /// - rss: RSS and AltRSS date format /// - dotNET: .NET date format public enum DateFormat { case custom(String) case strict(String) case iso8601(options: ISO8601DateTimeFormatter.Options) case extended case rss(alt: Bool) case dotNET } /// This struct group the options you can choose to output a string which represent /// the interval between two dates. public struct ComponentsFormatterOptions { /// The default formatting behavior. When using positional units, this behavior drops leading zeroes but pads middle and trailing values with zeros as needed. For example, with hours, minutes, and seconds displayed, the value for one hour and 10 seconds is “1:00:10”. For all other unit styles, this behavior drops all units whose values are 0. For example, when days, hours, minutes, and seconds are allowed, the abbreviated version of one hour and 10 seconds is displayed as “1h 10s”.* public var zeroBehavior: DateComponentsFormatter.ZeroFormattingBehavior = .pad // The maximum number of time units to include in the output string. // By default is nil, which does not cause the elimination of any units. public var maxUnitCount: Int? = nil // Configures the strings to use (if any) for unit names such as days, hours, minutes, and seconds. // By default is `positional`. public var style: DateComponentsFormatter.UnitsStyle = .positional // Setting this property to true results in output strings like “30 minutes remaining”. The default value of this property is false. public var includeTimeRemaining: Bool = false /// The bitmask of calendrical units such as day and month to include in the output string /// Allowed components are: `year,month,weekOfMonth,day,hour,minute,second`. /// By default it's set as nil which means set automatically based upon the interval. public var allowedUnits: NSCalendar.Unit? = nil /// The locale to use to format the string. /// If `ComponentsFormatterOptions` is used from a `TimeInterval` object the default value /// value is set to the current device's locale. /// If `ComponentsFormatterOptions` is used from a `DateInRegion` object the default value /// is set the `DateInRegion`'s locale. public var locale: Locale = LocaleName.current.locale /// Initialize a new ComponentsFormatterOptions struct /// - parameter allowedUnits: allowed units or nil if you want to keep the default value /// - parameter style: units style or nil if you want to keep the default value /// - parameter zero: zero behavior or nil if you want to keep the default value public init(allowedUnits: NSCalendar.Unit? = nil, style: DateComponentsFormatter.UnitsStyle? = nil, zero: DateComponentsFormatter.ZeroFormattingBehavior? = nil) { if allowedUnits != nil { self.allowedUnits = allowedUnits! } if style != nil { self.style = style! } if zero != nil { self.zeroBehavior = zero! } } /// Evaluate the best allowed units to workaround NSException of the DateComponentsFormatter internal func bestAllowedUnits(forInterval interval: TimeInterval) -> NSCalendar.Unit { switch interval { case 0...(SECONDS_IN_MINUTE-1): return [.second] case SECONDS_IN_MINUTE...(SECONDS_IN_HOUR-1): return [.minute,.second] case SECONDS_IN_HOUR...(SECONDS_IN_DAY-1): return [.hour,.minute,.second] case SECONDS_IN_DAY...(SECONDS_IN_WEEK-1): return [.day,.hour,.minute,.second] default: return [.year,.month,.weekOfMonth,.day,.hour,.minute,.second] } } } private let SECONDS_IN_MINUTE: TimeInterval = 60 private let SECONDS_IN_HOUR: TimeInterval = SECONDS_IN_MINUTE * 60 private let SECONDS_IN_DAY: TimeInterval = SECONDS_IN_HOUR * 24 private let SECONDS_IN_WEEK: TimeInterval = SECONDS_IN_DAY * 7
mit
9d4e09ddf886d123edf55e10f614db12
46.189349
488
0.745831
4.075115
false
false
false
false
lorentey/swift
stdlib/public/core/Identifiable.swift
6
1068
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2019 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// /// A class of types whose instances hold the value of an entity with stable identity. @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) public protocol Identifiable { /// A type representing the stable identity of the entity associated with `self`. associatedtype ID: Hashable /// The stable identity of the entity associated with `self`. var id: ID { get } } @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) extension Identifiable where Self: AnyObject { public var id: ObjectIdentifier { return ObjectIdentifier(self) } }
apache-2.0
98b151b68170612335245363378b127f
35.827586
86
0.621723
4.810811
false
false
false
false
alblue/swift
test/SILGen/indirect_enum.swift
1
24174
// RUN: %target-swift-emit-silgen -enable-sil-ownership -module-name indirect_enum -Xllvm -sil-print-debuginfo %s | %FileCheck %s indirect enum TreeA<T> { case Nil case Leaf(T) case Branch(left: TreeA<T>, right: TreeA<T>) } // CHECK-LABEL: sil hidden @$s13indirect_enum11TreeA_cases_1l1ryx_AA0C1AOyxGAGtlF : $@convention(thin) <T> (@in_guaranteed T, @guaranteed TreeA<T>, @guaranteed TreeA<T>) -> () { func TreeA_cases<T>(_ t: T, l: TreeA<T>, r: TreeA<T>) { // CHECK: bb0([[ARG1:%.*]] : @trivial $*T, [[ARG2:%.*]] : @guaranteed $TreeA<T>, [[ARG3:%.*]] : @guaranteed $TreeA<T>): // CHECK: [[METATYPE:%.*]] = metatype $@thin TreeA<T>.Type // CHECK-NEXT: [[NIL:%.*]] = enum $TreeA<T>, #TreeA.Nil!enumelt // CHECK-NOT: destroy_value [[NIL]] let _ = TreeA<T>.Nil // CHECK-NEXT: [[METATYPE:%.*]] = metatype $@thin TreeA<T>.Type // CHECK-NEXT: [[BOX:%.*]] = alloc_box $<τ_0_0> { var τ_0_0 } <T> // CHECK-NEXT: [[PB:%.*]] = project_box [[BOX]] // CHECK-NEXT: copy_addr [[ARG1]] to [initialization] [[PB]] // CHECK-NEXT: [[LEAF:%.*]] = enum $TreeA<T>, #TreeA.Leaf!enumelt.1, [[BOX]] // CHECK-NEXT: destroy_value [[LEAF]] let _ = TreeA<T>.Leaf(t) // CHECK-NEXT: [[METATYPE:%.*]] = metatype $@thin TreeA<T>.Type // CHECK-NEXT: [[BOX:%.*]] = alloc_box $<τ_0_0> { var (left: TreeA<τ_0_0>, right: TreeA<τ_0_0>) } <T> // CHECK-NEXT: [[PB:%.*]] = project_box [[BOX]] // CHECK-NEXT: [[LEFT:%.*]] = tuple_element_addr [[PB]] : $*(left: TreeA<T>, right: TreeA<T>), 0 // CHECK-NEXT: [[RIGHT:%.*]] = tuple_element_addr [[PB]] : $*(left: TreeA<T>, right: TreeA<T>), 1 // CHECK-NEXT: [[ARG2_COPY:%.*]] = copy_value [[ARG2]] // CHECK-NEXT: store [[ARG2_COPY]] to [init] [[LEFT]] // CHECK-NEXT: [[ARG3_COPY:%.*]] = copy_value [[ARG3]] // CHECK-NEXT: store [[ARG3_COPY]] to [init] [[RIGHT]] // CHECK-NEXT: [[BRANCH:%.*]] = enum $TreeA<T>, #TreeA.Branch!enumelt.1, [[BOX]] // CHECK-NEXT: destroy_value [[BRANCH]] let _ = TreeA<T>.Branch(left: l, right: r) } // CHECK: // end sil function '$s13indirect_enum11TreeA_cases_1l1ryx_AA0C1AOyxGAGtlF' // CHECK-LABEL: sil hidden @$s13indirect_enum16TreeA_reabstractyyS2icF : $@convention(thin) (@guaranteed @callee_guaranteed (Int) -> Int) -> () { func TreeA_reabstract(_ f: @escaping (Int) -> Int) { // CHECK: bb0([[ARG:%.*]] : @guaranteed $@callee_guaranteed (Int) -> Int): // CHECK: [[METATYPE:%.*]] = metatype $@thin TreeA<(Int) -> Int>.Type // CHECK-NEXT: [[BOX:%.*]] = alloc_box $<τ_0_0> { var τ_0_0 } <(Int) -> Int> // CHECK-NEXT: [[PB:%.*]] = project_box [[BOX]] // CHECK-NEXT: [[ARG_COPY:%.*]] = copy_value [[ARG]] // CHECK: [[THUNK:%.*]] = function_ref @$sS2iIegyd_S2iIegnr_TR // CHECK-NEXT: [[FN:%.*]] = partial_apply [callee_guaranteed] [[THUNK]]([[ARG_COPY]]) // CHECK-NEXT: store [[FN]] to [init] [[PB]] // CHECK-NEXT: [[LEAF:%.*]] = enum $TreeA<(Int) -> Int>, #TreeA.Leaf!enumelt.1, [[BOX]] // CHECK-NEXT: destroy_value [[LEAF]] // CHECK: return let _ = TreeA<(Int) -> Int>.Leaf(f) } // CHECK: } // end sil function '$s13indirect_enum16TreeA_reabstractyyS2icF' enum TreeB<T> { case Nil case Leaf(T) indirect case Branch(left: TreeB<T>, right: TreeB<T>) } // CHECK-LABEL: sil hidden @$s13indirect_enum11TreeB_cases_1l1ryx_AA0C1BOyxGAGtlF func TreeB_cases<T>(_ t: T, l: TreeB<T>, r: TreeB<T>) { // CHECK: [[METATYPE:%.*]] = metatype $@thin TreeB<T>.Type // CHECK: [[NIL:%.*]] = alloc_stack $TreeB<T> // CHECK-NEXT: inject_enum_addr [[NIL]] : $*TreeB<T>, #TreeB.Nil!enumelt // CHECK-NEXT: destroy_addr [[NIL]] // CHECK-NEXT: dealloc_stack [[NIL]] let _ = TreeB<T>.Nil // CHECK-NEXT: [[METATYPE:%.*]] = metatype $@thin TreeB<T>.Type // CHECK-NEXT: [[LEAF:%.*]] = alloc_stack $TreeB<T> // CHECK-NEXT: [[PAYLOAD:%.*]] = init_enum_data_addr [[LEAF]] : $*TreeB<T>, #TreeB.Leaf!enumelt.1 // CHECK-NEXT: copy_addr %0 to [initialization] [[PAYLOAD]] // CHECK-NEXT: inject_enum_addr [[LEAF]] : $*TreeB<T>, #TreeB.Leaf!enumelt // CHECK-NEXT: destroy_addr [[LEAF]] // CHECK-NEXT: dealloc_stack [[LEAF]] let _ = TreeB<T>.Leaf(t) // CHECK-NEXT: [[METATYPE:%.*]] = metatype $@thin TreeB<T>.Type // CHECK-NEXT: [[BOX:%.*]] = alloc_box $<τ_0_0> { var (left: TreeB<τ_0_0>, right: TreeB<τ_0_0>) } <T> // CHECK-NEXT: [[PB:%.*]] = project_box [[BOX]] // CHECK-NEXT: [[LEFT:%.*]] = tuple_element_addr [[PB]] // CHECK-NEXT: [[RIGHT:%.*]] = tuple_element_addr [[PB]] // CHECK-NEXT: copy_addr %1 to [initialization] [[LEFT]] : $*TreeB<T> // CHECK-NEXT: copy_addr %2 to [initialization] [[RIGHT]] : $*TreeB<T> // CHECK-NEXT: [[BRANCH:%.*]] = alloc_stack $TreeB<T> // CHECK-NEXT: [[PAYLOAD:%.*]] = init_enum_data_addr [[BRANCH]] // CHECK-NEXT: store [[BOX]] to [init] [[PAYLOAD]] // CHECK-NEXT: inject_enum_addr [[BRANCH]] : $*TreeB<T>, #TreeB.Branch!enumelt.1 // CHECK-NEXT: destroy_addr [[BRANCH]] // CHECK-NEXT: dealloc_stack [[BRANCH]] let _ = TreeB<T>.Branch(left: l, right: r) // CHECK: return } // CHECK-LABEL: sil hidden @$s13indirect_enum13TreeInt_cases_1l1rySi_AA0cD0OAFtF : $@convention(thin) (Int, @guaranteed TreeInt, @guaranteed TreeInt) -> () func TreeInt_cases(_ t: Int, l: TreeInt, r: TreeInt) { // CHECK: bb0([[ARG1:%.*]] : @trivial $Int, [[ARG2:%.*]] : @guaranteed $TreeInt, [[ARG3:%.*]] : @guaranteed $TreeInt): // CHECK: [[METATYPE:%.*]] = metatype $@thin TreeInt.Type // CHECK-NEXT: [[NIL:%.*]] = enum $TreeInt, #TreeInt.Nil!enumelt // CHECK-NOT: destroy_value [[NIL]] let _ = TreeInt.Nil // CHECK-NEXT: [[METATYPE:%.*]] = metatype $@thin TreeInt.Type // CHECK-NEXT: [[LEAF:%.*]] = enum $TreeInt, #TreeInt.Leaf!enumelt.1, [[ARG1]] // CHECK-NOT: destroy_value [[LEAF]] let _ = TreeInt.Leaf(t) // CHECK-NEXT: [[METATYPE:%.*]] = metatype $@thin TreeInt.Type // CHECK-NEXT: [[BOX:%.*]] = alloc_box ${ var (left: TreeInt, right: TreeInt) } // CHECK-NEXT: [[PB:%.*]] = project_box [[BOX]] // CHECK-NEXT: [[LEFT:%.*]] = tuple_element_addr [[PB]] // CHECK-NEXT: [[RIGHT:%.*]] = tuple_element_addr [[PB]] // CHECK-NEXT: [[ARG2_COPY:%.*]] = copy_value [[ARG2]] // CHECK-NEXT: store [[ARG2_COPY]] to [init] [[LEFT]] // CHECK-NEXT: [[ARG3_COPY:%.*]] = copy_value [[ARG3]] // CHECK-NEXT: store [[ARG3_COPY]] to [init] [[RIGHT]] // CHECK-NEXT: [[BRANCH:%.*]] = enum $TreeInt, #TreeInt.Branch!enumelt.1, [[BOX]] // CHECK-NEXT: destroy_value [[BRANCH]] let _ = TreeInt.Branch(left: l, right: r) } // CHECK: } // end sil function '$s13indirect_enum13TreeInt_cases_1l1rySi_AA0cD0OAFtF' enum TreeInt { case Nil case Leaf(Int) indirect case Branch(left: TreeInt, right: TreeInt) } enum TrivialButIndirect { case Direct(Int) indirect case Indirect(Int) } func a() {} func b<T>(_ x: T) {} func c<T>(_ x: T, _ y: T) {} func d() {} // CHECK-LABEL: sil hidden @$s13indirect_enum11switchTreeAyyAA0D1AOyxGlF : $@convention(thin) <T> (@guaranteed TreeA<T>) -> () { func switchTreeA<T>(_ x: TreeA<T>) { // CHECK: bb0([[ARG:%.*]] : @guaranteed $TreeA<T>): // -- x +0 // CHECK: switch_enum [[ARG]] : $TreeA<T>, // CHECK: case #TreeA.Nil!enumelt: [[NIL_CASE:bb1]], // CHECK: case #TreeA.Leaf!enumelt.1: [[LEAF_CASE:bb2]], // CHECK: case #TreeA.Branch!enumelt.1: [[BRANCH_CASE:bb3]], switch x { // CHECK: [[NIL_CASE]]: // CHECK: function_ref @$s13indirect_enum1ayyF // CHECK: br [[OUTER_CONT:bb[0-9]+]] case .Nil: a() // CHECK: [[LEAF_CASE]]([[LEAF_BOX:%.*]] : @guaranteed $<τ_0_0> { var τ_0_0 } <T>): // CHECK: [[VALUE:%.*]] = project_box [[LEAF_BOX]] // CHECK: copy_addr [[VALUE]] to [initialization] [[X:%.*]] : $*T // CHECK: function_ref @$s13indirect_enum1b{{[_0-9a-zA-Z]*}}F // CHECK: destroy_addr [[X]] // CHECK: dealloc_stack [[X]] // -- x +0 // CHECK: br [[OUTER_CONT]] case .Leaf(let x): b(x) // CHECK: [[BRANCH_CASE]]([[NODE_BOX:%.*]] : @guaranteed $<τ_0_0> { var (left: TreeA<τ_0_0>, right: TreeA<τ_0_0>) } <T>): // CHECK: [[TUPLE_ADDR:%.*]] = project_box [[NODE_BOX]] // CHECK: [[TUPLE:%.*]] = load_borrow [[TUPLE_ADDR]] // CHECK: ([[LEFT:%.*]], [[RIGHT:%.*]]) = destructure_tuple [[TUPLE]] // CHECK: switch_enum [[LEFT]] : $TreeA<T>, // CHECK: case #TreeA.Leaf!enumelt.1: [[LEAF_CASE_LEFT:bb[0-9]+]], // CHECK: default [[FAIL_LEFT:bb[0-9]+]] // CHECK: [[LEAF_CASE_LEFT]]([[LEFT_LEAF_BOX:%.*]] : @guaranteed $<τ_0_0> { var τ_0_0 } <T>): // CHECK: [[LEFT_LEAF_VALUE:%.*]] = project_box [[LEFT_LEAF_BOX]] // CHECK: switch_enum [[RIGHT]] : $TreeA<T>, // CHECK: case #TreeA.Leaf!enumelt.1: [[LEAF_CASE_RIGHT:bb[0-9]+]], // CHECK: default [[FAIL_RIGHT:bb[0-9]+]] // CHECK: [[LEAF_CASE_RIGHT]]([[RIGHT_LEAF_BOX:%.*]] : @guaranteed $<τ_0_0> { var τ_0_0 } <T>): // CHECK: [[RIGHT_LEAF_VALUE:%.*]] = project_box [[RIGHT_LEAF_BOX]] // CHECK: copy_addr [[LEFT_LEAF_VALUE]] // CHECK: copy_addr [[RIGHT_LEAF_VALUE]] // -- x +1 // CHECK: br [[OUTER_CONT]] // CHECK: [[FAIL_RIGHT]]([[DEFAULT_VAL:%.*]] : @guaranteed // CHECK: br [[DEFAULT:bb[0-9]+]] // CHECK: [[FAIL_LEFT]]([[DEFAULT_VAL:%.*]] : @guaranteed // CHECK: br [[DEFAULT]] case .Branch(.Leaf(let x), .Leaf(let y)): c(x, y) // CHECK: [[DEFAULT]]: // -- x +0 default: d() } // CHECK: [[OUTER_CONT:%.*]]: // -- x +0 } // CHECK: } // end sil function '$s13indirect_enum11switchTreeAyyAA0D1AOyxGlF' // CHECK-LABEL: sil hidden @$s13indirect_enum11switchTreeB{{[_0-9a-zA-Z]*}}F func switchTreeB<T>(_ x: TreeB<T>) { // CHECK: copy_addr %0 to [initialization] [[SCRATCH:%.*]] : // CHECK: switch_enum_addr [[SCRATCH]] switch x { // CHECK: bb{{.*}}: // CHECK: destroy_addr [[SCRATCH]] // CHECK: dealloc_stack [[SCRATCH]] // CHECK: function_ref @$s13indirect_enum1ayyF // CHECK: br [[OUTER_CONT:bb[0-9]+]] case .Nil: a() // CHECK: bb{{.*}}: // CHECK: copy_addr [[SCRATCH]] to [initialization] [[LEAF_COPY:%.*]] : // CHECK: [[LEAF_ADDR:%.*]] = unchecked_take_enum_data_addr [[LEAF_COPY]] // CHECK: copy_addr [take] [[LEAF_ADDR]] to [initialization] [[LEAF:%.*]] : // CHECK: function_ref @$s13indirect_enum1b{{[_0-9a-zA-Z]*}}F // CHECK: destroy_addr [[LEAF]] // CHECK: dealloc_stack [[LEAF]] // CHECK-NOT: destroy_addr [[LEAF_COPY]] // CHECK: dealloc_stack [[LEAF_COPY]] // CHECK: destroy_addr [[SCRATCH]] // CHECK: dealloc_stack [[SCRATCH]] // CHECK: br [[OUTER_CONT]] case .Leaf(let x): b(x) // CHECK: bb{{.*}}: // CHECK: copy_addr [[SCRATCH]] to [initialization] [[TREE_COPY:%.*]] : // CHECK: [[TREE_ADDR:%.*]] = unchecked_take_enum_data_addr [[TREE_COPY]] // -- box +1 immutable // CHECK: [[BOX:%.*]] = load [take] [[TREE_ADDR]] // CHECK: [[TUPLE:%.*]] = project_box [[BOX]] // CHECK: [[LEFT:%.*]] = tuple_element_addr [[TUPLE]] // CHECK: [[RIGHT:%.*]] = tuple_element_addr [[TUPLE]] // CHECK: switch_enum_addr [[LEFT]] {{.*}}, default [[LEFT_FAIL:bb[0-9]+]] // CHECK: bb{{.*}}: // CHECK: copy_addr [[LEFT]] to [initialization] [[LEFT_COPY:%.*]] : // CHECK: [[LEFT_LEAF:%.*]] = unchecked_take_enum_data_addr [[LEFT_COPY]] : $*TreeB<T>, #TreeB.Leaf // CHECK: switch_enum_addr [[RIGHT]] {{.*}}, default [[RIGHT_FAIL:bb[0-9]+]] // CHECK: bb{{.*}}: // CHECK: copy_addr [[RIGHT]] to [initialization] [[RIGHT_COPY:%.*]] : // CHECK: [[RIGHT_LEAF:%.*]] = unchecked_take_enum_data_addr [[RIGHT_COPY]] : $*TreeB<T>, #TreeB.Leaf // CHECK: copy_addr [take] [[LEFT_LEAF]] to [initialization] [[X:%.*]] : // CHECK: copy_addr [take] [[RIGHT_LEAF]] to [initialization] [[Y:%.*]] : // CHECK: function_ref @$s13indirect_enum1c{{[_0-9a-zA-Z]*}}F // CHECK: destroy_addr [[Y]] // CHECK: dealloc_stack [[Y]] // CHECK: destroy_addr [[X]] // CHECK: dealloc_stack [[X]] // CHECK-NOT: destroy_addr [[RIGHT_COPY]] // CHECK: dealloc_stack [[RIGHT_COPY]] // CHECK-NOT: destroy_addr [[LEFT_COPY]] // CHECK: dealloc_stack [[LEFT_COPY]] // -- box +0 // CHECK: destroy_value [[BOX]] // CHECK-NOT: destroy_addr [[TREE_COPY]] // CHECK: dealloc_stack [[TREE_COPY]] // CHECK: destroy_addr [[SCRATCH]] // CHECK: dealloc_stack [[SCRATCH]] case .Branch(.Leaf(let x), .Leaf(let y)): c(x, y) // CHECK: [[RIGHT_FAIL]]: // CHECK: destroy_addr [[LEFT_LEAF]] // CHECK-NOT: destroy_addr [[LEFT_COPY]] // CHECK: dealloc_stack [[LEFT_COPY]] // CHECK: destroy_value [[BOX]] // CHECK-NOT: destroy_addr [[TREE_COPY]] // CHECK: dealloc_stack [[TREE_COPY]] // CHECK: br [[INNER_CONT:bb[0-9]+]] // CHECK: [[LEFT_FAIL]]: // CHECK: destroy_value [[BOX]] // CHECK-NOT: destroy_addr [[TREE_COPY]] // CHECK: dealloc_stack [[TREE_COPY]] // CHECK: br [[INNER_CONT:bb[0-9]+]] // CHECK: [[INNER_CONT]]: // CHECK: destroy_addr [[SCRATCH]] // CHECK: dealloc_stack [[SCRATCH]] // CHECK: function_ref @$s13indirect_enum1dyyF // CHECK: br [[OUTER_CONT]] default: d() } // CHECK: [[OUTER_CONT]]: // CHECK: return } // Make sure that switchTreeInt obeys ownership invariants. // // CHECK-LABEL: sil hidden @$s13indirect_enum13switchTreeInt{{[_0-9a-zA-Z]*}}F func switchTreeInt(_ x: TreeInt) { switch x { case .Nil: a() case .Leaf(let x): b(x) case .Branch(.Leaf(let x), .Leaf(let y)): c(x, y) default: d() } } // CHECK: } // end sil function '$s13indirect_enum13switchTreeInt{{[_0-9a-zA-Z]*}}F' // CHECK-LABEL: sil hidden @$s13indirect_enum10guardTreeA{{[_0-9a-zA-Z]*}}F func guardTreeA<T>(_ tree: TreeA<T>) { // CHECK: bb0([[ARG:%.*]] : @guaranteed $TreeA<T>): do { // CHECK: [[ARG_COPY:%.*]] = copy_value [[ARG]] // CHECK: switch_enum [[ARG_COPY]] : $TreeA<T>, case #TreeA.Nil!enumelt: [[YES:bb[0-9]+]], default [[NO1:bb[0-9]+]] // CHECK: [[YES]]: guard case .Nil = tree else { return } // CHECK: [[X:%.*]] = alloc_stack $T // CHECK: [[ARG_COPY:%.*]] = copy_value [[ARG]] // CHECK: switch_enum [[ARG_COPY]] : $TreeA<T>, case #TreeA.Leaf!enumelt.1: [[YES:bb[0-9]+]], default [[NO2:bb[0-9]+]] // CHECK: [[YES]]([[BOX:%.*]] : @owned $<τ_0_0> { var τ_0_0 } <T>): // CHECK: [[VALUE_ADDR:%.*]] = project_box [[BOX]] // CHECK: [[TMP:%.*]] = alloc_stack // CHECK: copy_addr [[VALUE_ADDR]] to [initialization] [[TMP]] // CHECK: copy_addr [take] [[TMP]] to [initialization] [[X]] // CHECK: destroy_value [[BOX]] guard case .Leaf(let x) = tree else { return } // CHECK: [[ARG_COPY:%.*]] = copy_value [[ARG]] // CHECK: switch_enum [[ARG_COPY]] : $TreeA<T>, case #TreeA.Branch!enumelt.1: [[YES:bb[0-9]+]], default [[NO3:bb[0-9]+]] // CHECK: [[YES]]([[BOX:%.*]] : @owned $<τ_0_0> { var (left: TreeA<τ_0_0>, right: TreeA<τ_0_0>) } <T>): // CHECK: [[VALUE_ADDR:%.*]] = project_box [[BOX]] // CHECK: [[TUPLE:%.*]] = load_borrow [[VALUE_ADDR]] // CHECK: [[TUPLE_COPY:%.*]] = copy_value [[TUPLE]] // CHECK: end_borrow [[TUPLE]] // CHECK: ([[L:%.*]], [[R:%.*]]) = destructure_tuple [[TUPLE_COPY]] // CHECK: destroy_value [[BOX]] guard case .Branch(left: let l, right: let r) = tree else { return } // CHECK: destroy_value [[R]] // CHECK: destroy_value [[L]] // CHECK: destroy_addr [[X]] } do { // CHECK: [[ARG_COPY:%.*]] = copy_value [[ARG]] // CHECK: switch_enum [[ARG_COPY]] : $TreeA<T>, case #TreeA.Nil!enumelt: [[YES:bb[0-9]+]], default [[NO4:bb[0-9]+]] // CHECK: [[NO4]]([[ORIGINAL_VALUE:%.*]] : @owned $TreeA<T>): // CHECK: destroy_value [[ORIGINAL_VALUE]] // CHECK: [[YES]]: // CHECK: br if case .Nil = tree { } // CHECK: [[X:%.*]] = alloc_stack $T // CHECK: [[ARG_COPY:%.*]] = copy_value [[ARG]] // CHECK: switch_enum [[ARG_COPY]] : $TreeA<T>, case #TreeA.Leaf!enumelt.1: [[YES:bb[0-9]+]], default [[NO5:bb[0-9]+]] // CHECK: [[NO5]]([[ORIGINAL_VALUE:%.*]] : @owned $TreeA<T>): // CHECK: destroy_value [[ORIGINAL_VALUE]] // CHECK: [[YES]]([[BOX:%.*]] : @owned $<τ_0_0> { var τ_0_0 } <T>): // CHECK: [[VALUE_ADDR:%.*]] = project_box [[BOX]] // CHECK: [[TMP:%.*]] = alloc_stack // CHECK: copy_addr [[VALUE_ADDR]] to [initialization] [[TMP]] // CHECK: copy_addr [take] [[TMP]] to [initialization] [[X]] // CHECK: destroy_value [[BOX]] // CHECK: destroy_addr [[X]] if case .Leaf(let x) = tree { } // CHECK: [[ARG_COPY:%.*]] = copy_value [[ARG]] // CHECK: switch_enum [[ARG_COPY]] : $TreeA<T>, case #TreeA.Branch!enumelt.1: [[YES:bb[0-9]+]], default [[NO:bb[0-9]+]] // CHECK: [[NO]]([[ORIGINAL_VALUE:%.*]] : @owned $TreeA<T>): // CHECK: destroy_value [[ORIGINAL_VALUE]] // CHECK: [[YES]]([[BOX:%.*]] : @owned $<τ_0_0> { var (left: TreeA<τ_0_0>, right: TreeA<τ_0_0>) } <T>): // CHECK: [[VALUE_ADDR:%.*]] = project_box [[BOX]] // CHECK: [[TUPLE:%.*]] = load_borrow [[VALUE_ADDR]] // CHECK: [[TUPLE_COPY:%.*]] = copy_value [[TUPLE]] // CHECK: end_borrow [[TUPLE]] // CHECK: ([[L:%.*]], [[R:%.*]]) = destructure_tuple [[TUPLE_COPY]] // CHECK: destroy_value [[BOX]] // CHECK: destroy_value [[R]] // CHECK: destroy_value [[L]] if case .Branch(left: let l, right: let r) = tree { } } // CHECK: [[NO3]]([[ORIGINAL_VALUE:%.*]] : @owned $TreeA<T>): // CHECK: destroy_value [[ORIGINAL_VALUE]] // CHECK: [[NO2]]([[ORIGINAL_VALUE:%.*]] : @owned $TreeA<T>): // CHECK: destroy_value [[ORIGINAL_VALUE]] // CHECK: [[NO1]]([[ORIGINAL_VALUE:%.*]] : @owned $TreeA<T>): // CHECK: destroy_value [[ORIGINAL_VALUE]] } // CHECK-LABEL: sil hidden @$s13indirect_enum10guardTreeB{{[_0-9a-zA-Z]*}}F func guardTreeB<T>(_ tree: TreeB<T>) { do { // CHECK: copy_addr %0 to [initialization] [[TMP1:%.*]] : // CHECK: switch_enum_addr [[TMP1]] : $*TreeB<T>, case #TreeB.Nil!enumelt: [[YES:bb[0-9]+]], default [[NO2:bb[0-9]+]] // CHECK: [[YES]]: // CHECK: destroy_addr [[TMP1]] guard case .Nil = tree else { return } // CHECK: [[X:%.*]] = alloc_stack $T // CHECK: copy_addr %0 to [initialization] [[TMP2:%.*]] : // CHECK: switch_enum_addr [[TMP2]] : $*TreeB<T>, case #TreeB.Leaf!enumelt.1: [[YES:bb[0-9]+]], default [[NO2:bb[0-9]+]] // CHECK: [[YES]]: // CHECK: [[VALUE:%.*]] = unchecked_take_enum_data_addr [[TMP2]] // CHECK: copy_addr [take] [[VALUE]] to [initialization] [[X]] // CHECK: dealloc_stack [[TMP2]] guard case .Leaf(let x) = tree else { return } // CHECK: [[L:%.*]] = alloc_stack $TreeB // CHECK: [[R:%.*]] = alloc_stack $TreeB // CHECK: copy_addr %0 to [initialization] [[TMP3:%.*]] : // CHECK: switch_enum_addr [[TMP3]] : $*TreeB<T>, case #TreeB.Branch!enumelt.1: [[YES:bb[0-9]+]], default [[NO3:bb[0-9]+]] // CHECK: [[YES]]: // CHECK: [[BOX_ADDR:%.*]] = unchecked_take_enum_data_addr [[TMP3]] // CHECK: [[BOX:%.*]] = load [take] [[BOX_ADDR]] // CHECK: [[TUPLE_ADDR:%.*]] = project_box [[BOX]] // CHECK: copy_addr [[TUPLE_ADDR]] to [initialization] [[TUPLE_COPY:%.*]] : // CHECK: [[L_COPY:%.*]] = tuple_element_addr [[TUPLE_COPY]] // CHECK: copy_addr [take] [[L_COPY]] to [initialization] [[L]] // CHECK: [[R_COPY:%.*]] = tuple_element_addr [[TUPLE_COPY]] // CHECK: copy_addr [take] [[R_COPY]] to [initialization] [[R]] // CHECK: destroy_value [[BOX]] guard case .Branch(left: let l, right: let r) = tree else { return } // CHECK: destroy_addr [[R]] // CHECK: destroy_addr [[L]] // CHECK: destroy_addr [[X]] } do { // CHECK: copy_addr %0 to [initialization] [[TMP:%.*]] : // CHECK: switch_enum_addr [[TMP]] : $*TreeB<T>, case #TreeB.Nil!enumelt: [[YES:bb[0-9]+]], default [[NO:bb[0-9]+]] // CHECK: [[NO]]: // CHECK: destroy_addr [[TMP]] // CHECK: [[YES]]: // CHECK: destroy_addr [[TMP]] if case .Nil = tree { } // CHECK: [[X:%.*]] = alloc_stack $T // CHECK: copy_addr %0 to [initialization] [[TMP:%.*]] : // CHECK: switch_enum_addr [[TMP]] : $*TreeB<T>, case #TreeB.Leaf!enumelt.1: [[YES:bb[0-9]+]], default [[NO:bb[0-9]+]] // CHECK: [[NO]]: // CHECK: destroy_addr [[TMP]] // CHECK: [[YES]]: // CHECK: [[VALUE:%.*]] = unchecked_take_enum_data_addr [[TMP]] // CHECK: copy_addr [take] [[VALUE]] to [initialization] [[X]] // CHECK: dealloc_stack [[TMP]] // CHECK: destroy_addr [[X]] if case .Leaf(let x) = tree { } // CHECK: [[L:%.*]] = alloc_stack $TreeB // CHECK: [[R:%.*]] = alloc_stack $TreeB // CHECK: copy_addr %0 to [initialization] [[TMP:%.*]] : // CHECK: switch_enum_addr [[TMP]] : $*TreeB<T>, case #TreeB.Branch!enumelt.1: [[YES:bb[0-9]+]], default [[NO:bb[0-9]+]] // CHECK: [[NO]]: // CHECK: destroy_addr [[TMP]] // CHECK: [[YES]]: // CHECK: [[BOX_ADDR:%.*]] = unchecked_take_enum_data_addr [[TMP]] // CHECK: [[BOX:%.*]] = load [take] [[BOX_ADDR]] // CHECK: [[TUPLE_ADDR:%.*]] = project_box [[BOX]] // CHECK: copy_addr [[TUPLE_ADDR]] to [initialization] [[TUPLE_COPY:%.*]] : // CHECK: [[L_COPY:%.*]] = tuple_element_addr [[TUPLE_COPY]] // CHECK: copy_addr [take] [[L_COPY]] to [initialization] [[L]] // CHECK: [[R_COPY:%.*]] = tuple_element_addr [[TUPLE_COPY]] // CHECK: copy_addr [take] [[R_COPY]] to [initialization] [[R]] // CHECK: destroy_value [[BOX]] // CHECK: destroy_addr [[R]] // CHECK: destroy_addr [[L]] if case .Branch(left: let l, right: let r) = tree { } } // CHECK: [[NO3]]: // CHECK: destroy_addr [[TMP3]] // CHECK: [[NO2]]: // CHECK: destroy_addr [[TMP2]] // CHECK: [[NO1]]: // CHECK: destroy_addr [[TMP1]] } // Just run guardTreeInt through the ownership verifier // // CHECK-LABEL: sil hidden @$s13indirect_enum12guardTreeInt{{[_0-9a-zA-Z]*}}F func guardTreeInt(_ tree: TreeInt) { do { guard case .Nil = tree else { return } guard case .Leaf(let x) = tree else { return } guard case .Branch(left: let l, right: let r) = tree else { return } } do { if case .Nil = tree { } if case .Leaf(let x) = tree { } if case .Branch(left: let l, right: let r) = tree { } } } // SEMANTIC ARC TODO: This test needs to be made far more comprehensive. // CHECK-LABEL: sil hidden @$s13indirect_enum35dontDisableCleanupOfIndirectPayloadyyAA010TrivialButG0OF : $@convention(thin) (@guaranteed TrivialButIndirect) -> () { func dontDisableCleanupOfIndirectPayload(_ x: TrivialButIndirect) { // CHECK: bb0([[ARG:%.*]] : @guaranteed $TrivialButIndirect): // CHECK: [[ARG_COPY:%.*]] = copy_value [[ARG]] // CHECK: switch_enum [[ARG_COPY]] : $TrivialButIndirect, case #TrivialButIndirect.Direct!enumelt.1: [[YES:bb[0-9]+]], case #TrivialButIndirect.Indirect!enumelt.1: [[NO:bb[0-9]+]] // guard case .Direct(let foo) = x else { return } // CHECK: [[YES]]({{%.*}} : @trivial $Int): // CHECK: [[ARG_COPY:%.*]] = copy_value [[ARG]] // CHECK: switch_enum [[ARG_COPY]] : $TrivialButIndirect, case #TrivialButIndirect.Indirect!enumelt.1: [[YES:bb[0-9]+]], case #TrivialButIndirect.Direct!enumelt.1: [[NO2:bb[0-9]+]] // CHECK: [[YES]]([[BOX:%.*]] : @owned ${ var Int }): // CHECK: destroy_value [[BOX]] // CHECK: [[NO2]]({{%.*}} : @trivial $Int): // CHECK-NOT: destroy_value // CHECK: [[NO]]([[PAYLOAD:%.*]] : @owned ${ var Int }): // CHECK: destroy_value [[PAYLOAD]] guard case .Indirect(let bar) = x else { return } } // CHECK: } // end sil function '$s13indirect_enum35dontDisableCleanupOfIndirectPayloadyyAA010TrivialButG0OF'
apache-2.0
82158be8057625857bc5feae4e045b7b
43.46593
185
0.543674
3.08444
false
false
false
false
Snail93/iOSDemos
SnailSwiftDemos/SnailSwiftDemos/Bases/ViewControllers/ThirdFViewController.swift
2
1811
// // ThirdFViewController.swift // SnailSwiftDemos // // Created by Jian Wu on 2016/11/4. // Copyright © 2016年 Snail. All rights reserved. // import UIKit class ThirdFViewController: CustomViewController,UITableViewDataSource,UITableViewDelegate { @IBOutlet weak var aTableView: UITableView! var cellNames = ["ObjectMapper","Realm","FMDB","SQLite.swift","Alamofire","CocoaAsyncSocket","RongYun","KeychainAccess","QiNiu","MJRefresh","AFNetworking","RxCocoa","ImagePicker"] override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. leftBtn.isHidden = false navTitleLabel.text = "第三方库" aTableView.register(UITableViewCell.self, forCellReuseIdentifier: "ThirdCell") } //MARK: - UITableViewDelegate methods func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return cellNames.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "ThirdCell", for: indexPath) cell.textLabel?.text = cellNames[indexPath.row] return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { self.performSegue(withIdentifier: cellNames[indexPath.row], sender: nil) } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
apache-2.0
006c4bf573ddd1946ac1868cc4e2cc54
34.294118
183
0.696111
5.013928
false
false
false
false
nheagy/WordPress-iOS
WordPress/Classes/ViewRelated/Blog/SharingButtonsViewController.swift
1
35136
import UIKit import WordPressShared /// Manages which sharing button are displayed, their order, and other settings /// related to sharing. /// @objc class SharingButtonsViewController : UITableViewController { let buttonSectionIndex = 0 let moreSectionIndex = 1 let blog: Blog var buttons = [SharingButton]() var sections = [SharingButtonsSection]() var buttonsSection: SharingButtonsSection { return sections[buttonSectionIndex] } var moreSection: SharingButtonsSection { return sections[moreSectionIndex] } var twitterSection: SharingButtonsSection { return sections.last! } let buttonStyles = [ "icon-text": NSLocalizedString("Icon & Text", comment: "Title of a button style"), "icon": NSLocalizedString("Icon Only", comment: "Title of a button style"), "text": NSLocalizedString("Text Only", comment: "Title of a button style"), "official": NSLocalizedString("Official Buttons", comment: "Title of a button style") ] let buttonStyleTitle = NSLocalizedString("Button Style", comment:"Title for a list of different button styles.") let labelTitle = NSLocalizedString("Label", comment:"Noun. Title for the setting to edit the sharing label text.") let twitterUsernameTitle = NSLocalizedString("Twitter Username", comment:"Title for the setting to edit the twitter username used when sharing to twitter.") let twitterServiceID = "twitter" let managedObjectContext = ContextManager.sharedInstance().newMainContextChildContext() // MARK: - LifeCycle Methods init(blog: Blog) { self.blog = blog super.init(style: .Grouped) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() navigationItem.title = NSLocalizedString("Manage", comment: "Verb. Title of the screen for managing sharing buttons and settings related to sharing.") let service = SharingService(managedObjectContext: managedObjectContext) buttons = service.allSharingButtonsForBlog(self.blog) configureTableView() setupSections() syncSharingButtons() syncSharingSettings() } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) tableView.reloadData() } // MARK: - Sections Setup and Config /// Configures the table view. The table view is set to edit mode to allow /// rows in the buttons and more sections to be reordered. /// func configureTableView() { tableView.registerClass(SettingTableViewCell.self, forCellReuseIdentifier: SharingCellIdentifiers.SettingsCellIdentifier) tableView.registerClass(SwitchTableViewCell.self, forCellReuseIdentifier: SharingCellIdentifiers.SortableSwitchCellIdentifier) tableView.registerClass(SwitchTableViewCell.self, forCellReuseIdentifier: SharingCellIdentifiers.SwitchCellIdentifier) WPStyleGuide.configureColorsForView(view, andTableView: tableView) tableView.setEditing(true, animated: false) tableView.allowsSelectionDuringEditing = true } /// Sets up the sections for the table view and configures their starting state. /// func setupSections() { sections.append(setupButtonSection()) // buttons section should be section idx 0 sections.append(setupMoreSection()) // more section should be section idx 1 sections.append(setupShareLabelSection()) sections.append(setupButtonStyleSection()) if blog.isHostedAtWPcom { sections.append(setupReblogAndLikeSection()) sections.append(setupCommentLikeSection()) } sections.append(setupTwitterNameSection()) configureTwitterNameSection() configureButtonRows() configureMoreRows() } /// Sets up the buttons section. This section is sortable. /// func setupButtonSection() -> SharingButtonsSection { let section = SharingButtonsSection() section.canSort = true section.headerText = NSLocalizedString("Sharing Buttons", comment: "Title of a list of buttons used for sharing content to other services.") return section } /// Sets up the more section. This section is sortable. /// func setupMoreSection() -> SharingButtonsSection { let section = SharingButtonsSection() section.canSort = true section.headerText = NSLocalizedString("\"More\" Button", comment: "Title of a list of buttons used for sharing content to other services. These buttons appear when the user taps a `More` button.") section.footerText = NSLocalizedString("A \"more\" button contains a dropdown which displays sharing buttons", comment: "A short description of what the 'More' button is and how it works.") return section } /// Sets up the label section. /// func setupShareLabelSection() -> SharingButtonsSection { let section = SharingButtonsSection() let row = SharingSettingRow() row.action = { [unowned self] in self.handleEditLabel() } row.configureCell = {[unowned self] (cell: UITableViewCell) in cell.editingAccessoryType = .DisclosureIndicator cell.textLabel?.text = self.labelTitle cell.detailTextLabel?.text = self.blog.settings.sharingLabel } section.rows = [row] return section } /// Sets up the button style section /// func setupButtonStyleSection() -> SharingButtonsSection { let section = SharingButtonsSection() let row = SharingSettingRow() row.action = { [unowned self] in self.handleEditButtonStyle() } row.configureCell = {[unowned self] (cell: UITableViewCell) in cell.editingAccessoryType = .DisclosureIndicator cell.textLabel?.text = self.buttonStyleTitle cell.detailTextLabel?.text = self.buttonStyles[self.blog.settings.sharingButtonStyle] } section.rows = [row] return section } /// Sets up the reblog and the likes section /// func setupReblogAndLikeSection() -> SharingButtonsSection { var rows = [SharingButtonsRow]() let section = SharingButtonsSection() section.headerText = NSLocalizedString("Reblog & Like", comment: "Title for a list of ssettings for editing a blog's Reblog and Like settings.") // Reblog button row var row = SharingSwitchRow() row.configureCell = {[unowned self] (cell: UITableViewCell) in cell.editingAccessoryView = cell.accessoryView cell.editingAccessoryType = cell.accessoryType if let switchCell = cell as? SwitchTableViewCell { switchCell.textLabel?.text = NSLocalizedString("Show Reblog button", comment:"Title for the `show reblog button` setting") switchCell.on = !self.blog.settings.sharingDisabledReblogs switchCell.onChange = { newValue in self.blog.settings.sharingDisabledReblogs = !newValue self.saveBlogSettingsChanges(false) } } } rows.append(row) // Like button row row = SharingSwitchRow() row.configureCell = {[unowned self] (cell: UITableViewCell) in cell.editingAccessoryView = cell.accessoryView cell.editingAccessoryType = cell.accessoryType if let switchCell = cell as? SwitchTableViewCell { switchCell.textLabel?.text = NSLocalizedString("Show Like button", comment:"Title for the `show like button` setting") switchCell.on = !self.blog.settings.sharingDisabledLikes switchCell.onChange = { newValue in self.blog.settings.sharingDisabledLikes = !newValue self.saveBlogSettingsChanges(false) } } } rows.append(row) section.rows = rows return section } /// Sets up the section for comment likes /// func setupCommentLikeSection() -> SharingButtonsSection { let section = SharingButtonsSection() section.footerText = NSLocalizedString("Allow all comments to be Liked by you and your readers", comment:"A short description of the comment like sharing setting.") let row = SharingSwitchRow() row.configureCell = {[unowned self] (cell: UITableViewCell) in cell.editingAccessoryView = cell.accessoryView cell.editingAccessoryType = cell.accessoryType if let switchCell = cell as? SwitchTableViewCell { switchCell.textLabel?.text = NSLocalizedString("Comment Likes", comment:"Title for the `comment likes` setting") switchCell.on = self.blog.settings.sharingCommentLikesEnabled switchCell.onChange = { newValue in self.blog.settings.sharingCommentLikesEnabled = newValue self.saveBlogSettingsChanges(false) } } } section.rows = [row] return section } /// Sets up the twitter names section. The contents of the section are displayed /// or not displayed depending on if the Twitter button is enabled. /// func setupTwitterNameSection() -> SharingButtonsSection { return SharingButtonsSection() } /// Configures the twiter name section. When the twitter button is disabled, /// the section header is empty, and there are no rows. When the twitter button /// is enabled. the section header and the row is shown. /// func configureTwitterNameSection() { if !shouldShowTwitterSection() { twitterSection.footerText = " " twitterSection.rows.removeAll() return } twitterSection.footerText = NSLocalizedString("This will be included in tweets when people share using the Twitter button.", comment:"A description of the twitter sharing setting.") let row = SharingSettingRow() row.action = { [unowned self] in self.handleEditTwitterName() } row.configureCell = {[unowned self] (cell: UITableViewCell) in cell.editingAccessoryType = .DisclosureIndicator cell.textLabel?.text = self.twitterUsernameTitle var name = self.blog.settings.sharingTwitterName if name.characters.count > 0 { name = "@\(name)" } cell.detailTextLabel?.text = name } twitterSection.rows = [row] } /// Creates a sortable row for the specified button. /// /// - Parameters: /// - button: The sharing button that the row will represent. /// /// - Returns: A SortableSharingSwitchRow. /// func sortableRowForButton(button: SharingButton) -> SortableSharingSwitchRow { let row = SortableSharingSwitchRow(buttonID: button.buttonID) row.configureCell = {[unowned self] (cell: UITableViewCell) in cell.imageView?.image = self.iconForSharingButton(button) cell.imageView?.tintColor = WPStyleGuide.greyLighten20() cell.editingAccessoryView = nil cell.editingAccessoryType = .None cell.textLabel?.text = button.name } return row } /// Creates a switch row for the specified button in the sharing buttons section. /// /// - Parameters: /// - button: The sharing button that the row will represent. /// /// - Returns: A SortableSharingSwitchRow. /// func switchRowForButtonSectionButton(button: SharingButton) -> SortableSharingSwitchRow { let row = SortableSharingSwitchRow(buttonID: button.buttonID) row.configureCell = {[unowned self] (cell: UITableViewCell) in if let switchCell = cell as? SwitchTableViewCell { self.configureSortableSwitchCellAppearance(switchCell, button: button) switchCell.on = button.enabled && button.visible switchCell.onChange = { newValue in button.enabled = newValue if button.enabled { button.visibility = button.enabled ? SharingButton.visible : nil } self.refreshMoreSection() } } } return row } /// Creates a switch row for the specified button in the more buttons section. /// /// - Parameters: /// - button: The sharing button that the row will represent. /// /// - Returns: A SortableSharingSwitchRow. /// func switchRowForMoreSectionButton(button: SharingButton) -> SortableSharingSwitchRow { let row = SortableSharingSwitchRow(buttonID: button.buttonID) row.configureCell = {[unowned self] (cell: UITableViewCell) in if let switchCell = cell as? SwitchTableViewCell { self.configureSortableSwitchCellAppearance(switchCell, button: button) switchCell.on = button.enabled && !button.visible switchCell.onChange = { newValue in button.enabled = newValue if button.enabled { button.visibility = button.enabled ? SharingButton.hidden : nil } self.refreshButtonsSection() } } } return row } /// Configures common appearance properties for the button switch cells. /// /// - Parameters: /// - cell: The SwitchTableViewCell cell to configure /// - button: The sharing button that the row will represent. /// func configureSortableSwitchCellAppearance(cell: SwitchTableViewCell, button: SharingButton) { cell.editingAccessoryView = cell.accessoryView cell.editingAccessoryType = cell.accessoryType cell.imageView?.image = self.iconForSharingButton(button) cell.imageView?.tintColor = WPStyleGuide.greyLighten20() cell.textLabel?.text = button.name } /// Configures the rows for the button section. When the section is editing, /// all buttons are shown with switch cells. When the section is not editing, /// only enabled and visible buttons are shown and the rows are sortable. /// func configureButtonRows() { var rows = [SharingButtonsRow]() let row = SharingSwitchRow() row.configureCell = {[unowned self] (cell: UITableViewCell) in if let switchCell = cell as? SwitchTableViewCell { cell.editingAccessoryView = cell.accessoryView cell.editingAccessoryType = cell.accessoryType switchCell.textLabel?.text = NSLocalizedString("Edit sharing buttons", comment: "Title for the edit sharing buttons section") switchCell.on = self.buttonsSection.editing switchCell.onChange = { newValue in self.buttonsSection.editing = !self.buttonsSection.editing self.updateButtonOrderAfterEditing() self.saveButtonChanges(true) } } } rows.append(row) if !buttonsSection.editing { let buttonsToShow = buttons.filter { (button) -> Bool in return button.enabled && button.visible } for button in buttonsToShow { rows.append(sortableRowForButton(button)) } } else { for button in buttons { rows.append(switchRowForButtonSectionButton(button)) } } buttonsSection.rows = rows } /// Configures the rows for the more section. When the section is editing, /// all buttons are shown with switch cells. When the section is not editing, /// only enabled and hidden buttons are shown and the rows are sortable. /// func configureMoreRows() { var rows = [SharingButtonsRow]() let row = SharingSwitchRow() row.configureCell = {[unowned self] (cell: UITableViewCell) in if let switchCell = cell as? SwitchTableViewCell { cell.editingAccessoryView = cell.accessoryView cell.editingAccessoryType = cell.accessoryType switchCell.textLabel?.text = NSLocalizedString("Edit \"More\" button", comment: "Title for the edit more button section") switchCell.on = self.moreSection.editing switchCell.onChange = { newValue in self.updateButtonOrderAfterEditing() self.moreSection.editing = !self.moreSection.editing self.saveButtonChanges(true) } } } rows.append(row) if !moreSection.editing { let buttonsToShow = buttons.filter { (button) -> Bool in return button.enabled && !button.visible } for button in buttonsToShow { rows.append(sortableRowForButton(button)) } } else { for button in buttons { rows.append(switchRowForMoreSectionButton(button)) } } moreSection.rows = rows } /// Refreshes the rows for but button section (also the twitter section if /// needed) and reloads the section. /// func refreshButtonsSection() { configureButtonRows() configureTwitterNameSection() let indexSet = NSMutableIndexSet(index: buttonSectionIndex) indexSet.addIndex(sections.count - 1) tableView.reloadSections(indexSet, withRowAnimation: .Automatic) } /// Refreshes the rows for but more section (also the twitter section if /// needed) and reloads the section. /// func refreshMoreSection() { configureMoreRows() configureTwitterNameSection() let indexSet = NSMutableIndexSet(index: moreSectionIndex) indexSet.addIndex(sections.count - 1) tableView.reloadSections(indexSet, withRowAnimation: .Automatic) } /// Provides the icon that represents the sharing button's service. /// /// - Parameters: /// - button: The sharing button for the icon. /// /// - Returns: The UIImage for the icon /// func iconForSharingButton(button: SharingButton) -> UIImage { return WPStyleGuide.iconForService(button.buttonID) } // MARK: - Instance Methods /// Whether the twitter section should be present or not. /// /// - Returns: true if the twitter section should be shown. False otherwise. /// func shouldShowTwitterSection() -> Bool { for button in buttons { if button.buttonID == twitterServiceID { return button.enabled } } return false } /// Saves changes to blog settings back to the blog and optionally refreshes /// the tableview. /// /// - Parameters: /// - refresh: True if the tableview should be reloaded. /// func saveBlogSettingsChanges(refresh: Bool) { if refresh { tableView.reloadData() } let context = ContextManager.sharedInstance().mainContext let service = BlogService(managedObjectContext: context) service.updateSettingsForBlog(self.blog, success: nil, failure: { [weak self] (error: NSError!) in DDLogSwift.logError(error.description) self?.showErrorSyncingMessage(error) }) } /// Syncs sharing buttons from the user's blog and reloads the button sections /// when finished. Fails silently if there is an error. /// func syncSharingButtons() { let service = SharingService(managedObjectContext: managedObjectContext) service.syncSharingButtonsForBlog(self.blog, success: { [weak self] in self?.reloadButtons() }, failure: { (error: NSError!) in DDLogSwift.logError(error.description) }) } /// Sync sharing settings from the user's blog and reloads the setting sections /// when finished. Fails silently if there is an error. /// func syncSharingSettings() { let service = BlogService(managedObjectContext: managedObjectContext) service.syncSettingsForBlog(blog, success: { [weak self] in self?.reloadSettingsSections() }, failure: { (error: NSError!) in DDLogSwift.logError(error.description) }) } /// Reloads the sections for different button settings. /// func reloadSettingsSections() { let settingsSections = NSMutableIndexSet() for i in 0..<sections.count { if i <= buttonSectionIndex { continue } settingsSections.addIndex(i) } tableView.reloadSections(settingsSections, withRowAnimation: .Automatic) } // MARK: - Update And Save Buttons /// Updates rows after editing. /// func updateButtonOrderAfterEditing() { let buttonsForButtonSection = buttons.filter { (btn) -> Bool in return btn.enabled && btn.visible } let buttonsForMoreSection = buttons.filter { (btn) -> Bool in return btn.enabled && !btn.visible } let remainingButtons = buttons.filter { (btn) -> Bool in return !btn.enabled } var order = 0 for button in buttonsForButtonSection { button.order = order order += 1 } for button in buttonsForMoreSection { button.order = order order += 1 } for button in remainingButtons { // we'll update the order for the remaining buttons but this is not // respected by the REST API and changes after syncing. button.order = order order += 1 } } /// Saves changes to sharing buttons to core data, reloads the buttons, then /// pushes the changes up to the blog, optionally refreshing when done. /// /// - Parameters: /// - refreshAfterSync: If true buttons are reloaded when the sync completes. /// func saveButtonChanges(refreshAfterSync: Bool) { let context = ContextManager.sharedInstance().mainContext ContextManager.sharedInstance().saveContext(context) { [weak self] in self?.reloadButtons() self?.syncButtonChangesToBlog(refreshAfterSync) } } /// Retrives a fresh copy of the SharingButtons from core data, updating the /// `buttons` property and refreshes the button section and the more section. /// func reloadButtons() { let service = SharingService(managedObjectContext: managedObjectContext) buttons = service.allSharingButtonsForBlog(blog) refreshButtonsSection() refreshMoreSection() } /// Saves changes to the sharing buttons back to the blog. /// /// - Parameters: /// - refresh: True if the tableview sections should be reloaded. /// func syncButtonChangesToBlog(refresh: Bool) { let service = SharingService(managedObjectContext: managedObjectContext) service.updateSharingButtonsForBlog(blog, sharingButtons: buttons, success: {[weak self] in if refresh { self?.reloadButtons() } }, failure: { [weak self] (error: NSError!) in DDLogSwift.logError(error.description) self?.showErrorSyncingMessage(error) }) } /// Shows an alert. The localized description of the specified NSError is /// included in the alert. /// /// - Parameters: /// - error: An NSError object. /// func showErrorSyncingMessage(error: NSError) { let title = NSLocalizedString("Could Not Save Changes", comment: "Title of an prompt letting the user know there was a problem saving.") let message = NSLocalizedString("There was a problem saving changes to sharing management.", comment: "A short error message shown in a prompt.") let controller = UIAlertController(title: title, message: "\(message) \(error.localizedDescription)", preferredStyle: .Alert) controller.addCancelActionWithTitle(NSLocalizedString("OK", comment: "A button title."), handler: nil) controller.presentFromRootViewController() } // MARK: - Actions /// Called when the user taps the label row. Shows a controller to change the /// edit label text. /// func handleEditLabel() { let text = blog.settings.sharingLabel let placeholder = NSLocalizedString("Type a label", comment: "A placeholder for the sharing label.") let hint = NSLocalizedString("Change the text of the sharing button's label. This text won't appear until you add at least one sharing button.", comment: "Instructions for editing the sharing label.") let controller = SettingsTextViewController(text: text, placeholder: placeholder, hint: hint, isPassword: false) controller.title = labelTitle controller.onValueChanged = {[unowned self] (value) in guard value != self.blog.settings.sharingLabel else { return } self.blog.settings.sharingLabel = value self.saveBlogSettingsChanges(true) } navigationController?.pushViewController(controller, animated: true) } /// Called when the user taps the button style row. Shows a controller to /// choose from available button styles. /// func handleEditButtonStyle() { var titles = [String]() var values = [String]() _ = buttonStyles.map({ (k: String, v: String) in titles.append(v) values.append(k) }) let currentValue = blog.settings.sharingButtonStyle let dict: [String: AnyObject] = [ SettingsSelectionDefaultValueKey: values[0], SettingsSelectionTitleKey: buttonStyleTitle, SettingsSelectionTitlesKey: titles, SettingsSelectionValuesKey: values, SettingsSelectionCurrentValueKey: currentValue ] let controller = SettingsSelectionViewController(dictionary: dict) controller.onItemSelected = { [unowned self] (selected) in if let str = selected as? String { if self.blog.settings.sharingButtonStyle == str { return } self.blog.settings.sharingButtonStyle = str self.saveBlogSettingsChanges(true) } } navigationController?.pushViewController(controller, animated: true) } /// Called when the user taps the twitter name row. Shows a controller to change /// the twitter name text. /// func handleEditTwitterName() { let text = blog.settings.sharingTwitterName let placeholder = NSLocalizedString("Username", comment: "A placeholder for the twitter username") let hint = NSLocalizedString("This will be included in tweets when people share using the Twitter button.", comment: "Information about the twitter sharing feature.") let controller = SettingsTextViewController(text: text, placeholder: placeholder, hint: hint, isPassword: false) controller.title = twitterUsernameTitle controller.onValueChanged = {[unowned self] (value) in if value == self.blog.settings.sharingTwitterName { return } // Remove the @ sign if it was entered. var str = NSString(string: value) str = str.stringByReplacingOccurrencesOfString("@", withString: "") self.blog.settings.sharingTwitterName = str as String self.saveBlogSettingsChanges(true) } navigationController?.pushViewController(controller, animated: true) } // MARK: - TableView Delegate Methods override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return sections.count } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return sections[section].rows.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let row = sections[indexPath.section].rows[indexPath.row] let cell = tableView.dequeueReusableCellWithIdentifier(row.cellIdentifier)! row.configureCell?(cell) return cell } override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? { return sections[section].headerText } override func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { guard let title = self.tableView(tableView, titleForHeaderInSection: section) else { return nil } let headerView = WPTableViewSectionHeaderFooterView(reuseIdentifier: nil, style: .Header) headerView.title = title return headerView } override func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { let title = self.tableView(tableView, titleForHeaderInSection: section) return WPTableViewSectionHeaderFooterView.heightForHeader(title, width: view.bounds.width) } override func tableView(tableView: UITableView, titleForFooterInSection section: Int) -> String? { return sections[section].footerText } override func tableView(tableView: UITableView, viewForFooterInSection section: Int) -> UIView? { guard let title = self.tableView(tableView, titleForFooterInSection: section) else { return nil } let footerView = WPTableViewSectionHeaderFooterView(reuseIdentifier: nil, style: .Footer) footerView.title = title return footerView } override func tableView(tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat { let title = self.tableView(tableView, titleForFooterInSection: section) return WPTableViewSectionHeaderFooterView.heightForFooter(title, width: view.bounds.width) } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { let row = sections[indexPath.section].rows[indexPath.row] if row.cellIdentifier != SharingCellIdentifiers.SettingsCellIdentifier { tableView.deselectRowAtIndexPath(indexPath, animated: true) } row.action?() } override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool { let section = sections[indexPath.section] return section.canSort && !section.editing && indexPath.row > 0 } // The table view is in editing mode, but no cells should show the delete button, // only the move icon. override func tableView(tableView: UITableView, editingStyleForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCellEditingStyle { return .None } override func tableView(tableView: UITableView, shouldIndentWhileEditingRowAtIndexPath indexPath: NSIndexPath) -> Bool { return false } // The first row in the section is static containing the on/off toggle. override func tableView(tableView: UITableView, targetIndexPathForMoveFromRowAtIndexPath sourceIndexPath: NSIndexPath, toProposedIndexPath proposedDestinationIndexPath: NSIndexPath) -> NSIndexPath { let row = proposedDestinationIndexPath.row > 0 ? proposedDestinationIndexPath.row : 1 return NSIndexPath(forRow: row, inSection: sourceIndexPath.section) } // Updates the order of the moved button. override func tableView(tableView: UITableView, moveRowAtIndexPath sourceIndexPath: NSIndexPath, toIndexPath destinationIndexPath: NSIndexPath) { let sourceSection = sections[sourceIndexPath.section] let diff = destinationIndexPath.row - sourceIndexPath.row let movedRow = sourceSection.rows[sourceIndexPath.row] as! SortableSharingSwitchRow let movedButton = buttons.filter { (button) -> Bool in return button.buttonID == movedRow.buttonID } let theButton = movedButton.first! let oldIndex = buttons.indexOf(theButton)! let newIndex = oldIndex + diff let buttonsArr = NSMutableArray(array: buttons) buttonsArr.removeObjectAtIndex(oldIndex) buttonsArr.insertObject(theButton, atIndex: newIndex) // Update the order for all buttons for (index, button) in buttonsArr.enumerate() { let sharingButton = button as! SharingButton sharingButton.order = index } self.saveButtonChanges(false) } // MARK: - View Model Assets typealias SharingButtonsRowAction = () -> Void typealias SharingButtonsCellConfig = (UITableViewCell) -> Void struct SharingCellIdentifiers { static let SettingsCellIdentifier = "SettingsTableViewCellIdentifier" static let SortableSwitchCellIdentifier = "SortableSwitchTableViewCellIdentifier" static let SwitchCellIdentifier = "SwitchTableViewCellIdentifier" } /// Represents a section in the sharinging management table view. /// class SharingButtonsSection { var rows: [SharingButtonsRow] = [SharingButtonsRow]() var headerText: String? var footerText: String? var editing = false var canSort = false } /// Represents a row in the sharing management table view. /// class SharingButtonsRow { var cellIdentifier = "" var action: SharingButtonsRowAction? var configureCell: SharingButtonsCellConfig? } /// A sortable switch row. By convention this is only used for sortable button rows /// class SortableSharingSwitchRow: SharingButtonsRow { var buttonID: String init(buttonID: String) { self.buttonID = buttonID super.init() cellIdentifier = SharingCellIdentifiers.SortableSwitchCellIdentifier } } /// An unsortable switch row. /// class SharingSwitchRow: SharingButtonsRow { override init() { super.init() cellIdentifier = SharingCellIdentifiers.SwitchCellIdentifier } } /// A row for sharing settings that do not need a switch control in its cell. /// class SharingSettingRow: SharingButtonsRow { override init() { super.init() cellIdentifier = SharingCellIdentifiers.SettingsCellIdentifier } } }
gpl-2.0
c9cf8da346bcad293b92164cb7d76f24
35.523909
208
0.64498
5.358548
false
false
false
false
ioscreator/ioscreator
SwiftUIBackgroundColorTutorial/SwiftUIBackgroundColorTutorial/SceneDelegate.swift
1
2789
// // SceneDelegate.swift // SwiftUIBackgroundColorTutorial // // Created by Arthur Knopper on 28/08/2019. // Copyright © 2019 Arthur Knopper. All rights reserved. // import UIKit import SwiftUI class SceneDelegate: UIResponder, UIWindowSceneDelegate { var window: UIWindow? func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) { // Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`. // If using a storyboard, the `window` property will automatically be initialized and attached to the scene. // This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead). // Create the SwiftUI view that provides the window contents. let contentView = ContentView() // Use a UIHostingController as window root view controller. if let windowScene = scene as? UIWindowScene { let window = UIWindow(windowScene: windowScene) window.rootViewController = UIHostingController(rootView: contentView) self.window = window window.makeKeyAndVisible() } } func sceneDidDisconnect(_ scene: UIScene) { // Called as the scene is being released by the system. // This occurs shortly after the scene enters the background, or when its session is discarded. // Release any resources associated with this scene that can be re-created the next time the scene connects. // The scene may re-connect later, as its session was not neccessarily discarded (see `application:didDiscardSceneSessions` instead). } func sceneDidBecomeActive(_ scene: UIScene) { // Called when the scene has moved from an inactive state to an active state. // Use this method to restart any tasks that were paused (or not yet started) when the scene was inactive. } func sceneWillResignActive(_ scene: UIScene) { // Called when the scene will move from an active state to an inactive state. // This may occur due to temporary interruptions (ex. an incoming phone call). } func sceneWillEnterForeground(_ scene: UIScene) { // Called as the scene transitions from the background to the foreground. // Use this method to undo the changes made on entering the background. } func sceneDidEnterBackground(_ scene: UIScene) { // Called as the scene transitions from the foreground to the background. // Use this method to save data, release shared resources, and store enough scene-specific state information // to restore the scene back to its current state. } }
mit
d134d95f73be0b4396deeeb495fb7c3e
42.5625
147
0.7066
5.371869
false
false
false
false
diegosanchezr/Chatto
ChattoAdditions/Tests/Chat Items/TextMessages/TextMessagePresenterTests.swift
1
4601
/* The MIT License (MIT) Copyright (c) 2015-present Badoo Trading Limited. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ import XCTest import Chatto @testable import ChattoAdditions class TextMessagePresenterTests: XCTestCase, UICollectionViewDataSource { var presenter: TextMessagePresenter<TextMessageViewModelDefaultBuilder, TextMessageTestHandler>! let decorationAttributes = ChatItemDecorationAttributes(bottomMargin: 0, showsTail: false) override func setUp() { let viewModelBuilder = TextMessageViewModelDefaultBuilder() let sizingCell = TextMessageCollectionViewCell.sizingCell() let textStyle = TextMessageCollectionViewCellDefaultStyle() let baseStyle = BaseMessageCollectionViewCellDefaultSyle() let messageModel = MessageModel(uid: "uid", senderId: "senderId", type: "text-message", isIncoming: true, date: NSDate(), status: .Success) let textMessageModel = TextMessageModel(messageModel: messageModel, text: "Some text") self.presenter = TextMessagePresenter(messageModel: textMessageModel, viewModelBuilder: viewModelBuilder, interactionHandler: TextMessageTestHandler(), sizingCell: sizingCell, baseCellStyle: baseStyle, textCellStyle: textStyle, layoutCache: NSCache()) } func testThat_RegistersAndDequeuesCells() { let collectionView = UICollectionView(frame: CGRect.zero, collectionViewLayout: UICollectionViewFlowLayout()) TextMessagePresenter<TextMessageViewModelDefaultBuilder, TextMessageTestHandler>.registerCells(collectionView) collectionView.dataSource = self collectionView.reloadData() XCTAssertNotNil(self.presenter.dequeueCell(collectionView: collectionView, indexPath: NSIndexPath(forItem: 0, inSection: 0))) collectionView.dataSource = nil } func testThat_heightForCelReturnsPositiveHeight() { let height = self.presenter.heightForCell(maximumWidth: 320, decorationAttributes: self.decorationAttributes) XCTAssertTrue(height > 0) } func testThat_CellIsConfigured() { let cell = TextMessageCollectionViewCell(frame: CGRect.zero) self.presenter.configureCell(cell, decorationAttributes: self.decorationAttributes) XCTAssertEqual("Some text", cell.bubbleView.textMessageViewModel.text) } func testThat_CanCalculateHeightInBackground() { XCTAssertTrue(self.presenter.canCalculateHeightInBackground) } func testThat_ShouldShowMenuReturnsTrue() { let cell = TextMessageCollectionViewCell(frame: CGRect.zero) self.presenter.cellWillBeShown(cell) // Needs to have a reference to the current cell before getting menu calls XCTAssertTrue(self.presenter.shouldShowMenu()) } func testThat_CanPerformCopyAction() { XCTAssertTrue(self.presenter.canPerformMenuControllerAction(Selector("copy:"))) } // MARK: Helpers func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return 1 } func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { return self.presenter.dequeueCell(collectionView: collectionView, indexPath: indexPath) } } class TextMessageTestHandler: BaseMessageInteractionHandlerProtocol { typealias ViewModelT = TextMessageViewModel func userDidTapOnFailIcon(viewModel viewModel: ViewModelT) { } func userDidTapOnBubble(viewModel viewModel: ViewModelT) { } func userDidLongPressOnBubble(viewModel viewModel: ViewModelT) { } }
mit
895221cc0c7757bd9d0fec4a42578897
43.669903
259
0.768529
5.483909
false
true
false
false
googlemaps/maps-sdk-for-ios-samples
snippets/PlacesSnippets/PlacesSnippets/Swift/GetStartedViewController.swift
1
1510
// // GetStartedViewController.swift // PlacesSnippets // // Created by Chris Arriola on 7/13/20. // Copyright © 2020 Google. All rights reserved. // // [START maps_places_ios_get_started] import GooglePlaces import UIKit class GetStartedViewController : UIViewController { // Add a pair of UILabels in Interface Builder, and connect the outlets to these variables. @IBOutlet private var nameLabel: UILabel! @IBOutlet private var addressLabel: UILabel! private var placesClient: GMSPlacesClient! override func viewDidLoad() { super.viewDidLoad() placesClient = GMSPlacesClient.shared() } // Add a UIButton in Interface Builder, and connect the action to this function. @IBAction func getCurrentPlace(_ sender: UIButton) { let placeFields: GMSPlaceField = [.name, .formattedAddress] placesClient.findPlaceLikelihoodsFromCurrentLocation(withPlaceFields: placeFields) { [weak self] (placeLikelihoods, error) in guard let strongSelf = self else { return } guard error == nil else { print("Current place error: \(error?.localizedDescription ?? "")") return } guard let place = placeLikelihoods?.first?.place else { strongSelf.nameLabel.text = "No current place" strongSelf.addressLabel.text = "" return } strongSelf.nameLabel.text = place.name strongSelf.addressLabel.text = place.formattedAddress } } } // [END maps_places_ios_get_started]
apache-2.0
bbebd1aec3b1b5c5c62ca7983be71fe5
29.18
129
0.688535
4.451327
false
false
false
false
VladimirDinic/WDSideMenu
WDSideMenu/WDSideMenu/ViewControllers/MyWDViewController.swift
1
2102
// // MyWDViewController.swift // Dictionary // // Created by Vladimir Dinic on 2/16/17. // Copyright © 2017 Vladimir Dinic. All rights reserved. // import UIKit class MyWDViewController: WDViewController, SideMenuDelegate { override func viewDidLoad() { super.viewDidLoad() ControlManager.sharedInstance.sideMenuDelegate = self // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func setupParameters() { resizeMainContentView = resizeMainContentViewConfig sideMenuType = menuTypeConfig scaleFactor = scaleFactorConfig sizeMenuWidth = sizeMenuWidthConfig } override func getMainViewController() -> UIViewController? { let navigation:MyNavigationController = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "NavigationController") as! MyNavigationController self.mainContentDelegate = navigation navigation.wdSideView = self return navigation } override func getSideMenuViewController() -> UIViewController? { let sideMenuViewController = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "SideViewController") as! SideViewController self.sideMenuDelegate = sideMenuViewController return sideMenuViewController } func showMeSideMenu() { self.showSideMenu() } func hideMeSideMenu() { self.hideSideMenu() } func toggleMeSideMenu() { self.toggleSideMenu() } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
mit
dc946952523f4f112fa9b8ac31fdb58c
29.449275
180
0.685388
5.414948
false
true
false
false
huangboju/Moots
Examples/边缘侧滑/MedalCount Completed/MedalCount/Model/GamesDataStore.swift
1
1746
/** * Copyright (c) 2016 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 final class GamesDataStore { // MARK: - Properties private(set) var summer: [Games] = [] private(set) var winter: [Games] = [] // MARK: - Initializers init() { let path = Bundle.main.path(forResource: "GamesData", ofType: "plist") let rawData = NSDictionary(contentsOfFile: path!) as! [String: [[String: AnyObject]]] let rawSummer = rawData["summer"]!.reversed() for raw in rawSummer { self.summer.append(Games(dictionary: raw)) } let rawWinter = rawData["winter"]!.reversed() for raw in rawWinter { self.winter.append(Games(dictionary: raw)) } } }
mit
857b28a30700183f8d44973387ed32ba
37.8
89
0.719359
4.268949
false
false
false
false
barijaona/vienna-rss
Vienna/Sources/Shared/NSPopUpButtonExtensions.swift
4
2463
// // NSPopUpButtonExtensions.swift // Vienna // // Copyright 2020 // // 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 // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // import Cocoa extension NSPopUpButton { /// Add an item to the popup button menu with an associated image. The image is rescaled to 16x16 to fit in /// the menu. I've been trying to figure out how to get the actual menu item height but at a minimum, 16x16 /// is the conventional size for a 'small' document icon. So I'm OK with this for now. @objc func addItem(withTitle title: String, image: NSImage) { let newItem = NSMenuItem(title: title, action: nil, keyEquivalent: "") image.size = NSSize(width: 16, height: 16) newItem.image = image self.menu?.addItem(newItem) } /// Add an item to the popup button menu with the specified tag. @objc func addItem(withTitle title: String, tag: Int) { let newItem = NSMenuItem(title: title, action: nil, keyEquivalent: "") newItem.tag = tag self.menu?.addItem(newItem) } /// Add an item to the popup button menu with the specified tag and represented object @objc func addItem(withTitle title: String, tag: Int, representedObject object: Any) { let newItem = NSMenuItem(title: title, action: nil, keyEquivalent: "") newItem.tag = tag newItem.representedObject = object self.menu?.addItem(newItem) } /// Add an item to the popup button menu with the specified represented object. @objc func addItem(withTitle title: String, representedObject object: Any) { let newItem = NSMenuItem(title: title, action: nil, keyEquivalent: "") newItem.representedObject = object self.menu?.addItem(newItem) } /// Inserts the specified menu item into the popup menu at the given index and assigns it /// an initial tag value. @objc func insertItem(withTitle title: String, tag: Int, atIndex index: Int) { let newItem = NSMenuItem(title: title, action: nil, keyEquivalent: "") newItem.tag = tag self.menu?.insertItem(newItem, at: index) } }
apache-2.0
c12261d774d174b40596d096caf75a60
34.695652
108
0.725538
3.748858
false
false
false
false
realami/Msic
weekTwo/weekTwo/Controllers/SecondViewController.swift
1
2351
// // SecondViewController.swift // weekTwo // // Created by Cyan on 28/10/2017. // Copyright © 2017 Cyan. All rights reserved. // import UIKit import Then import SnapKit extension UIColor { class var randomColor:UIColor { get { let red = CGFloat(arc4random()%256)/255.0 let green = CGFloat(arc4random()%256)/255.0 let blue = CGFloat(arc4random()%256)/255.0 return UIColor(red: red, green: green, blue: blue, alpha: 1.0) } } } class SecondViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource { var collectionView: UICollectionView! override func viewDidLoad() { super.viewDidLoad() let flowLayout = UICollectionViewFlowLayout().then { $0.scrollDirection = .horizontal $0.itemSize = CGSize(width: UIScreen.main.bounds.width / 2, height: UIScreen.main.bounds.height / 3) $0.minimumLineSpacing = 44 $0.minimumInteritemSpacing = 44 } collectionView = UICollectionView(frame: view.bounds, collectionViewLayout: flowLayout).then { $0.dataSource = self $0.delegate = self $0.backgroundColor = .clear $0.register(CollectionViewCell.self, forCellWithReuseIdentifier: CollectionViewCell.cellId) } view.addSubview(collectionView) collectionView.snp.makeConstraints { $0.center.equalTo(view) $0.left.equalTo(view.snp.left).offset(21) $0.right.equalTo(view.snp.right).offset(-21) $0.height.equalTo(view.bounds.height / 2) } title = "Cards" } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return 12 } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: CollectionViewCell.cellId, for: indexPath) as! CollectionViewCell cell.backgroundColor = UIColor.randomColor cell.icon.image = UIImage(named: "icon_\(indexPath.row % 4)") cell.label.text = "item - \(indexPath.row + 1)" return cell } }
mit
591ee2b603cd0a5115eab6dc7858b4bc
31.191781
140
0.62766
4.825462
false
false
false
false
huonw/swift
test/SILOptimizer/closure_lifetime_fixup_objc.swift
1
5628
// RUN: %target-swift-frontend %s -emit-sil -o - | %FileCheck %s // REQUIRES: objc_interop import Foundation @objc public protocol DangerousEscaper { @objc func malicious(_ mayActuallyEscape: () -> ()) } // CHECK: sil @$S27closure_lifetime_fixup_objc19couldActuallyEscapeyyyyc_AA16DangerousEscaper_ptF : $@convention(thin) (@guaranteed @callee_guaranteed () -> (), @guaranteed DangerousEscaper) -> () { // CHECK: bb0([[ARG:%.*]] : $@callee_guaranteed () -> (), [[SELF:%.*]] : $DangerousEscaper): // CHECK: [[OE:%.*]] = open_existential_ref [[SELF]] // Copy (1). // CHECK: strong_retain [[ARG]] : $@callee_guaranteed () -> () // Extend the lifetime to the end of this function (2). // CHECK: strong_retain [[ARG]] : $@callee_guaranteed () -> () // CHECK: [[OPT_CLOSURE:%.*]] = enum $Optional<@callee_guaranteed () -> ()>, #Optional.some!enumelt.1, [[ARG]] : $@callee_guaranteed () -> () // CHECK: [[NE:%.*]] = convert_escape_to_noescape [[ARG]] : $@callee_guaranteed () -> () to $@noescape @callee_guaranteed () -> () // CHECK: [[WITHOUT_ACTUALLY_ESCAPING_THUNK:%.*]] = function_ref @$SIg_Ieg_TR : $@convention(thin) (@noescape @callee_guaranteed () -> ()) -> () // CHECK: [[C:%.*]] = partial_apply [callee_guaranteed] [[WITHOUT_ACTUALLY_ESCAPING_THUNK]]([[NE]]) : $@convention(thin) (@noescape @callee_guaranteed () -> ()) -> () // Sentinel without actually escaping closure (3). // CHECK: [[SENTINEL:%.*]] = mark_dependence [[C]] : $@callee_guaranteed () -> () on [[NE]] : $@noescape @callee_guaranteed () -> () // Copy of sentinel (4). // CHECK: strong_retain [[SENTINEL]] : $@callee_guaranteed () -> () // CHECK: [[BLOCK_STORAGE:%.*]] = alloc_stack $@block_storage @callee_guaranteed () -> () // CHECK: [[CLOSURE_ADDR:%.*]] = project_block_storage [[BLOCK_STORAGE]] : $*@block_storage @callee_guaranteed () -> () // CHECK: store [[SENTINEL]] to [[CLOSURE_ADDR]] : $*@callee_guaranteed () -> () // CHECK: [[BLOCK_INVOKE:%.*]] = function_ref @$SIeg_IyB_TR : $@convention(c) (@inout_aliasable @block_storage @callee_guaranteed () -> ()) -> () // CHECK: [[BLOCK:%.*]] = init_block_storage_header [[BLOCK_STORAGE]] : $*@block_storage @callee_guaranteed () -> (), invoke [[BLOCK_INVOKE]] : $@convention(c) (@inout_aliasable @block_storage @callee_guaranteed () -> ()) -> (), type $@convention(block) @noescape () -> () // Optional sentinel (4). // CHECK: [[OPT_SENTINEL:%.*]] = enum $Optional<@callee_guaranteed () -> ()>, #Optional.some!enumelt.1, [[SENTINEL]] : $@callee_guaranteed () -> () // Copy of sentinel closure (5). // CHECK: [[BLOCK_COPY:%.*]] = copy_block [[BLOCK]] : $@convention(block) @noescape () -> () // Release of sentinel closure (3). // CHECK: destroy_addr [[CLOSURE_ADDR]] : $*@callee_guaranteed () -> () // CHECK: dealloc_stack [[BLOCK_STORAGE]] : $*@block_storage @callee_guaranteed () -> () // Release of closure copy (1). // CHECK: strong_release %0 : $@callee_guaranteed () -> () // CHECK: [[METH:%.*]] = objc_method [[OE]] : $@opened("{{.*}}") DangerousEscaper, #DangerousEscaper.malicious!1.foreign : <Self where Self : DangerousEscaper> (Self) -> (() -> ()) -> (), $@convention(objc_method) <τ_0_0 where τ_0_0 : DangerousEscaper> (@convention(block) @noescape () -> (), τ_0_0) -> () // CHECK: apply [[METH]]<@opened("{{.*}}") DangerousEscaper>([[BLOCK_COPY]], [[OE]]) : $@convention(objc_method) <τ_0_0 where τ_0_0 : DangerousEscaper> (@convention(block) @noescape () -> (), τ_0_0) -> () // Release sentinel closure copy (5). // CHECK: strong_release [[BLOCK_COPY]] : $@convention(block) @noescape () -> () // CHECK: [[ESCAPED:%.*]] = is_escaping_closure [objc] [[OPT_SENTINEL]] : $Optional<@callee_guaranteed () -> ()> // CHECK: cond_fail [[ESCAPED]] : $Builtin.Int1 // Release of sentinel copy (4). // CHECK: release_value [[OPT_SENTINEL]] : $Optional<@callee_guaranteed () -> ()> // Extendend lifetime (2). // CHECK: release_value [[OPT_CLOSURE]] : $Optional<@callee_guaranteed () -> ()> // CHECK: return public func couldActuallyEscape(_ closure: @escaping () -> (), _ villian: DangerousEscaper) { villian.malicious(closure) } // We need to store nil on the back-edge. // CHECK sil {{.*}}dontCrash // CHECK: is_escaping_closure [objc] // CHECK: cond_fail // CHECK: destroy_addr %0 // CHECK: [[NONE:%.*]] = enum $Optional<@callee_guaranteed () -> ()>, #Optional.none!enumelt // CHECK: store [[NONE]] to %0 : $*Optional<@callee_guaranteed () -> ()> public func dontCrash() { for i in 0 ..< 2 { let queue = DispatchQueue(label: "Foo") queue.sync { } } } @_silgen_name("getDispatchQueue") func getDispatchQueue() -> DispatchQueue // We must not release the closure after calling super.deinit. // CHECK: sil hidden @$S27closure_lifetime_fixup_objc1CCfD : $@convention(method) (@owned C) -> () { // CHECK: bb0([[SELF:%.*]] : $C): // CHECK: [[F:%.*]] = function_ref @$S27closure_lifetime_fixup_objc1CCfdyyXEfU_ // CHECK: [[PA:%.*]] = partial_apply [callee_guaranteed] [[F]](%0) // CHECK: [[OPT:%.*]] = enum $Optional<@callee_guaranteed () -> ()>, #Optional.some!enumelt.1, [[PA]] // CHECK: [[DEINIT:%.*]] = objc_super_method [[SELF]] : $C, #NSObject.deinit!deallocator.foreign // CHECK: release_value [[OPT]] : $Optional<@callee_guaranteed () -> ()> // CHECK: [[SUPER:%.*]] = upcast [[SELF]] : $C to $NSObject // user: %34 // CHECK-NEXT: apply [[DEINIT]]([[SUPER]]) : $@convention(objc_method) (NSObject) -> () // CHECK-NEXT: [[T:%.*]] = tuple () // CHECK-NEXT: return [[T]] : $() class C: NSObject { deinit { getDispatchQueue().sync(execute: { _ = self }) } }
apache-2.0
f146f267baf907b596cd0ad22aec7595
54.117647
307
0.604945
3.453317
false
false
false
false
kosicki123/WWDC
WWDC/DownloadProgressViewController.swift
1
5292
// // DownloadProgressViewController.swift // WWDC // // Created by Guilherme Rambo on 22/04/15. // Copyright (c) 2015 Guilherme Rambo. All rights reserved. // import Cocoa import ViewUtils enum DownloadProgressViewButtonState : Int { case NoDownload case Downloaded case Downloading case Paused } class DownloadProgressViewController: NSViewController { var session: Session! { didSet { updateUI() } } @IBOutlet var downloadButton: NSButton! @IBOutlet var progressIndicator: GRActionableProgressIndicator? private var downloadStartedHndl: AnyObject? private var downloadFinishedHndl: AnyObject? private var downloadChangedHndl: AnyObject? private var downloadCancelledHndl: AnyObject? private var downloadPausedHndl: AnyObject? private var downloadResumedHndl: AnyObject? private var subscribed: Bool = false var downloadFinishedCallback: () -> () = {} override func viewDidLoad() { super.viewDidLoad() updateUI() } deinit { NSNotificationCenter.defaultCenter().removeObserver(self.downloadStartedHndl!) NSNotificationCenter.defaultCenter().removeObserver(self.downloadFinishedHndl!) NSNotificationCenter.defaultCenter().removeObserver(self.downloadChangedHndl!) NSNotificationCenter.defaultCenter().removeObserver(self.downloadCancelledHndl!) NSNotificationCenter.defaultCenter().removeObserver(self.downloadPausedHndl!) NSNotificationCenter.defaultCenter().removeObserver(self.downloadResumedHndl!) } private func updateUI() { progressIndicator?.doubleAction = "showDownloadsWindow:" if let session = session { if session.hd_url != nil { view.hidden = false updateDownloadStatus() } else { view.hidden = true } } else { view.hidden = true } } private func updateButtonVisibility(visibility: DownloadProgressViewButtonState) { switch (visibility) { case .NoDownload: self.progressIndicator?.hidden = true self.downloadButton.hidden = false case .Downloaded: self.progressIndicator?.hidden = true self.downloadButton.hidden = true case .Downloading: self.progressIndicator?.hidden = false self.downloadButton.hidden = true case .Paused: self.progressIndicator?.hidden = false self.downloadButton.hidden = true } } private func subscribeForNotifications() { let nc = NSNotificationCenter.defaultCenter() self.downloadStartedHndl = nc.addObserverForName(VideoStoreNotificationDownloadStarted, object: nil, queue: NSOperationQueue.mainQueue()) { note in if !self.isThisNotificationForMe(note) { return } self.updateButtonVisibility(.Downloading) } self.downloadFinishedHndl = nc.addObserverForName(VideoStoreNotificationDownloadFinished, object: nil, queue: NSOperationQueue.mainQueue()) { note in if !self.isThisNotificationForMe(note) { return } self.updateButtonVisibility(.Downloaded) self.downloadFinishedCallback() } self.downloadChangedHndl = nc.addObserverForName(VideoStoreNotificationDownloadProgressChanged, object: nil, queue: NSOperationQueue.mainQueue()) { note in if !self.isThisNotificationForMe(note) { return } self.updateButtonVisibility(.Downloading) if let info = note.userInfo { if let totalBytesExpectedToWrite = info["totalBytesExpectedToWrite"] as? Int { self.progressIndicator?.maxValue = Double(totalBytesExpectedToWrite) } if let totalBytesWritten = info["totalBytesWritten"] as? Int { self.progressIndicator?.doubleValue = Double(totalBytesWritten) } } } self.downloadCancelledHndl = nc.addObserverForName(VideoStoreNotificationDownloadCancelled, object: nil, queue: NSOperationQueue.mainQueue()) { note in self.updateButtonVisibility(.NoDownload) } self.downloadPausedHndl = nc.addObserverForName(VideoStoreNotificationDownloadPaused, object: nil, queue: NSOperationQueue.mainQueue()) { note in self.updateButtonVisibility(.Paused) } self.downloadResumedHndl = nc.addObserverForName(VideoStoreNotificationDownloadResumed, object: nil, queue: NSOperationQueue.mainQueue()) { note in self.updateButtonVisibility(.Downloading) } self.subscribed = true } private func updateDownloadStatus() { if self.subscribed == false { self.subscribeForNotifications() } if VideoStore.SharedStore().isDownloading(session.hd_url!) { self.updateButtonVisibility(.Downloading) } else { if VideoStore.SharedStore().hasVideo(session.hd_url!) { self.updateButtonVisibility(.Downloaded) } else { self.updateButtonVisibility(.NoDownload) } } } private func isThisNotificationForMe(note: NSNotification!) -> Bool { // we don't have a downloadable session, so this is clearly not for us if session == nil { return false } if session.hd_url == nil { return false } if let url = note.object as? String { if url != session.hd_url! { // notification's URL doesn't match our session's URL return false } } else { // notification's object is not a valid string return false } // this is for us return true } @IBAction func download(sender: NSButton) { if session == nil { return } if let url = session.hd_url { VideoStore.SharedStore().download(url) } } }
bsd-2-clause
68851891cdb1c7477d7d458975a84d0f
29.068182
157
0.737528
4.108696
false
false
false
false
joshjeong/twitter
Twitter/Twitter/MentionsViewController.swift
1
2868
// // MentionsViewController.swift // Twitter // // Created by Josh Jeong on 4/21/17. // Copyright © 2017 JoshJeong. All rights reserved. // import UIKit class MentionsViewController: UIViewController { @IBOutlet weak var tableView: UITableView! let refreshControl = UIRefreshControl() var tweets = [Tweet]() override func viewDidLoad() { super.viewDidLoad() tableView.rowHeight = UITableViewAutomaticDimension tableView.estimatedRowHeight = 200 refreshControl.addTarget(self, action: #selector(self.refreshTableData(_:)), for: UIControlEvents.valueChanged) tableView.insertSubview(refreshControl, at: 0) refreshTableData(refreshControl) NotificationCenter.default.addObserver(forName: NSNotification.Name(rawValue: "didTapRetweet"), object: nil, queue: OperationQueue.main) { (notification) in if let tweet = notification.userInfo?["tweet"] as? Tweet { let vc = self.storyboard?.instantiateViewController(withIdentifier: "ComposeViewController") as! ComposeViewController vc.tweet = tweet self.navigationController?.pushViewController(vc, animated: true) } } } @IBAction func onLogoutButton(_ sender: UIBarButtonItem) { self.dismiss(animated: true, completion: nil) } func refreshTableData(_ refreshControl: UIRefreshControl) { TwitterClient.sharedInstance?.mentionsTimeLine(success: { (tweets) in self.tweets = tweets self.tableView.reloadData() }, failure: { (error) in }) refreshControl.endRefreshing() } @IBAction func onShowComposeViewController(_ sender: UIBarButtonItem) { let vc = storyboard?.instantiateViewController(withIdentifier: "ComposeViewController") as! ComposeViewController navigationController?.pushViewController(vc, animated: true) } } extension MentionsViewController: UITableViewDelegate, UITableViewDataSource { func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "TweetTableViewCell", for: indexPath) as! TweetTableViewCell cell.tweet = tweets[indexPath.row] cell.selectionStyle = .none return cell } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return tweets.count } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let vc = storyboard?.instantiateViewController(withIdentifier: "DetailViewController") as! DetailViewController vc.tweet = tweets[indexPath.row] navigationController?.pushViewController(vc, animated: true) } }
mit
9ccfedf3802cafe16f3e843ebf563852
38.273973
164
0.683641
5.577821
false
false
false
false