repo_name
stringlengths
6
91
path
stringlengths
8
968
copies
stringclasses
210 values
size
stringlengths
2
7
content
stringlengths
61
1.01M
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
6
99.8
line_max
int64
12
1k
alpha_frac
float64
0.3
0.91
ratio
float64
2
9.89
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
RoRoche/iOSSwiftStarter
iOSSwiftStarter/iOSSwiftStarter/Classes/Common/Store/API/Queries/QueryListRepos.swift
1
2218
// // QueryListRepos.swift // iOSSwiftStarter // // Created by Romain Rochegude on 13/12/2015. // Copyright © 2015 Romain Rochegude. All rights reserved. // import Foundation import SwiftTask import Alamofire import ObjectMapper import Kugel public class OnQueryListReposDidFinish: AbstractQueryNotification { public static let Name: String = "OnQueryListReposDidFinish"; } class QueryListRepos: Task<Void, Array<RepoDTO>, NSError> { init(user: String!) { let initClosure: InitClosure = { progress, fulfill, reject, configure in let request = Alamofire.request(ApiService.ListRepos(user: user, sort: ApiService.ListReposSort.DESC)) .responseJSON { response in if(response.result.error != nil) { reject(response.result.error!); } else { if let JSON = response.result.value { let repos: Array<RepoDTO> = Mapper<RepoDTO>().mapArray(JSON)!; fulfill(repos); } else { let error: NSError = NSError(domain: "JSON parsing", code: 0, userInfo: [:]); reject(error); } } } // we plug the cancel method of the Task to the cancel method of the request configure.cancel = { request.cancel(); } }; super.init(weakified: false, paused: false, initClosure: initClosure); self.success { (value: Array<RepoDTO>) -> Void in let userInfo: [NSObject: AnyObject] = OnQueryListReposDidFinish.buildUserInfoSuccess(value as AnyObject); Kugel.publish(OnQueryListReposDidFinish.Name, object: self, userInfo:userInfo); }.failure { (error: NSError?, isCancelled: Bool) -> Void in let userInfo: [NSObject: AnyObject] = OnQueryListReposDidFinish.buildUserInfoFailure(error!, isCancelled: isCancelled); Kugel.publish(OnQueryListReposDidFinish.Name, object: self, userInfo:userInfo); } } }
apache-2.0
bb1e060831d79618bfc343581e46a63e
37.241379
135
0.571493
4.872527
false
false
false
false
blockchain/My-Wallet-V3-iOS
Modules/Platform/Sources/PlatformUIKit/BuySellUIKit/Core/Components/LinkedCardView/LinkedCardView.swift
1
1246
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import RxSwift final class LinkedCardView: UIView { // MARK: - Public Properties var viewModel: LinkedCardViewModel! { willSet { disposeBag = DisposeBag() } didSet { guard let viewModel = viewModel else { return } badgeImageView.viewModel = viewModel.badgeImageViewModel viewModel.nameContent .drive(cardNameLabel.rx.content) .disposed(by: disposeBag) viewModel.limitContent .drive(cardLimitLabel.rx.content) .disposed(by: disposeBag) } } // MARK: - Rx private var disposeBag = DisposeBag() // MARK: - Private IBOutlets @IBOutlet private var badgeImageView: BadgeImageView! @IBOutlet private var cardNameLabel: UILabel! @IBOutlet private var cardLimitLabel: UILabel! // MARK: - Setup override init(frame: CGRect) { super.init(frame: frame) setup() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setup() } private func setup() { fromNib(in: .module) clipsToBounds = true } }
lgpl-3.0
e3430d7a378001bddea5b196d257e483
22.055556
68
0.594378
4.901575
false
false
false
false
Animaxx/A-VibrancyView
A_VibrancyView/A_VibrancyView.swift
1
3597
// // A_VibrancyView.swift // A_VibrancyView_Demo // // Created by Animax Deng on 2/19/16. // Copyright © 2016 Animax Deng. All rights reserved. // import UIKit class A_VibrancyView: UIView { private var blurEffect:UIBlurEffect? = nil private var effectView:UIVisualEffectView? = nil private var vibrancyView:UIVisualEffectView? = nil override func awakeFromNib() { super.awakeFromNib() self.backgroundColor = UIColor.clearColor() } override func willMoveToSuperview(newSuperview: UIView?) { super.willMoveToSuperview(newSuperview) self.attachEffectView() } func presentEffect(style:UIBlurEffectStyle = .Light, animationDuration:Double = 0.5 ) { self.blurEffect = UIBlurEffect(style: style) let block = { () -> Void in self.effectView?.effect = self.blurEffect let vibrancy = UIVibrancyEffect(forBlurEffect: self.blurEffect!) self.vibrancyView?.effect = vibrancy } if (animationDuration > 0.0) { UIView.animateWithDuration(animationDuration, animations: block) } else { block() } } private func attachEffectView() { if self.vibrancyView != nil && self.effectView != nil { return } self.effectView = UIVisualEffectView() if let effectview = self.effectView { self.insertSubview(effectview, atIndex: 0) self.autoFullsize(effectview) self.vibrancyView = UIVisualEffectView() effectview.contentView.addSubview(self.vibrancyView!) self.autoFullsize(self.vibrancyView!) } self.layoutIfNeeded() } func convertAllSubview() { if let transparencyView = self.vibrancyView { for item in self.subviews { if item != self.effectView && item != self.vibrancyView { transparencyView.contentView.addSubview(item) } } } } func recoverAllSubview() { if let transparencyView = self.vibrancyView { for item in transparencyView.contentView.subviews { self.addSubview(item); } } } // MARK: Helping methods private func autoFullsize(subview:UIView) { if let superview = subview.superview { subview.translatesAutoresizingMaskIntoConstraints = false superview.addConstraint(NSLayoutConstraint.init(item: superview, attribute: .Top, relatedBy: .Equal, toItem:subview , attribute: .Top, multiplier: 1.0, constant: 0)) superview.addConstraint(NSLayoutConstraint.init(item: subview, attribute: .Bottom, relatedBy: .Equal, toItem: superview, attribute: .Bottom, multiplier: 1.0, constant: 0)) superview.addConstraint(NSLayoutConstraint.init(item: superview, attribute: .Left, relatedBy: .Equal, toItem: subview, attribute: .Left, multiplier: 1.0, constant: 0)) superview.addConstraint(NSLayoutConstraint.init(item: subview, attribute: .Right, relatedBy: .Equal, toItem: superview, attribute: .Right, multiplier: 1.0, constant: 0)) } } // MARK: Custom properties @IBInspectable var alphaOfEffect: CGFloat { get { if let effectview = self.effectView { return effectview.alpha } else { return 1.0 } } set { self.effectView?.alpha = newValue } } }
mit
44c028d6714a7f7aa0f753b22226318b
33.912621
183
0.606507
5.008357
false
false
false
false
rsyncOSX/RsyncOSX
RsyncOSX/ReadUserConfigurationJSON.swift
1
1477
// // ReadUserConfigurationsJSON.swift // RsyncUI // // Created by Thomas Evensen on 12/02/2022. // import Combine import Foundation class ReadUserConfigurationJSON: NamesandPaths { var filenamedatastore = [SharedReference.shared.userconfigjson] var subscriptons = Set<AnyCancellable>() @discardableResult init() { super.init(.configurations) filenamedatastore.publisher .compactMap { filenamejson -> URL in var filename = "" if let path = fullpathmacserial { filename = path + "/" + filenamejson } return URL(fileURLWithPath: filename) } .tryMap { url -> Data in try Data(contentsOf: url) } .decode(type: DecodeUserConfiguration.self, decoder: JSONDecoder()) .sink { completion in switch completion { case .finished: // print("The publisher finished normally.") return case .failure: // No file, write new file with default values WriteUserConfigurationJSON(UserConfiguration()) } } receiveValue: { [unowned self] data in UserConfiguration(data) subscriptons.removeAll() }.store(in: &subscriptons) _ = Setrsyncpath() _ = RsyncVersionString() } }
mit
cb5139a244be9fc5d1c3e651456d5da0
31.108696
79
0.542316
5.275
false
true
false
false
vector-im/vector-ios
Riot/Modules/Room/Views/RemoveJitsiWidget/RemoveJitsiWidgetView.swift
1
6081
// // Copyright 2021 New Vector Ltd // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // import Foundation import Reusable @objcMembers class RemoveJitsiWidgetView: UIView { private enum Constants { static let activationThreshold: CGFloat = 0.5 } private enum State: Equatable { case notStarted case sliding(percentage: CGFloat) case completed static func == (lhs: State, rhs: State) -> Bool { switch (lhs, rhs) { case (.notStarted, .notStarted): return true case (let .sliding(percentage1), let .sliding(percentage2)): return percentage1 == percentage2 case (.completed, .completed): return true default: return false } } } @IBOutlet private weak var slidingViewLeadingConstraint: NSLayoutConstraint! @IBOutlet private weak var slidingView: UIView! @IBOutlet private weak var slidingViewLabel: UILabel! { didSet { slidingViewLabel.text = VectorL10n.roomSlideToEndGroupCall } } @IBOutlet private weak var arrowsView: ArrowsAnimationView! @IBOutlet private weak var hangupView: UIView! @IBOutlet private weak var hangupImage: UIImageView! @IBOutlet private weak var topSeparatorView: UIView! @IBOutlet private weak var bottomSeparatorView: UIView! private var state: State = .notStarted private var theme: Theme = ThemeService.shared().theme // MARK - Private private func configure(withState state: State) { switch state { case .notStarted: arrowsView.isAnimating = false hangupView.backgroundColor = .clear hangupImage.tintColor = theme.noticeColor slidingViewLeadingConstraint.constant = 0 case .sliding(let percentage): arrowsView.isAnimating = true if percentage < Constants.activationThreshold { hangupView.backgroundColor = .clear hangupImage.tintColor = theme.noticeColor } else { hangupView.backgroundColor = theme.noticeColor hangupImage.tintColor = theme.callScreenButtonTintColor } slidingViewLeadingConstraint.constant = percentage * slidingView.frame.width case .completed: arrowsView.isAnimating = false hangupView.backgroundColor = theme.noticeColor hangupImage.tintColor = theme.callScreenButtonTintColor } } private func updateState(to newState: State) { guard newState != state else { return } configure(withState: newState) state = newState if state == .completed { delegate?.removeJitsiWidgetViewDidCompleteSliding(self) } } // MARK: - Touch Handling override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { super.touchesBegan(touches, with: event) if state == .notStarted { updateState(to: .sliding(percentage: 0)) } } override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) { super.touchesMoved(touches, with: event) switch state { case .sliding: if let touch = touches.first { let touchLocation = touch.location(in: self) if frame.contains(touchLocation) { let percentage = touchLocation.x / frame.width updateState(to: .sliding(percentage: percentage)) } } default: break } } override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) { super.touchesEnded(touches, with: event) switch state { case .sliding(let percentage): if percentage < Constants.activationThreshold { updateState(to: .notStarted) } else { updateState(to: .completed) } default: break } } override func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent?) { super.touchesCancelled(touches, with: event) switch state { case .sliding(let percentage): if percentage < Constants.activationThreshold { updateState(to: .notStarted) } else { updateState(to: .completed) } default: break } } // MARK: - API weak var delegate: RemoveJitsiWidgetViewDelegate? static func instantiate() -> RemoveJitsiWidgetView { let view = RemoveJitsiWidgetView.loadFromNib() view.update(theme: ThemeService.shared().theme) return view } func reset() { updateState(to: .notStarted) } } // MARK: - NibLoadable extension RemoveJitsiWidgetView: NibLoadable { } // MARK: - Themable extension RemoveJitsiWidgetView: Themable { func update(theme: Theme) { self.theme = theme self.backgroundColor = theme.headerBackgroundColor slidingViewLabel.textColor = theme.textPrimaryColor arrowsView.update(theme: theme) topSeparatorView.backgroundColor = theme.lineBreakColor bottomSeparatorView.backgroundColor = theme.lineBreakColor configure(withState: state) } }
apache-2.0
41649040a9d9a1ba6a283bf75683ef96
30.345361
88
0.60467
5.215266
false
false
false
false
jdbateman/Lendivine
OAuthSwift-master/OAuthSwiftDemo/KivaUserAccount.swift
1
1160
// // KivaUserAccount.swift // OAuthSwift // // Created by john bateman on 10/29/15. // Copyright © 2015 Dongri Jin. All rights reserved. // import Foundation class KivaUserAccount { var firstName: String = "" var lastName: String = "" var lenderID: String = "" var id: NSNumber = -1 var isPublic: Bool = false var isDeveloper: Bool = false // designated initializer init(dictionary: [String: AnyObject]?) { if let dictionary = dictionary { if let fname = dictionary["first_name"] as? String { firstName = fname } if let lname = dictionary["last_name"] as? String { lastName = lname } if let liD = dictionary["lender_id"] as? String { lenderID = liD } if let iD = dictionary["id"] as? NSNumber { id = iD } if let isPub = dictionary["is_public"] as? Bool { isPublic = isPub } if let dev = dictionary["is_developer"] as? Bool { isDeveloper = dev } } } }
mit
0448ca460187cc4614f360360eaefe83
25.976744
64
0.509922
4.390152
false
false
false
false
suifengqjn/douyu
douyu/douyu/Classes/Home/Controller/GameController.swift
1
2952
// // GameController.swift // douyu // // Created by qianjn on 2017/1/1. // Copyright © 2017年 SF. All rights reserved. // import UIKit private let kEdgeMargin: CGFloat = 10 private let k_Item_Width: CGFloat = (kScreenWidth - 2 * kEdgeMargin) / 3 private let k_Item_Height: CGFloat = k_Item_Width * 6 / 5 private let kGameViewH : CGFloat = 90 private let kGameCellID = "kGameCellID" class GameController: UIViewController { fileprivate lazy var gameModel:GameViewModel = GameViewModel() fileprivate lazy var collectionView: UICollectionView = { [weak self] in let layout = UICollectionViewFlowLayout() layout.itemSize = CGSize(width: k_Item_Width, height: k_Item_Height) layout.minimumLineSpacing = 0 layout.minimumInteritemSpacing = 0 layout.sectionInset = UIEdgeInsets(top: 0, left: kEdgeMargin, bottom: 0, right: kEdgeMargin) let collView = UICollectionView(frame: (self?.view.bounds)!, collectionViewLayout: layout) collView.dataSource = self collView.backgroundColor = UIColor.white collView.autoresizingMask = [.flexibleWidth, .flexibleHeight] collView.register(UINib(nibName: "GameCell", bundle: nil), forCellWithReuseIdentifier: kGameCellID) return collView }() fileprivate lazy var collectionHeadTopView: CollectionHeader = { let headView = CollectionHeader.createHeadView() headView.frame = CGRect(x: 0, y: -kGameViewH, width: kScreenWidth, height: kGameViewH) headView.iconImage.image = UIImage(named: "Img_orange") headView.titlelabel.text = "常见" headView.moreBtn.isHidden = true return headView }() override func viewDidLoad() { super.viewDidLoad() buildUI() loadData() } } // MARK: - UI extension GameController { fileprivate func buildUI() { view.addSubview(collectionView) collectionView.addSubview(collectionHeadTopView) collectionView.contentInset = UIEdgeInsets(top: collectionHeadTopView.frame.height, left: 0, bottom: 0, right: 0) } } // MARK: - load data extension GameController { fileprivate func loadData() { gameModel.loadGamesData { self.collectionView.reloadData() } } } // MARK: - UICollectionView extension GameController: UICollectionViewDataSource { func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return gameModel.games.count; } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let game = gameModel.games[indexPath.item] let cell = collectionView.dequeueReusableCell(withReuseIdentifier: kGameCellID, for: indexPath) as? GameCell cell?.game = game return cell! } }
apache-2.0
3358406175cd2f30a7ff8283227da9e8
30.329787
121
0.672326
4.908333
false
false
false
false
spweau/Test_DYZB
Test_DYZB/Test_DYZB/Classes/Home/View/RecommendCycleView.swift
1
5083
// // RecommendCycleView.swift // Test_DYZB // // Created by Spweau on 2017/2/24. // Copyright © 2017年 sp. All rights reserved. // import UIKit private let kCycleCellID = "kCycleCellID" class RecommendCycleView: UIView { // MARK: 定义属性 var cycleTimer : Timer? var cycleModels : [CycleModel]? { didSet { // 1.刷新collectionView collectionView.reloadData() // 2.设置pageControl个数 pageControl.numberOfPages = cycleModels?.count ?? 0 // 3.默认滚动到中间某一个位置 let indexPath = IndexPath(item: (cycleModels?.count ?? 0) * 100, section: 0) collectionView.scrollToItem(at: indexPath, at: .left, animated: false) // 4.添加定时器 removeCycleTimer() addCycleTimer() } } // MARK: 控件属性 @IBOutlet weak var collectionView: UICollectionView! @IBOutlet weak var pageControl: UIPageControl! override func awakeFromNib() { super.awakeFromNib() // 设置该控件不随着父控件的拉伸而拉伸 autoresizingMask = UIViewAutoresizing() // 注册Cell collectionView.register(UINib(nibName: "CollectionCycleCell", bundle: nil), forCellWithReuseIdentifier: kCycleCellID) // collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: kCycleCellID) // // 设置 collectionView 的 layout // let layout = collectionView.collectionViewLayout as! UICollectionViewFlowLayout // // 在这里面设置的frame 就是xib的大小,不是我们设置的大小,所以在layoutSubviews里面设置 //// layout.itemSize = collectionView.bounds.size // layout.minimumLineSpacing = 0 // layout.minimumInteritemSpacing = 0 collectionView.isPagingEnabled = true } override func layoutSubviews() { super.layoutSubviews() // 设置 collectionView 的 layout let layout = collectionView.collectionViewLayout as! UICollectionViewFlowLayout // 在这里面设置的frame 就是xib的大小,不是我们设置的大小,所以在layoutSubviews里面设置 layout.itemSize = collectionView.bounds.size layout.minimumLineSpacing = 0 layout.minimumInteritemSpacing = 0 layout.scrollDirection = .horizontal } } // MARK:- 提供一个快速创建View的类方法 extension RecommendCycleView { class func recommendCycleView() -> RecommendCycleView { return Bundle.main.loadNibNamed("RecommendCycleView", owner: nil, options: nil)?.first as! RecommendCycleView } } // MARK:- 遵守UICollectionView的数据源协议 extension RecommendCycleView : UICollectionViewDataSource { func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return (cycleModels?.count ?? 0) * 10000 } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: kCycleCellID, for: indexPath) as! CollectionCycleCell cell.cycleModel = cycleModels![(indexPath as NSIndexPath).item % cycleModels!.count] cell.backgroundColor = indexPath.item % 2 == 0 ? UIColor.red : UIColor.blue return cell } } // MARK:- 遵守UICollectionView的代理协议 extension RecommendCycleView : UICollectionViewDelegate { func scrollViewDidScroll(_ scrollView: UIScrollView) { // 1.获取滚动的偏移量 let offsetX = scrollView.contentOffset.x + scrollView.bounds.width * 0.5 // 2.计算pageControl的currentIndex pageControl.currentPage = Int(offsetX / scrollView.bounds.width) % (cycleModels?.count ?? 1) } func scrollViewWillBeginDragging(_ scrollView: UIScrollView) { removeCycleTimer() } func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) { addCycleTimer() } } // MARK:- 对定时器的操作方法 extension RecommendCycleView { fileprivate func addCycleTimer() { cycleTimer = Timer(timeInterval: 3.0, target: self, selector: #selector(self.scrollToNext), userInfo: nil, repeats: true) RunLoop.main.add(cycleTimer!, forMode: RunLoopMode.commonModes) } fileprivate func removeCycleTimer() { cycleTimer?.invalidate() // 从运行循环中移除 cycleTimer = nil } @objc fileprivate func scrollToNext() { // 1.获取滚动的偏移量 let currentOffsetX = collectionView.contentOffset.x let offsetX = currentOffsetX + collectionView.bounds.width // 2.滚动该位置 collectionView.setContentOffset(CGPoint(x: offsetX, y: 0), animated: true) } }
mit
999c02c1f573d4c684b10fe0b7e58880
30
129
0.651316
5.330317
false
false
false
false
honghaoz/CrackingTheCodingInterview
Swift/LeetCode/Dynamic Programming/62_Unique Paths.swift
1
1714
// 62_Unique Paths // https://leetcode.com/problems/unique-paths/ // // Created by Honghao Zhang on 9/21/19. // Copyright © 2019 Honghaoz. All rights reserved. // // Description: // A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below). // //The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked 'Finish' in the diagram below). // //How many possible unique paths are there? // // //Above is a 7 x 3 grid. How many possible unique paths are there? // //Note: m and n will be at most 100. // //Example 1: // //Input: m = 3, n = 2 //Output: 3 //Explanation: //From the top-left corner, there are a total of 3 ways to reach the bottom-right corner: //1. Right -> Right -> Down //2. Right -> Down -> Right //3. Down -> Right -> Right //Example 2: // //Input: m = 7, n = 3 //Output: 28 // // 机器人从左上角出发,到右下角。求多少条不同的路径。 import Foundation class Num62 { // 经典DP文件,参考64 Minimum Path Sum // 坐标型动态规划 func uniquePaths(_ m: Int, _ n: Int) -> Int { guard m > 0 else { return 0 } guard n > 0 else { return 0 } // state: s[i][j] represents the number of unique path to (i, j) // initialize var s: [[Int]] = Array(repeating: Array(repeating: 0, count: n), count: m) s[0][0] = 1 // init row 0 for j in 1..<n { s[0][j] = 1 } // init column 0 for i in 1..<m { s[i][0] = 1 } // transition function for i in 1..<m { for j in 1..<n { s[i][j] = s[i - 1][j] + s[i][j - 1] } } return s[m - 1][n - 1] } }
mit
749a243ac1cbc2d2d8f5283b4414dadc
22.028169
173
0.583486
3.01105
false
false
false
false
HTWDD/HTWDresden-iOS
HTWDD/Core/Services/TimetableService.swift
1
1249
// // TimetableService.swift // HTWDD // // Created by Mustafa Karademir on 01.10.19. // Copyright © 2019 HTW Dresden. All rights reserved. // import Foundation import RxSwift class TimetableService: Service { // MARK: - Properties private var apiService: ApiService // MARK: - Lifecycle init(apiService: ApiService) { self.apiService = apiService } func load(parameters: ()) -> Observable<()> { return Observable.empty() } func requestTimetable() -> Observable<[Lesson]> { let (year, major, group, _) = KeychainService.shared.readStudyToken() if let year = year, let major = major, let group = group { return apiService .requestLessons(for: year, major: major, group: group) .observeOn(SerialDispatchQueueScheduler(qos: .background)) .asObservable() } else { return Observable.error(AuthError.noStudyToken) } } func requestElectiveLessons() -> Observable<[Lesson]> { return apiService.requestElectiveLessons() } } // MARK: - HasTimetable extension TimetableService: HasTimetable { var timetableService: TimetableService { return self } }
gpl-2.0
1b39d500ccd061286e2c203050ecd11c
26.130435
77
0.625
4.639405
false
false
false
false
wwu-pi/md2-framework
de.wwu.md2.framework/res/resources/ios/lib/controller/eventhandler/MD2OnClickHandler.swift
1
2041
// // MD2OnClickHandler.swift // md2-ios-library // // Created by Christoph Rieger on 30.07.15. // Copyright (c) 2015 Christoph Rieger. All rights reserved. // import UIKit /// Event handler for click events. class MD2OnClickHandler: MD2WidgetEventHandler { /// Convenience typealias for the tuple of action and widget typealias actionWidgetTuple = (MD2Action, MD2WidgetWrapper) /// The singleton instance. static let instance: MD2OnClickHandler = MD2OnClickHandler() /// The list of registered action-widget tuples. var actions: Dictionary<String, actionWidgetTuple> = [:] /// Singleton initializer. private init() { // Nothing to initialize } /** Register an action. :param: action The action to execute in case of an event. :param: widget The widget that the action should be bound to. */ func registerAction(action: MD2Action, widget: MD2WidgetWrapper) { actions[action.actionSignature] = (action, widget) } /** Unregister an action. :param: action The action to remove. :param: widget The widget the action was registered to. */ func unregisterAction(action: MD2Action, widget: MD2WidgetWrapper) { for (key, value) in actions { if key == action.actionSignature { actions[key] = nil break } } } /** Method that is called to fire an event. *Notice* Visible to Objective-C runtime to receive events from UI elements. :param: sender The widget sending the event. */ @objc func fire(sender: UIControl) { //println("Event fired to OnClickHandler: " + String(sender.tag) + "=" + WidgetMapping.fromRawValue(sender.tag).description) for (_, (action, widget)) in actions { if widget.widgetId == MD2WidgetMapping.fromRawValue(sender.tag) { action.execute() } } } }
apache-2.0
1152bb28d5f1a5a4506cc6765a71a13c
27.760563
132
0.609505
4.525499
false
false
false
false
wikimedia/wikipedia-ios
Wikipedia/Code/LoadingAnimationViewController.swift
1
3595
import UIKit class LoadingAnimationViewController: UIViewController { var theme: Theme = Theme.standard var cancelBlock: (() -> Void)? @IBOutlet private var satelliteImageView: UIImageView! @IBOutlet private var backgroundView: UIView! @IBOutlet private var cancelButton: UIButton! @IBOutlet private var backgroundImageView: UIImageView! @IBOutlet private var statusLabel: UILabel! override func viewDidLoad() { super.viewDidLoad() apply(theme: theme) cancelButton.setTitle(CommonStrings.cancelActionTitle, for: .normal) statusLabel.text = WMFLocalizedString("data-migration-status", value: "Updating...", comment: "Message displayed during a long running data migration.") view.accessibilityViewIsModal = true updateFonts() } @objc func applicationDidBecomeActive(_ notification: Notification) { satelliteImageView.startRotating() } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) satelliteImageView.startRotating() UIAccessibility.post(notification: UIAccessibility.Notification.screenChanged, argument: statusLabel) NotificationCenter.default.addObserver(self, selector: #selector(applicationDidBecomeActive), name: UIApplication.didBecomeActiveNotification, object: nil) } override func viewDidDisappear(_ animated: Bool) { super.viewDidDisappear(animated) satelliteImageView.stopRotating() UIAccessibility.post(notification: UIAccessibility.Notification.screenChanged, argument: nil) NotificationCenter.default.removeObserver(self, name: UIApplication.didBecomeActiveNotification, object: nil) } @IBAction func tappedCancel(_ sender: UIButton) { cancelBlock?() } override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) { super.traitCollectionDidChange(previousTraitCollection) updateFonts() } private func updateFonts() { cancelButton.titleLabel?.font = UIFont.wmf_font(.semiboldTitle3, compatibleWithTraitCollection: traitCollection) statusLabel.font = UIFont.wmf_font(.boldHeadline, compatibleWithTraitCollection: traitCollection) } } private extension UIView { var rotationKey: String { return "rotation" } func startRotating(duration: Double = 1) { let kAnimationKey = rotationKey if layer.animation(forKey: kAnimationKey) == nil { let animate = CABasicAnimation(keyPath: "transform.rotation") animate.duration = duration animate.repeatCount = Float.infinity animate.fromValue = 0.0 animate.toValue = Float(.pi * 2.0) layer.add(animate, forKey: kAnimationKey) } } func stopRotating() { let kAnimationKey = rotationKey if self.layer.animation(forKey: kAnimationKey) != nil { self.layer.removeAnimation(forKey: kAnimationKey) } } } extension LoadingAnimationViewController: Themeable { func apply(theme: Theme) { self.theme = theme guard viewIfLoaded != nil else { return } backgroundView.backgroundColor = theme.colors.paperBackground cancelButton.setTitleColor(theme.colors.link, for: .normal) backgroundImageView.tintColor = theme.colors.animationBackground statusLabel.textColor = theme.colors.primaryText } }
mit
31d58c5b0f8b9295b74020292d6cd0eb
34.95
163
0.678442
5.661417
false
false
false
false
justinjdickow/ios-map-zoom-scroll
map-zoom-scroll-test/map-zoom-scroll-test/ViewController.swift
1
2779
// // ViewController.swift // map-zoom-scroll-test // // Created by Justin Dickow on 10/17/14. // Copyright (c) 2014 undefined. All rights reserved. // import UIKit import MapKit class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate { @IBOutlet weak var mapView: MKMapView! @IBOutlet weak var tableView: UITableView! var last: Int = 0 let titles: [String] = ["Bob's Sale", "Justin's Sale", "Fire Sale", "Estate Sale", "Bob's Sale", "Justin's Sale", "Brooke's Sale", "Estate Sale", "Fire Sale"] override func viewDidLoad() { super.viewDidLoad() tableView.bounces = false tableView.delegate = self tableView.dataSource = self let location = CLLocationCoordinate2D( latitude: 51.50007773, longitude: -0.1246402 ) let span = MKCoordinateSpanMake(0.05, 0.05) let region = MKCoordinateRegion(center: location, span: span) mapView.setRegion(region, animated: true) let annotation = MKPointAnnotation() annotation.setCoordinate(location) annotation.title = "Big Ben" annotation.subtitle = "London" mapView.addAnnotation(annotation) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func scrollViewDidEndDragging(scrollView: UIScrollView, willDecelerate decelerate: Bool) { // Detect the table view cell that is at the top let visibleCells = self.tableView.indexPathsForVisibleRows() as [NSIndexPath] let top = visibleCells[0] if (top.row > last) { // zoom out } else if (top.row < last) { // zoom in } last = top.row } func scrollViewDidScroll(scrollView: UIScrollView) { } func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? { return "Nearby Sales" } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return titles.count } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let row = indexPath.row var cell = tableView.dequeueReusableCellWithIdentifier("reuseIdentifier") as UITableViewCell cell.textLabel!.text = String(row) + ": " + titles[row] return cell } func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return 100.0 } }
mit
6a208160151c8123b3d1a7e4e0ae83b1
29.877778
162
0.633321
4.989228
false
false
false
false
AndyQ/CNCPlotter
CNCPlotter/TouchBarIdentifiers.swift
1
858
// // TouchBarIdentifiers.swift // TouchBar // // Created by Andy Pereira on 10/31/16. // Copyright © 2016 Ray Wenderlich. All rights reserved. // import AppKit extension NSTouchBarItemIdentifier { static let infoLabelItem = NSTouchBarItemIdentifier("com.andyqua.InfoLabel") static let visitedLabelItem = NSTouchBarItemIdentifier("com.andyqua.VisitedLabel") static let visitSegmentedItem = NSTouchBarItemIdentifier("com.andyqua.VisitedSegementedItem") static let visitedItem = NSTouchBarItemIdentifier("com.andyqua.VisitedItem") static let ratingLabel = NSTouchBarItemIdentifier("com.andyqua.RatingLabel") static let ratingScrubber = NSTouchBarItemIdentifier("com.andyqua.RatingScrubber") } extension NSTouchBarCustomizationIdentifier { static let travelBar = NSTouchBarCustomizationIdentifier("com.andyqua.ViewController.TravelBar") }
apache-2.0
208281c6b2fd25e4ad8702173c10cbcd
37.954545
98
0.808635
4.534392
false
false
false
false
JOCR10/iOS-Curso
Tareas/Tarea 2/TareaNumerosPrimos/TareaNumerosPrimos/PrimosViewController.swift
1
1767
// // PrimosViewController.swift // TareaNumerosPrimos // // Created by Local User on 5/22/17. // Copyright © 2017 Local User. All rights reserved. // import UIKit class PrimosViewController: UIViewController { @IBOutlet weak var tableView: UITableView! var numerosPrimos = [Int]() override func viewDidLoad() { super.viewDidLoad() numerosPrimos = initializeArray() tableView.registerCustomCell(identifier: NumeroPrimoTableViewCell.getCellIdentifier()) // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func initializeArray()-> [Int]{ var array = [Int]() for index in 1...1000 { if index == 1 || !(2..<index).contains { index % $0 == 0 } { array.append(index) } } return array } } extension PrimosViewController: UITableViewDelegate, UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return numerosPrimos.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: NumeroPrimoTableViewCell.getCellIdentifier()) as! NumeroPrimoTableViewCell let value = numerosPrimos[indexPath.row] cell.primoLabel?.text = "\(value)" return cell } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 200 } }
mit
b0e1dc7cd2269b18e9094d8231344b9a
26.59375
140
0.625142
4.988701
false
false
false
false
sublimter/Meijiabang
KickYourAss/KickYourAss/ZXY_Start/ZXY_ThirdPartyFile/ZXY_NetHelperOperate.swift
3
5600
// // ZXY_NetHelperOperate.swift // KickYourAss // // Created by 宇周 on 15/1/20. // Copyright (c) 2015年 宇周. All rights reserved. // import UIKit let _ZXY_NetInstance = ZXY_NetHelperOperate() class ZXY_NetHelperOperate: NSObject { class var sharedInstance:ZXY_NetHelperOperate { return _ZXY_NetInstance } /** 判断网络连接状态 :param: statusBlock 当连接状态改变的时候将 状态码传递 */ func judgeNetCanConnect(currentStatus statusBlock: ((status :AFNetworkReachabilityStatus)->Void)?) -> Void { var net : AFNetworkReachabilityManager = AFNetworkReachabilityManager.sharedManager() net.startMonitoring() net.setReachabilityStatusChangeBlock(statusBlock) } /** 网络请求连接 :param: urlString 数据连接请求API :param: parameter 数据请求参数 :param: success 数据连接成功的时候的回调函数 :param: errors 数据连接失败的时候的回调函数 */ func startGetDataPost(urlString: String , parameter: Dictionary<String ,AnyObject>? , successBlock success:((returnDic : Dictionary<String ,AnyObject>)->Void)? , failBlock errors:((error: NSError) -> Void)?) { var afnet = AFHTTPRequestOperationManager() var ser = AFHTTPRequestSerializer() ser.timeoutInterval = 30 var stampTime = timeStamp() afnet.responseSerializer = AFJSONResponseSerializer() afnet.responseSerializer.acceptableContentTypes = NSSet(object: "text/html") afnet.requestSerializer = ser var sendParameter = Dictionary<String ,AnyObject>() if(parameter != nil) { sendParameter = parameter! sendParameter["timestamp"] = stampTime sendParameter["token"] = timeStampMD5("meijia"+stampTime) } else { var stampTime = timeStamp() //var sendParameter = Dictionary<String ,AnyObject>() sendParameter["timestamp"] = stampTime sendParameter["token"] = timeStampMD5("meijia"+stampTime) } afnet.POST(urlString, parameters: sendParameter, success: { (operation:AFHTTPRequestOperation!, anyObject: AnyObject!) -> Void in if(success != nil) { println(operation.responseString) var returnData = operation.responseData var json: AnyObject? = NSJSONSerialization.JSONObjectWithData(returnData, options: NSJSONReadingOptions.MutableLeaves, error: nil) var jsonDic : Dictionary<String , AnyObject> = json as Dictionary<String, AnyObject> success!(returnDic: jsonDic) } }, failure: { (operation: AFHTTPRequestOperation!, error: NSError!) -> Void in if(errors != nil) { errors!(error:error) } }) } func startPostImg(urlSring : String , parameter : Dictionary<String , AnyObject>? ,imgData: [NSData] , fileKey: String , success:((returnDic : Dictionary<String , AnyObject>) -> Void)? , failure:((failError : NSError) -> Void)?) { var afnet = AFHTTPRequestOperationManager() var ser = AFHTTPRequestSerializer() ser.timeoutInterval = 30 afnet.responseSerializer = AFJSONResponseSerializer() afnet.responseSerializer.acceptableContentTypes = NSSet(object: "text/html") afnet.requestSerializer = ser afnet.requestSerializer = ser var stampTime = timeStamp() var sendParameter = Dictionary<String ,AnyObject>() if(parameter != nil) { sendParameter = parameter! sendParameter["timestamp"] = stampTime sendParameter["token"] = timeStampMD5("meijia"+stampTime) } else { var stampTime = timeStamp() //var sendParameter = Dictionary<String ,AnyObject>() sendParameter["timestamp"] = stampTime sendParameter["token"] = timeStampMD5("meijia"+stampTime) } afnet.POST(urlSring, parameters: sendParameter, constructingBodyWithBlock: { (formData) -> Void in imgData.map({ formData.appendPartWithFileData($0, name: fileKey, fileName: "tiancailcy.jpg", mimeType: "image/jpeg") }) return }, success: { (operation, anyObject) -> Void in println(operation.responseString) if(success != nil) { var returnData = operation.responseData var json: AnyObject? = NSJSONSerialization.JSONObjectWithData(returnData, options: NSJSONReadingOptions.MutableLeaves, error: nil) var jsonDic : Dictionary<String , AnyObject> = json as Dictionary<String, AnyObject> success!(returnDic: jsonDic) } }) { (operation, error) -> Void in if(failure != nil) { failure!(failError:error) } } } /** 获取时间戳 :returns: 返回时间戳 */ func timeStamp() -> String { let a = Int(NSDate().timeIntervalSince1970) return "\(a)" } /** 将时间戳加密 :param: addString 需要加密的字符串 :returns: 返回加密后的时间戳 */ func timeStampMD5(addString : NSString) -> String { return addString.md5() } }
mit
703986a4a8c04b0d81519d7bbb862fd2
33.075949
232
0.592125
4.885662
false
false
false
false
lucasmpaim/EasyRest
Sources/EasyRest/Classes/API/API.swift
1
9857
// // API.swift // RestClient // // Created by Guizion Labs on 10/03/16. // Copyright © 2016 Guizion Labs. All rights reserved. // import Foundation import Alamofire import UIKit open class API <T> where T: Codable { var curl: String? open var path: URLRequest open var queryParams: [String: String]? open var bodyParams: [String: Any]? open var method: HTTPMethod open var headers: [String: String] = [:] open var interceptors: [Interceptor] = [] open var logger: Loggable? var cancelled = false fileprivate var cancelToken: CancelationToken<T>? fileprivate var manager : Alamofire.SessionManager fileprivate let noNetWorkCodes = Set([ NSURLErrorCannotFindHost, NSURLErrorCannotConnectToHost, NSURLErrorNetworkConnectionLost, NSURLErrorDNSLookupFailed, NSURLErrorHTTPTooManyRedirects, NSURLErrorNotConnectedToInternet ]) public init(path: URL, method: HTTPMethod, queryParams: [String: String]?, bodyParams: [String: Any]?, headers: [String: String]?, interceptors: [Interceptor]?, cancelToken: CancelationToken<T>?) { self.path = try! URLRequest(url: path, method: method) self.queryParams = queryParams self.bodyParams = bodyParams self.method = method self.cancelToken = cancelToken if headers != nil { self.headers = headers! } let configuration = URLSessionConfiguration.default configuration.timeoutIntervalForRequest = 30 manager = Alamofire.SessionManager(configuration: configuration) if interceptors != nil {self.interceptors.append(contentsOf: interceptors!)} self.cancelToken?.api = self } func beforeRequest() { for interceptor in interceptors { interceptor.requestInterceptor(self) } if queryParams != nil { self.path = try! URLEncoding.queryString.encode(self.path, with: queryParams) } } open func processResponse<U>( _ onSuccess: @escaping (_ result: Response<T>?) -> Void, onError: @escaping (RestError?) -> Void, always: @escaping () -> Void) -> ((_ response: DataResponse<U>) -> Void) { return { (response: DataResponse<U>) -> Void in if self.cancelled { // Ignore the result if the request are canceled return } for interceptor in self.interceptors { interceptor.responseInterceptor(self, response: response) } switch response.result { case .success: if Utils.isSuccessfulRequest(response: response) { var instance: T? = nil // For empty results do { if let _ = response.result.value { if response.result.value is Data { if response.result.value is T { instance = response.result.value as? T } else { self.logger?.error("When downloading raw data, please provide T as Data") } } else { instance = try JSONDecoder().decode(T.self, from: response.data!) } } } catch { self.logger?.error(error.localizedDescription) self.logger?.error(error) } let responseBody = Response<T>(response.response?.statusCode, body: instance) onSuccess(responseBody) } else { let error = RestError(rawValue: response.response?.statusCode ?? RestErrorType.unknow.rawValue, rawIsHttpCode: true, rawResponse: response.result.value, rawResponseData: response.data) onError(error) } case .failure(let _error): let errorType = response.response?.statusCode ?? (self.noNetWorkCodes.contains(_error._code) ? RestErrorType.noNetwork.rawValue :RestErrorType.unknow.rawValue) let error = RestError(rawValue: _error._code == NSURLErrorTimedOut ? RestErrorType.noNetwork.rawValue : errorType, rawIsHttpCode: true, rawResponse: response.result.value, rawResponseData: response.data) onError(error) } always() } } open func upload(_ onProgress: @escaping (_ progress: Float) -> Void, onSuccess: @escaping (_ result: Response<T>?) -> Void, onError: @escaping (RestError?) -> Void, always: @escaping () -> Void) { assert(self.method == .post) assert((self.bodyParams?.count ?? 0) == 1) self.beforeRequest() Alamofire.upload(multipartFormData: { form in for (key,item) in self.bodyParams! { assert(item is UIImage || item is Data) if let _item = item as? UIImage { let data = _item.pngData()! form.append(data, withName: key, fileName: key, mimeType: "image/png") } else { let data = item as! Data form.append(data, withName: key, fileName: key, mimeType: "") } } }, usingThreshold: UInt64.init(), to: self.path.url!, method: .post, headers: self.headers, encodingCompletion: { result in switch (result) { case .success(let upload, _, _): upload.uploadProgress(closure: { progress in onProgress(Float(progress.fractionCompleted)) }) upload.responseJSON(completionHandler: self.processResponse(onSuccess, onError: onError, always: always)) case .failure(_): onError(RestError(rawValue: RestErrorType.formEncodeError.rawValue, rawIsHttpCode: false, rawResponse: nil, rawResponseData: nil)) always() } }) } open func download( _ onProgress: @escaping (_ progress: Float) -> Void, onSuccess: @escaping (_ result: Response<T>?) -> Void, onError: @escaping (RestError?) -> Void, always: @escaping () -> Void) { assert(self.method == .get) self.beforeRequest() let request = manager.request(path.url!, method: self.method, parameters: bodyParams, encoding: JSONEncoding.default, headers: headers) self.curl = request.debugDescription let callback: ((_ response: DataResponse<Data>) -> Void) = self.processResponse(onSuccess, onError: onError, always: always) request .responseData(completionHandler: callback) .downloadProgress(closure: {handler in onProgress(Float(handler.fractionCompleted)) }) cancelToken?.request = request } open func download( _ destination: FileManager.SearchPathDirectory, _ onProgress: @escaping (_ progress: Float) -> Void, onSuccess: @escaping (_ result: Response<Data>?) -> Void, onError: @escaping (RestError?) -> Void, always: @escaping () -> Void) { assert(self.method == .get) self.beforeRequest() let destination = DownloadRequest.suggestedDownloadDestination(for: destination) Alamofire.download( path.url!, method: self.method, parameters: self.bodyParams, encoding: JSONEncoding.default, headers: headers, to: destination) .responseData(completionHandler: {response in switch response.result { case .success(_): let responseBody = Response( response.response?.statusCode, body: response.result.value) onSuccess(responseBody) case .failure(_): onError(RestError(rawValue: RestErrorType.formEncodeError.rawValue, rawIsHttpCode: false, rawResponse: nil, rawResponseData: nil)) } always() }) .downloadProgress(closure: {handler in onProgress(Float(handler.fractionCompleted)) }) } open func execute( _ onSuccess: @escaping (Response<T>?) -> Void, onError: @escaping (RestError?) -> Void, always: @escaping () -> Void) { self.beforeRequest() let request = manager.request(path.url!, method: self.method, parameters: bodyParams, encoding: JSONEncoding.default, headers: headers) self.curl = request.debugDescription request.responseJSON(completionHandler: self.processResponse( onSuccess, onError: onError, always: always)) cancelToken?.request = request } }
mit
25474d6c1e4e9cd1c19e565fe9a1e964
39.065041
201
0.521713
5.6
false
false
false
false
EvsenevDev/SmartReceiptsiOS
SmartReceipts/Reports/PDF/TripReportHeader.swift
2
1853
// // TripReportHeader.swift // SmartReceipts // // Created by Bogdan Evsenev on 01/12/2017. // Copyright © 2017 Will Baumann. All rights reserved. // import Foundation fileprivate let HeaderRowsSpacing: CGFloat = 8 class TripReportHeader: UIView { @IBOutlet var tripNameLabel: UILabel! @IBOutlet weak var stackView: UIStackView! @IBOutlet var rowPrototype: UILabel! var yOffset: CGFloat = 0 override func awakeFromNib() { super.awakeFromNib() tripNameLabel.font = PDFFontStyle.title.font rowPrototype.removeFromSuperview() } func setTrip(name: String) { tripNameLabel.text = name adjustLabelHeightToFitAndPosition(label: tripNameLabel) } func appendRow(_ row: String, style: PDFFontStyle = .default) { let label = makeRowCopy() label.removeConstraints(label.constraints) label.numberOfLines = 0 label.font = style.font label.text = row adjustLabelHeightToFitAndPosition(label: label) stackView.addArrangedSubview(label) } private func adjustLabelHeightToFitAndPosition(label: UILabel) { let size = CGSize(width: frame.width, height: CGFloat.greatestFiniteMagnitude) let fitHeight = label.sizeThatFits(size).height yOffset += HeaderRowsSpacing var labelFrame = label.frame labelFrame.origin.y = yOffset labelFrame.size.height = fitHeight label.frame = labelFrame yOffset += fitHeight var myFrame = frame myFrame.size.height = yOffset frame = myFrame } private func makeRowCopy() -> UILabel { let data = NSKeyedArchiver.archivedData(withRootObject: rowPrototype) return NSKeyedUnarchiver.unarchiveObject(with: data) as! UILabel } }
agpl-3.0
a65f3c67bc188f63011ff62e5abf3506
28.396825
86
0.660367
4.848168
false
false
false
false
AssistoLab/FloatingLabel
FloatingLabel/src/fields/ListFloatingField.swift
2
3163
// // ListFloatingField.swift // FloatingLabel // // Created by Kevin Hirsch on 27/07/15. // Copyright (c) 2015 Kevin Hirsch. All rights reserved. // import UIKit import DropDown public class ListFloatingField: ActionFloatingField { //MARK: - Properties //MARK: UI public let dropDown = DropDown() //MARK: Content public var dataSource: [String] { get { return dropDown.dataSource } set { dropDown.dataSource = newValue } } /** The localization keys for the data source for the drop down. Changing this value automatically reloads the drop down. This has uses for setting accibility identifiers on the drop down cells (same ones as the localization keys). */ public var localizationKeysDataSource: [String] { get { return dropDown.localizationKeysDataSource } set { dropDown.localizationKeysDataSource = newValue } } public var selectedItem: String? public var selectedRow: Index? { get { return dropDown.indexForSelectedRow } set { if let newValue = newValue where newValue >= 0 && newValue < dataSource.count { dropDown.selectRowAtIndex(newValue) } else { dropDown.deselectRowAtIndexPath(newValue) } } } public override var isEditing: Bool { return editing } private var editing = false { didSet { updateUI(animated: true) } } public var willShowAction: Closure? { willSet { dropDown.willShowAction = newValue } } //MARK: - Init's convenience init() { self.init(frame: Frame.InitialFrame) } override init(frame: CGRect) { super.init(frame: frame) } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } } //MARK: - Initialization extension ListFloatingField { public override func setup() { super.setup() rightView = UIImageView(image: Icon.Arrow.image().template()) rightViewMode = .Always setNeedsUpdateConstraints() dropDown.anchorView = self dropDown.topOffset = CGPoint(x: Constraints.HorizontalPadding, y: -bounds.height) dropDown.selectionAction = { [unowned self] (index, item) in self.editing = false self.selectedItem = item self.selectedRow = index self.text = item self.valueChangedAction?(item) } dropDown.cancelAction = { [unowned self] in self.editing = false } action = { [unowned self] in self.editing = true self.dropDown.show() } } } //MARK: - Initialization extension ListFloatingField { public override func layoutSublayersOfLayer(layer: CALayer) { super.layoutSublayersOfLayer(layer) let separatorLineMinY = separatorLine.superview!.convertRect(separatorLine.frame, toView: dropDown.anchorView?.plainView).minY - 1 dropDown.bottomOffset = CGPoint(x: Constraints.HorizontalPadding, y: separatorLineMinY) dropDown.width = separatorLine.bounds.width } override public func updateUI(animated animated: Bool) { super.updateUI(animated: animated) if isFloatingLabelDisplayed { dropDown.topOffset.y = -bounds.height } else { let floatingLabelMinY = floatingLabel.superview!.convertRect(floatingLabel.frame, toView: dropDown.anchorView?.plainView).minY dropDown.topOffset.y = -bounds.height + floatingLabelMinY } } }
mit
49066003441dceb38770367b2087414b
21.274648
132
0.726525
3.74763
false
false
false
false
robertofrontado/RxSocialConnect-iOS
Sources/Core/Internal/Persistence/TokenCache.swift
1
1190
// // TokenCache.swift // RxSocialConnect // // Created by Roberto Frontado on 5/23/16. // Copyright © 2016 Roberto Frontado. All rights reserved. // import RxSwift import OAuthSwift class TokenCache { fileprivate let disk: Disk fileprivate var memory: [String: AnyObject] static let INSTANCE = TokenCache() fileprivate init() { disk = Disk() memory = [String: AnyObject]() } func save<T: OAuthSwiftCredential>(_ key: String, data: T) { memory.updateValue(Observable.just(data), forKey: key) disk.save(key, data: data) } func get<T: OAuthSwiftCredential>(_ keyToken: String, classToken: T.Type) -> Observable<T>? { var token = memory[keyToken] if token == nil { token = disk.get(keyToken, classToken: classToken) if let token = token { memory.updateValue(token, forKey: keyToken) } } return token as? Observable<T> } func evict(_ key: String) { memory.removeValue(forKey: key) disk.evict(key) } func evictAll() { memory.removeAll() disk.evictAll() } }
apache-2.0
0bc078704b0696dfe744a7d888857b6e
23.265306
97
0.583684
4.142857
false
false
false
false
TeamYYZ/DineApp
Dine/SignUpViewController.swift
1
1081
// // BaseSignUpViewController.swift // Dine // // Created by YiHuang on 3/19/16. // Copyright © 2016 YYZ. All rights reserved. // import UIKit class SignUpViewController: UIViewController { let gradientLayer = CAGradientLayer() static var emailaddr: String? static var password: String? static var firstname: String? static var lastname: String? override func viewDidLoad() { super.viewDidLoad() gradientLayer.frame = self.view.bounds gradientLayer.zPosition = -1 let color1 = ColorTheme.sharedInstance.loginGradientFisrtColor.CGColor as CGColorRef let color2 = ColorTheme.sharedInstance.loginGradientSecondColor.CGColor as CGColorRef gradientLayer.colors = [color1, color2] gradientLayer.locations = [0.0, 1.0] self.view.layer.addSublayer(gradientLayer) // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
gpl-3.0
2c34af55353d53125d9790eb976e4ba4
29
93
0.690741
4.635193
false
false
false
false
accepton/accepton-apple
Example/Tests/AcceptOnPaymentProcessorSpec.swift
1
6546
// https://github.com/Quick/Quick import Quick import Nimble import accepton //Relating to the information returned by the API for certain payment processors that //should be enabled class AcceptOnPaymentProcessorSpec: QuickSpec { override func spec() { describe("paypal") { AcceptOnAPIFactory.query.withAtleast(.PaypalRest, .Sandbox).each { apiInfo, desc in context(desc) { it("Can retrieve the paypal rest client secret") { var _paymentMethods: AcceptOnAPIPaymentMethodsInfo? apiInfo.api.createTransactionTokenWithDescription("Foo", forAmountInCents: 100, completion: { (token, error) -> () in if error != nil { NSException(name: "createTransactionTokenWithDescription", reason: error!.description, userInfo: nil).raise() return } apiInfo.api.getAvailablePaymentMethodsForTransactionWithId(token!.id, completion: { (paymentMethods, error) -> () in if error != nil { NSException(name: "getAvailablePaymentMethodsForTransactionWithId", reason: error!.description, userInfo: nil).raise() return } _paymentMethods = paymentMethods! }) }) expect(_paymentMethods?.supportsPaypal).toEventually(equal(true)) } } } } describe("apple_pay") { AcceptOnAPIFactory.query.withAtleast(.Sandbox).without(.ApplePayStripe).each { apiInfo, desc in context(desc) { it("Does get supportsApplePay == false for a non apple-pay enabled account") { var _paymentMethods: AcceptOnAPIPaymentMethodsInfo? apiInfo.api.createTransactionTokenWithDescription("Foo", forAmountInCents: 100, completion: { (token, error) -> () in if error != nil { NSException(name: "createTransactionTokenWithDescription", reason: error!.description, userInfo: nil).raise() return } apiInfo.api.getAvailablePaymentMethodsForTransactionWithId(token!.id, completion: { (paymentMethods, error) -> () in if error != nil { NSException(name: "getAvailablePaymentMethodsForTransactionWithId", reason: error!.description, userInfo: nil).raise() return } _paymentMethods = paymentMethods! }) }) expect(_paymentMethods?.supportsApplePay).toEventually(equal(false)) } } } } describe("braintree") { AcceptOnAPIFactory.query.withAtleast(.Sandbox).withAtleast(.Braintree).each { apiInfo, desc in context(desc) { it("Does get supportsBrainTree == true for a brain-tree enabled account and a nonce") { var _paymentMethods: AcceptOnAPIPaymentMethodsInfo? apiInfo.api.createTransactionTokenWithDescription("Foo", forAmountInCents: 100, completion: { (token, error) -> () in if error != nil { NSException(name: "createTransactionTokenWithDescription", reason: error!.description, userInfo: nil).raise() return } apiInfo.api.getAvailablePaymentMethodsForTransactionWithId(token!.id, completion: { (paymentMethods, error) -> () in if error != nil { NSException(name: "getAvailablePaymentMethodsForTransactionWithId", reason: error!.description, userInfo: nil).raise() return } _paymentMethods = paymentMethods! }) }) expect(_paymentMethods?.supportsBraintree).toEventually(equal(true)) expect(_paymentMethods?.braintreeMerchantId).toEventuallyNot(equal(nil)) expect(_paymentMethods?.braintreeClientAuthorizationFingerprint).toEventuallyNot(equal(nil)) expect(_paymentMethods?.braintreeRawEncodedClientToken).toEventuallyNot(equal(nil)) } } } } it("Does get stripeApplePayMerchantIdentifier for an account that has stripe & apple-pay integration enabled") { let apiKey = apiKeyWithProperties([.ApplePay], withoutProperties: []) let api = AcceptOnAPI(publicKey: apiKey.key, isProduction: false) var _paymentMethods: AcceptOnAPIPaymentMethodsInfo? api.createTransactionTokenWithDescription("Foo", forAmountInCents: 100, completion: { (token, error) -> () in if error != nil { NSException(name: "createTransactionTokenWithDescription", reason: error!.description, userInfo: nil).raise() return } api.getAvailablePaymentMethodsForTransactionWithId(token!.id, completion: { (paymentMethods, error) -> () in if error != nil { NSException(name: "getAvailablePaymentMethodsForTransactionWithId", reason: error!.description, userInfo: nil).raise() return } _paymentMethods = paymentMethods! }) }) expect(_paymentMethods?.stripeApplePayMerchantIdentifier).toEventually(equal(apiKey.metadata["stripe_merchant_identifier"] as? String)) } } }
mit
395285605d7f3058c57ff7df2e3fd6eb
54.016807
154
0.501069
6.659207
false
false
false
false
iHunterX/SocketIODemo
DemoSocketIO/Utils/Validator/Rules/ValidationRulePaymentCard.swift
1
4626
/* ValidationRulePaymentCard.swift Validator Created by @adamwaite. Copyright (c) 2015 Adam Waite. All rights reserved. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ // Thanks to these guys for a lot of this code: // github.com/vitkuzmenko/CreditCardValidator/blob/master/CreditCardValidator/CreditCardValidator.swift // gist.github.com/cwagdev/635ce973e8e86da0403a import Foundation public enum PaymentCardType: Int { case Amex, Mastercard, Visa, Maestro, DinersClub, JCB, Discover, UnionPay public static var all: [PaymentCardType] = [.Amex, .Mastercard, .Visa, .Maestro, .DinersClub, .JCB, .Discover, .UnionPay] public var name: String { switch self { case .Amex: return "American Express" case .Mastercard: return "Mastercard" case .Visa: return "Visa" case .Maestro: return "Maestro" case .DinersClub: return "Diners Club" case .JCB: return "JCB" case .Discover: return "Discover" case .UnionPay: return "Union Pay" } } private var identifyingExpression: String { switch self { case .Amex: return "^3[47][0-9]{5,}$" case .Mastercard: return "^(5[1-5]|2[2-7])[0-9]{5,}$" case .Visa: return "^4[0-9]{6,}$" case .Maestro: return "^(?:5[0678]\\d\\d|6304|6390|67\\d\\d)\\d{8,15}$" case .DinersClub: return "^3(?:0[0-5]|[68][0-9])[0-9]{4,}$" case .JCB: return "^(?:2131|1800|35[0-9]{3})[0-9]{3,}$" case .Discover: return "^6(?:011|5[0-9]{2})[0-9]{3,}$" case .UnionPay: return "^62[0-5]\\d{13,16}$" } } private static func typeForCardNumber(string: String?) -> PaymentCardType? { guard let string = string else { return nil } for type in PaymentCardType.all { let predicate = NSPredicate(format: "SELF MATCHES %@", type.identifyingExpression) if predicate.evaluate(with: string) { return type } } return nil } public init?(cardNumber: String) { guard let type = PaymentCardType.typeForCardNumber(string: cardNumber) else { return nil } self.init(rawValue: type.rawValue) } } public struct ValidationRulePaymentCard: ValidationRule { public typealias InputType = String public let acceptedTypes: [PaymentCardType] public let failureError: ValidationErrorType public init(acceptedTypes: [PaymentCardType], failureError: ValidationErrorType) { self.acceptedTypes = acceptedTypes self.failureError = failureError } public init(failureError: ValidationErrorType) { self.init(acceptedTypes: PaymentCardType.all, failureError: failureError) } public func validateInput(input: String?) -> Bool { guard let cardNum = input else { return false } guard ValidationRulePaymentCard.luhnCheck(cardNumber: cardNum) else { return false } guard let cardType = PaymentCardType(cardNumber: cardNum) else { return false } return acceptedTypes.contains(cardType) } private static func luhnCheck(cardNumber: String) -> Bool { var sum = 0 let reversedCharacters = cardNumber.characters.reversed().map { String($0) } for (idx, element) in reversedCharacters.enumerated() { guard let digit = Int(element) else { return false } switch ((idx % 2 == 1), digit) { case (true, 9): sum += 9 case (true, 0...8): sum += (digit * 2) % 9 default: sum += digit } } return sum % 10 == 0 } }
gpl-3.0
6c362daa0eb78698ec6a5e01247c47ea
36.306452
125
0.656507
4.090186
false
false
false
false
acsalu/Keymochi
Keyboard/ForwardingView.swift
2
8156
// // ForwardingView.swift // TransliteratingKeyboard // // Created by Alexei Baboulevitch on 7/19/14. // Copyright (c) 2014 Alexei Baboulevitch ("Archagon"). All rights reserved. // import UIKit typealias TouchTimestamp = (down: TimeInterval, up: TimeInterval) protocol FowardingViewDelegate { func fowardingView(_:ForwardingView, didOutputTouchTimestamp touchTimestamp: TouchTimestamp, onView view: UIView) } class ForwardingView: UIView { var touchToView: [UITouch:UIView] var touchBeganTimeTable = [UITouch:Double]() var delegate: FowardingViewDelegate? override init(frame: CGRect) { self.touchToView = [:] super.init(frame: frame) self.contentMode = UIViewContentMode.redraw self.isMultipleTouchEnabled = true self.isUserInteractionEnabled = true self.isOpaque = false } required init?(coder: NSCoder) { fatalError("NSCoding not supported") } // Why have this useless drawRect? Well, if we just set the backgroundColor to clearColor, // then some weird optimization happens on UIKit's side where tapping down on a transparent pixel will // not actually recognize the touch. Having a manual drawRect fixes this behavior, even though it doesn't // actually do anything. override func draw(_ rect: CGRect) {} override func hitTest(_ point: CGPoint, with event: UIEvent!) -> UIView? { if self.isHidden || self.alpha == 0 || !self.isUserInteractionEnabled { return nil } else { return (self.bounds.contains(point) ? self : nil) } } func handleControl(_ view: UIView?, controlEvent: UIControlEvents) { if let control = view as? UIControl { let targets = control.allTargets for target in targets { if let actions = control.actions(forTarget: target, forControlEvent: controlEvent) { for action in actions { let selectorString = action let selector = Selector(selectorString) control.sendAction(selector, to: target, for: nil) } } } } } // TODO: there's a bit of "stickiness" to Apple's implementation func findNearestView(_ position: CGPoint) -> UIView? { if !self.bounds.contains(position) { return nil } var closest: (UIView, CGFloat)? = nil for anyView in self.subviews { let view = anyView if view.isHidden { continue } view.alpha = 1 let distance = distanceBetween(view.frame, point: position) if closest != nil { if distance < closest!.1 { closest = (view, distance) } } else { closest = (view, distance) } } if closest != nil { return closest!.0 } else { return nil } } // http://stackoverflow.com/questions/3552108/finding-closest-object-to-cgpoint b/c I'm lazy func distanceBetween(_ rect: CGRect, point: CGPoint) -> CGFloat { if rect.contains(point) { return 0 } var closest = rect.origin if (rect.origin.x + rect.size.width < point.x) { closest.x += rect.size.width } else if (point.x > rect.origin.x) { closest.x = point.x } if (rect.origin.y + rect.size.height < point.y) { closest.y += rect.size.height } else if (point.y > rect.origin.y) { closest.y = point.y } let a = pow(Double(closest.y - point.y), 2) let b = pow(Double(closest.x - point.x), 2) return CGFloat(sqrt(a + b)); } // reset tracked views without cancelling current touch func resetTrackedViews() { for view in self.touchToView.values { self.handleControl(view, controlEvent: .touchCancel) } self.touchToView.removeAll(keepingCapacity: true) } func ownView(_ newTouch: UITouch, viewToOwn: UIView?) -> Bool { var foundView = false if viewToOwn != nil { for (touch, view) in self.touchToView { if viewToOwn == view { if touch == newTouch { break } else { self.touchToView[touch] = nil foundView = true } break } } } self.touchToView[newTouch] = viewToOwn return foundView } override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { for touch in touches { touchBeganTimeTable[touch] = CACurrentMediaTime() let position = touch.location(in: self) let view = findNearestView(position) let viewChangedOwnership = self.ownView(touch, viewToOwn: view) if !viewChangedOwnership { self.handleControl(view, controlEvent: .touchDown) if touch.tapCount > 1 { // two events, I think this is the correct behavior but I have not tested with an actual UIControl self.handleControl(view, controlEvent: .touchDownRepeat) } } } } override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) { for touch in touches { let position = touch.location(in: self) let oldView = self.touchToView[touch] let newView = findNearestView(position) if oldView != newView { self.handleControl(oldView, controlEvent: .touchDragExit) let viewChangedOwnership = self.ownView(touch, viewToOwn: newView) if !viewChangedOwnership { self.handleControl(oldView, controlEvent: .touchDragOutside) self.handleControl(newView, controlEvent: .touchDragEnter) } else { self.handleControl(newView, controlEvent: .touchDragInside) } } else { self.handleControl(oldView, controlEvent: .touchDragInside) } } } override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) { for touch in touches { let view = self.touchToView[touch] let downTime = touchBeganTimeTable[touch]! let upTime = CACurrentMediaTime() touchBeganTimeTable.removeValue(forKey: touch) if let delegate = self.delegate { let touchTimestamp = TouchTimestamp(downTime, upTime) if let view = view { delegate.fowardingView(self, didOutputTouchTimestamp: touchTimestamp, onView: view) } } let touchPosition = touch.location(in: self) if self.bounds.contains(touchPosition) { self.handleControl(view, controlEvent: .touchUpInside) } else { self.handleControl(view, controlEvent: .touchCancel) } self.touchToView[touch] = nil } } override func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent?) { for touch in touches { let view = self.touchToView[touch] self.handleControl(view, controlEvent: .touchCancel) self.touchToView[touch] = nil } } }
bsd-3-clause
e34f8affff53fe374232c98acf5fc03d
32.154472
118
0.52771
5.27555
false
false
false
false
dogo/AKSideMenu
AKSideMenuExamples/Simple/AKSideMenuSimple/LeftMenuViewController/LeftMenuView.swift
1
2842
// // LeftMenuView.swift // AKSideMenuSimple // // Created by Diogo Autilio on 30/10/20. // Copyright © 2020 AnyKey Entertainment. All rights reserved. // import Foundation import UIKit final class LeftMenuView: UITableView { // MARK: - Properties var didTouchIndex: ((_ index: Int) -> Void)? // MARK: - Life Cycle override init(frame: CGRect, style: UITableView.Style) { super.init(frame: frame, style: style) self.delegate = self self.dataSource = self self.isOpaque = false self.backgroundColor = .clear self.backgroundView = nil self.separatorStyle = .none self.bounces = false } @available(*, unavailable) required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func layoutSubviews() { super.layoutSubviews() updateContentInset() } // MARK: - Private Methods private func updateContentInset() { let tableViewHeight = self.bounds.height let contentHeight = self.contentSize.height let centeringInset = (tableViewHeight - contentHeight) / 2.0 let topInset = max(centeringInset, 0.0) self.contentInset = UIEdgeInsets(top: topInset, left: 0.0, bottom: 0.0, right: 0.0) } } extension LeftMenuView: UITableViewDelegate { func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) didTouchIndex?(indexPath.row) } } extension LeftMenuView: UITableViewDataSource { func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 54 } func tableView(_ tableView: UITableView, numberOfRowsInSection sectionIndex: Int) -> Int { return 5 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cellIdentifier: String = "Cell" var cell: UITableViewCell? = tableView.dequeueReusableCell(withIdentifier: cellIdentifier) if cell == nil { cell = UITableViewCell(style: .default, reuseIdentifier: cellIdentifier) cell?.backgroundColor = .clear cell?.textLabel?.font = UIFont(name: "HelveticaNeue", size: 21) cell?.textLabel?.textColor = .white cell?.textLabel?.highlightedTextColor = .lightGray cell?.selectedBackgroundView = UIView() } let titles = ["Home", "Calendar", "Profile", "Settings", "Log Out"] let images = ["IconHome", "IconCalendar", "IconProfile", "IconSettings", "IconEmpty"] cell?.textLabel?.text = titles[indexPath.row] cell?.imageView?.image = UIImage(named: images[indexPath.row]) return cell ?? UITableViewCell() } }
mit
eab53d74f8871c9d16ff69f0a7c209eb
29.548387
100
0.651531
4.766779
false
false
false
false
eTilbudsavis/native-ios-eta-sdk
Sources/EventsTracker/EventsCache.swift
1
4649
// // ┌────┬─┐ ┌─────┐ // │ ──┤ └─┬───┬───┤ ┌──┼─┬─┬───┐ // ├── │ ╷ │ · │ · │ ╵ │ ╵ │ ╷ │ // └────┴─┴─┴───┤ ┌─┴─────┴───┴─┴─┘ // └─┘ // // Copyright (c) 2018 ShopGun. All rights reserved. import Foundation /// The only thing a cached object _NEEDS_ is to be codable, and have a cacheId protocol CacheableEvent: Codable { var cacheId: String { get } } /// A class that handles the Caching of the events to disk class EventsCache<T: CacheableEvent> { let diskCachePath: URL? let maxCount: Int // If directory is nil, it will never cache to disk, only to memory. init(fileName: String, directory: URL? = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first, maxCount: Int = 1000) { self.diskCachePath = directory?.appendingPathComponent(fileName) self.maxCount = maxCount } /// Note - this property is syncronized with memory writes, so may not be instantaneous var objectCount: Int { return self.cacheInMemoryQueue.sync { self.allObjects.count } } /// Lazily initialize from the disk. this may take a while, so the beware the first call to allObjects lazy fileprivate var allObjects: [T] = { return self.cacheOnDiskQueue.sync { let objs = self.retreiveFromDisk() ?? [] if objs.count > self.maxCount { return Array(objs.suffix(self.maxCount)) } return objs } }() func write(toTail objects: [T]) { guard objects.count > 0 else { return } cacheInMemoryQueue.async { self.allObjects = Array((self.allObjects + objects).suffix(self.maxCount)) self.requestWriteToDisk() } } func read(fromHead count: Int) -> [T] { return self.cacheInMemoryQueue.sync { Array(self.allObjects.prefix(count)) } } func remove(ids: [String]) { guard ids.count > 0 else { return } cacheInMemoryQueue.async { self.allObjects = self.allObjects.filter { ids.contains($0.cacheId) == false } self.requestWriteToDisk() } } fileprivate var writeToDiskTimer: Timer? fileprivate var writeRequestCount: Int = 0 fileprivate let cacheInMemoryQueue: DispatchQueue = DispatchQueue(label: "com.shopgun.ios.sdk.events_cache.memory_queue", attributes: []) fileprivate let cacheOnDiskQueue: DispatchQueue = DispatchQueue(label: "com.shopgun.ios.sdk.events_cache.disk_queue", attributes: []) fileprivate func requestWriteToDisk() { writeRequestCount += 1 if writeToDiskTimer == nil { writeToDiskTimer = Timer(timeInterval: 0.2, target: self, selector: #selector(writeToDiskTimerTick(_:)), userInfo: nil, repeats: false) RunLoop.main.add(writeToDiskTimer!, forMode: RunLoop.Mode.common) } } @objc fileprivate func writeToDiskTimerTick(_ timer: Timer) { writeCurrentStateToDisk() } fileprivate func writeCurrentStateToDisk() { cacheInMemoryQueue.async { let objsToSave = self.allObjects let currentWriteRequestCount = self.writeRequestCount self.cacheOnDiskQueue.async { self.saveToDisk(objects: objsToSave) // something has changed while we were writing to disk - write again! if currentWriteRequestCount != self.writeRequestCount { self.writeCurrentStateToDisk() } else { // reset timer so that another request can be made self.writeToDiskTimer = nil } } } } fileprivate func retreiveFromDisk() -> [T]? { guard let fileURL = diskCachePath else { return nil } guard let data = try? Data(contentsOf: fileURL) else { return nil } return try? PropertyListDecoder().decode([T].self, from: data) } fileprivate func saveToDisk(objects: [T]) { guard let fileURL = diskCachePath else { return } guard let encodedData: Data = try? PropertyListEncoder().encode(objects) else { return } try? encodedData.write(to: fileURL) } }
mit
11545272b90a716ecae97bea0be5b006
33.361538
147
0.574659
4.677487
false
false
false
false
Khala-wan/Slarder
Slarder/Slarder.swift
1
5268
// // Slarder.swift // PodMan // // Created by 万圣 on 2017/6/19. // Copyright © 2017年 万圣. All rights reserved. // import Cocoa extension Slarder where Base:Process { /// Process 执行普通脚本(无异步任务的,无输入)并获得 标准输出、错误输出、执行完成等回调处理能力。 /// /// - Parameters: /// - sudo: 是否需要root权限 默认不需要 /// - outputHandler: 标准输出回调 /// - outputString: 输出信息 /// - input:输入流Pipe /// - errorputHandler: 错误输出回调 如果该参数为nil,则错误信息当做标准输出信息输出。 /// - errorMessage:错误信息 /// - terminateHandler: /// - status:完成结果的Code func launchWith(sudo:Bool = false,outputHandler:((_ outputMessage:String,_ input:Pipe?)->())?,errorputHandler:((_ errorMessage:String)->())?,terminateHandler:((_ status:Int32)->())?){ let outputPipe = outputHandler == nil ? nil : Pipe() let errorputPipe = errorputHandler == nil ? nil : Pipe() var readHandlers:(FileHandle?,FileHandle?) = self.setInOutputAndErrorOutput(input: nil, output: outputPipe, errorOutput: errorputPipe) var pid:pid_t? if sudo { do{ let result = try self.base.authorLanuch() readHandlers.0 = result.0 pid = result.1 }catch{ print(error.localizedDescription) return } }else{ base.launch() } /// 标准输出 let outResult = handleOutPutString(readHandler: readHandlers.0) if outResult.0 { outputHandler!(outResult.1, nil) } /// 标准错误输出 let errorResult = handleOutPutString(readHandler: readHandlers.1) if errorResult.0 { errorputHandler!(errorResult.1) } /// 执行结束回调 if let handler = terminateHandler{ self.handleTermination(sudo: sudo,async: true,pid: pid, terminateHandler: handler) } } /// Process 执行异步脚本(有异步任务的,有输入)并获得 标准输出、错误输出、执行完成等回调处理能力。 /// /// - Parameters: /// - sudo: 是否需要root权限 默认不需要 /// - outputHandler: 标准输出回调 /// - outputString: 输出信息 /// - input:输入流Pipe /// - errorputHandler: 错误输出回调 如果该参数为nil,则错误信息当做标准输出信息输出。 /// - errorMessage:错误信息 /// - terminateHandler: /// - status:完成结果的Code func launchAsyncWith(sudo:Bool = false,outputHandler:((_ outputMessage:String,_ input:Pipe?)->())?,errorputHandler:((_ errorMessage:String)->())?,terminateHandler:((_ status:Int32)->())?){ let outputPipe = outputHandler == nil ? nil : Pipe() let errorputPipe = errorputHandler == nil ? nil : Pipe() let inputPipe = Pipe() var readHandlers:(FileHandle?,FileHandle?) = self.setInOutputAndErrorOutput(input: inputPipe, output: outputPipe, errorOutput: errorputPipe) var pid:pid_t? if sudo { do{ let result = try self.base.authorLanuch() readHandlers.0 = result.0 pid = result.1 }catch{ print(error.localizedDescription) return } }else{ base.launch() } /// 标准输出 if let outHandler:FileHandle = readHandlers.0{ outHandler.waitForDataInBackgroundAndNotify() NotificationCenter.default.addObserver(forName: NSNotification.Name.NSFileHandleDataAvailable, object: outHandler , queue: nil, using: { (noti) in let result = self.handleOutPutString(readHandler: readHandlers.0) if result.0 { outputHandler!(result.1,inputPipe) } outHandler.waitForDataInBackgroundAndNotify() }) } /// 标准错误输出 if let outHandler:FileHandle = readHandlers.1{ outHandler.waitForDataInBackgroundAndNotify() NotificationCenter.default.addObserver(forName: NSNotification.Name.NSFileHandleDataAvailable, object: outHandler , queue: nil, using: { (noti) in let result = self.handleOutPutString(readHandler: readHandlers.0) if result.0 { errorputHandler!(result.1) } outHandler.waitForDataInBackgroundAndNotify() }) } /// 执行结束回调 if let handler = terminateHandler{ self.handleTermination(sudo: sudo, async: true, pid: pid, terminateHandler: handler) } } } public struct Slarder<Base> { public let base: Base public init(_ base: Base) { self.base = base } var isRootRunning:Bool = false } public extension Process { public var sd: Slarder<Process> { return Slarder(self) } }
bsd-2-clause
3fec143e1849478bb04d66b05f90d98e
33.121429
192
0.565208
4.164778
false
false
false
false
VictorNouvellet/Player
Player/Player/Class/SongDetailViewController.swift
1
2199
// // SongDetailViewController.swift // Player // // Created by Victor Nouvellet on 10/15/17. // Copyright © 2017 Victor Nouvellet. All rights reserved. // import UIKit class SongDetailViewController: UIViewController { var song: SongModel? = nil { didSet { guard let song = song else { return } fillView(song: song) } } override func viewDidLoad() { super.viewDidLoad() } func fillView(song: SongModel) { let artworkImageView = UIImageView(frame: self.view.frame) artworkImageView.contentMode = .scaleAspectFit self.view.addSubview(artworkImageView) artworkImageView.bounds.origin = self.view.bounds.origin artworkImageView.setImageFromURL(url: song.artworkUrl) } override var previewActionItems: [UIPreviewActionItem] { let playing: Bool = (PlayerManager.shared.song == self.song && PlayerManager.shared.player?.isPlaying ?? false) let playAction = UIPreviewAction(title: (playing ? "Pause" : "Play"), style: .default) { (action, viewController) in if playing { PlayerManager.shared.pause() } else { if PlayerManager.shared.song != self.song { PlayerManager.shared.song = self.song } PlayerManager.shared.play() } } let shareAction = UIPreviewAction(title: "Share", style: .default) { (action, viewController) in guard let iTunesUrlString = self.song?.iTunesUrl, let iTunesUrl = URL(string: iTunesUrlString) else { log.error("Error when sharing song : iTunes URL is wrong") return } log.debug("Action: \(action), viewcontroller: \(viewController)") let activityController = UIActivityViewController(activityItems: [iTunesUrl], applicationActivities: nil) UIApplication.shared.keyWindow!.rootViewController!.childViewControllers.last!.present(activityController, animated: true, completion: { // Do something when shared }) } return [playAction, shareAction] } }
bsd-3-clause
3a1a6f9e8ab72bf8246f0289fa824180
37.561404
148
0.620564
5.018265
false
false
false
false
StretchSense/iOS-Library
Examples/DemoMultipleChannel/DemoMultipleChannel/ViewController.swift
1
8444
// // ViewController.swift // DemoMultipleChannel // // Created by Jeremy Labrado on 26/05/16. // Copyright © 2016 StretchSense. All rights reserved. // import UIKit import CoreBluetooth class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate { @IBOutlet weak var myTableViewAvailable: UITableView! @IBOutlet weak var myTableViewConnected: UITableView! var stretchsenseObject = StretchSenseAPI() //////// override func viewDidLoad() { print("viewDidLoad()") /* This function is called as the initialiser of the view controller */ super.viewDidLoad() // Start scanning for new peripheral stretchsenseObject.startBluetooth() // initialazing the table view self.myTableViewAvailable.delegate = self self.myTableViewAvailable.dataSource = self // initialazing the table view self.myTableViewConnected.delegate = self self.myTableViewConnected.dataSource = self // Load data myTableViewAvailable.reloadData() myTableViewConnected.reloadData() // setting the observer waiting for notification let defaultCenter = NotificationCenter.default // when a notification "UpdateInfo" is detected, go to the function newInfoDetected() defaultCenter.addObserver(self, selector: #selector(newInfoDetected), name: NSNotification.Name(rawValue: "UpdateInfo"),object: nil) defaultCenter.addObserver(self, selector: #selector(newValueDetected0), name: NSNotification.Name(rawValue: "UpdateValueNotification"),object: nil) //NSTimer.scheduledTimerWithTimeInterval(0.1, target: self, selector: #selector(update), userInfo: nil, repeats: false) stretchsenseObject.startScanning() } // MARK: New Info Functions func newInfoDetected() { print("newInfoDetected()") // if a notification is received, reload the tables myTableViewAvailable.reloadData() myTableViewConnected.reloadData() stretchsenseObject.startScanning() } func newValueDetected0() { myTableViewConnected.reloadData() } func newValueDetected1() { myTableViewConnected.reloadData() } func newValueDetected2() { myTableViewConnected.reloadData() } func newValueDetected3() { myTableViewConnected.reloadData() } func newValueDetected4() { myTableViewConnected.reloadData() } func newValueDetected5() { myTableViewConnected.reloadData() } func newValueDetected6() { myTableViewConnected.reloadData() } func newValueDetected7() { myTableViewConnected.reloadData() } func newValueDetected8() { myTableViewConnected.reloadData() } func newValueDetected9() { myTableViewConnected.reloadData() } /*func update() { print("update()") myTableViewAvailable.reloadData() myTableViewConnected.reloadData() }*/ // MARK: TableView Functions func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { //print("numberOfRowInSection()") if tableView == self.myTableViewAvailable { print("numberOfRowInSection() Available") // Set the number of Rows in the Table return stretchsenseObject.getNumberOfPeripheralAvailable() } else { print("numberOfRowInSection() Connected") return stretchsenseObject.getNumberOfPeripheralConnected() } } func numberOfSections(in tableView: UITableView) -> Int { print("numberOfSectionsInTableView()") // Set the number of Section in the table return 1 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { //print("cellForRowAtIndexPath()") // This function filled each cell with the UUID and set the background color depending on the sensors's state var listPeripheralsAvailable = stretchsenseObject.getListPeripheralsAvailable() let listperipheralsConnected = stretchsenseObject.getListPeripheralsConnected() if tableView == self.myTableViewAvailable { print("cellForRowAtIndexPath() Available") let cellAvailable = tableView.dequeueReusableCell(withIdentifier: "CellAvailable", for: indexPath) as UITableViewCell if listPeripheralsAvailable.count != 0 { // If the sensor is connected, the background is green and we display his color in the subtitle if listPeripheralsAvailable[indexPath.row]?.state == CBPeripheralState.connected{ cellAvailable.backgroundColor = UIColor.green for myPeripheralConnected in listperipheralsConnected{ if myPeripheralConnected.uuid == (cellAvailable.textLabel?.text)!{ //cell.detailTextLabel?.text = myPeripheralConnected.colorName[myPeripheralConnected.uniqueNumber] cellAvailable.detailTextLabel?.text = myPeripheralConnected.colors[myPeripheralConnected.uniqueNumber].colorName } else{ } } } // If the sensor is disconnected, the background is grey else if listPeripheralsAvailable[indexPath.row]?.state == CBPeripheralState.disconnected{ cellAvailable.backgroundColor = UIColor.lightGray } } // For each row, we complete it with the UUID of the sensor cellAvailable.textLabel?.text = "\(listPeripheralsAvailable[indexPath.row]!.identifier.uuidString)" return cellAvailable } else { print("cellForRowAtIndexPath() Connected") let cellConnected = tableView.dequeueReusableCell(withIdentifier: "CellConnected", for: indexPath) as UITableViewCell for myPeripheralConnected in listperipheralsConnected{ print(myPeripheralConnected.value) cellConnected.textLabel?.text = "\((listperipheralsConnected[(indexPath as NSIndexPath).row].value * 0.1))" + " pF" cellConnected.backgroundColor = myPeripheralConnected.colors[indexPath.row].colorValueRGB cellConnected.detailTextLabel?.text = myPeripheralConnected.uuid } return cellConnected } } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { print("didSelectRowAtIndexPath()") // This function is called when we click on one cell // We want to connect or disconnect the sensor clicked let cell = tableView.cellForRow(at: indexPath) var listPeripheralsAvailable = stretchsenseObject.getListPeripheralsAvailable() // If the sensor is connected we want to disconnect it by asking the confirmation if listPeripheralsAvailable[indexPath.row]?.state == CBPeripheralState.connected{ let refreshAlert = UIAlertController(title: "Delete", message: "Are you sure you want to disconnect the peripheral? ", preferredStyle: UIAlertControllerStyle.alert) refreshAlert.addAction(UIAlertAction(title: "Confirm", style: .default, handler: { (action: UIAlertAction!) in // If we confirm, we disconnect this sensor self.stretchsenseObject.disconnectOnePeripheralWithUUID(cell!.textLabel!.text!) })) refreshAlert.addAction(UIAlertAction(title: "Cancel", style: .default, handler: { (action: UIAlertAction!) in // Else we let the sensor connected })) present(refreshAlert, animated: true, completion: nil) } // If the sensor is disconnected, we connect it else if listPeripheralsAvailable[indexPath.row]?.state == CBPeripheralState.disconnected{ if indexPath.row <= listPeripheralsAvailable.count{ //print("Go to connect Function") stretchsenseObject.connectToPeripheralWithUUID(cell!.textLabel!.text!) } } } ///////// }
mit
99467195f731679a32af5d2309dff004
38.453271
176
0.646453
5.743537
false
false
false
false
hfutrell/BezierKit
BezierKit/BezierKitTests/ReversibleTests.swift
1
2896
// // ReversibleTests.swift // BezierKit // // Created by Holmes Futrell on 11/24/19. // Copyright © 2019 Holmes Futrell. All rights reserved. // import XCTest import BezierKit class ReversibleTests: XCTestCase { let lineSegment = LineSegment(p0: CGPoint(x: 3, y: 5), p1: CGPoint(x: 6, y: 7)) let quadraticCurve = QuadraticCurve(p0: CGPoint(x: 6, y: 7), p1: CGPoint(x: 7, y: 5), p2: CGPoint(x: 6, y: 3)) let cubicCurve = CubicCurve(p0: CGPoint(x: 6, y: 3), p1: CGPoint(x: 5, y: 2), p2: CGPoint(x: 4, y: 3), p3: CGPoint(x: 3, y: 5)) let expectedReversedLineSegment = LineSegment(p0: CGPoint(x: 6, y: 7), p1: CGPoint(x: 3, y: 5)) let expectedReversedQuadraticCurve = QuadraticCurve(p0: CGPoint(x: 6, y: 3), p1: CGPoint(x: 7, y: 5), p2: CGPoint(x: 6, y: 7)) let expectedReversedCubicCurve = CubicCurve(p0: CGPoint(x: 3, y: 5), p1: CGPoint(x: 4, y: 3), p2: CGPoint(x: 5, y: 2), p3: CGPoint(x: 6, y: 3)) func testReversibleLineSegment() { XCTAssertEqual(lineSegment.reversed(), expectedReversedLineSegment) } func testReversibleQuadraticCurve() { XCTAssertEqual(quadraticCurve.reversed(), expectedReversedQuadraticCurve) } func testReversibleCubicCurve() { XCTAssertEqual(cubicCurve.reversed(), expectedReversedCubicCurve) } func testReversiblePathComponent() { let component = PathComponent(curves: [lineSegment, quadraticCurve, cubicCurve]) let expectedReversedComponent = PathComponent(curves: [expectedReversedCubicCurve, expectedReversedQuadraticCurve, expectedReversedLineSegment]) XCTAssertEqual(component.reversed(), expectedReversedComponent) } func testReversiblePath() { let component1 = PathComponent(curve: LineSegment(p0: CGPoint(x: 1, y: 2), p1: CGPoint(x: 3, y: 4))) let component2 = PathComponent(curve: LineSegment(p0: CGPoint(x: 1, y: -2), p1: CGPoint(x: 3, y: 5))) let path = Path(components: [component1, component2]) let reversedComponent1 = PathComponent(curve: LineSegment(p0: CGPoint(x: 3, y: 4), p1: CGPoint(x: 1, y: 2))) let reversedComponent2 = PathComponent(curve: LineSegment(p0: CGPoint(x: 3, y: 5), p1: CGPoint(x: 1, y: -2))) let expectedRerversedPath = Path(components: [reversedComponent1, reversedComponent2]) XCTAssertEqual(path.reversed(), expectedRerversedPath) } }
mit
31ee80dd37cc530688f76b68dda548b1
47.25
152
0.562003
4.135714
false
true
false
false
JGiola/swift
test/expr/closure/multi_statement.swift
1
12036
// RUN: %target-typecheck-verify-swift -swift-version 5 -enable-experimental-static-assert func isInt<T>(_ value: T) -> Bool { return value is Int } func maybeGetValue<T>(_ value: T) -> T? { return value } enum MyError: Error { case featureIsTooCool func doIt() { } } enum State { case suspended case partial(Int, Int) case finished } func random(_: Int) -> Bool { return false } func mightThrow() throws -> Bool { throw MyError.featureIsTooCool } func mapWithMoreStatements(ints: [Int], state: State) throws { let _ = try ints.map { i in guard var actualValue = maybeGetValue(i) else { return String(0) } let value = actualValue + 1 do { if isInt(i) { print(value) } else if value == 17 { print("seventeen!") } } while actualValue < 100 { actualValue += 1 } my_repeat: repeat { print("still here") if i % 7 == 0 { break my_repeat } } while random(i) defer { print("I am so done here") } for j in 0..<i where j % 2 == 0 { if j % 7 == 0 { continue } switch (state, j) { case (.suspended, 0): print("something") fallthrough case (.finished, 0): print("something else") case (.partial(let current, let end), let j): print("\(current) of \(end): \(j)") default: print("so, here we are") } print("even") throw MyError.featureIsTooCool } #assert(true) // expected-warning@+1{{danger zone}} #warning("danger zone") #if false struct NothingHere { } #else struct NestedStruct { var x: Int } #endif do { print(try mightThrow()) } catch let e as MyError { e.doIt() } catch { print(error) } return String(value) } } func acceptsWhateverClosure<T, R>(_ value: T, _ fn: (T) -> R) { } func testReturnWithoutExpr(i: Int) { acceptsWhateverClosure(i) { i in print(i) return } } // `withContiguousStorageIfAvailable` is overloaded, so let's make sure that // filtering works correctly. func test_overloaded_call(arr: [Int], body: (UnsafeBufferPointer<Int>) -> Void) -> Void { arr.withContiguousStorageIfAvailable { buffer in let _ = type(of: buffer) body(buffer) // ok } } // Used to wrap closure in `FunctionConversionExpr` in this case, // but now solver would just inject return expression into optional where necessary. func test_result_optional_injection() { func fn<T>(_: () -> T?) -> [T] { [] } _ = fn { if true { return // Ok } } } let _ = { for i: Int8 in 0 ..< 20 { // Ok (pattern can inform a type of the sequence) print(i) } } func test_workaround_for_optional_void_result() { func test<T>(_: (Int?) -> T?) {} test { guard let x = $0 else { return // Ok } print(x) } test { if $0! > 0 { return } let _ = $0 } func test_concrete(_: (Int) -> Void?) { } test_concrete { guard let x = Optional($0) else { return // Ok } print(x) } test_concrete { if $0 > 0 { return // Ok } let _ = $0 } } enum WrapperEnum<Wrapped> where Wrapped: RawRepresentable { case known(Wrapped) static func ~= (lhs: Wrapped, rhs: WrapperEnum<Wrapped>) -> Bool where Wrapped: Equatable { switch rhs { case .known(let wrapped): return wrapped == lhs } } } func test_custom_tilde_equals_operator_matching() { enum TildeTest : String { case test = "test" case otherTest = "" } func test(_: (WrapperEnum<TildeTest>) -> Void) {} test { v in print(v) switch v { case .test: break // Ok although `.test` comes from `TildeTest` instead of `WrapperEnum` case .otherTest: break // Ok although `.otherTest` comes from `TildeTest` instead of `WrapperEnum` case .known(_): break // Ok - `.known` comes from `WrapperEnum` } } } // Local functions can capture variables before they are declared. func test_local_function_capturing_vars() { struct A { var cond: Bool } func test<T>(fn: () -> T) -> T { fn() } func outer(a: A) { test { func local() { if !message.isEmpty { // Ok print(message) } message = "World" // Ok } var message = a.cond ? "hello" : "" } } } func test_test_invalid_redeclaration() { func test(_: () -> Void) { } test { let foo = 0 // expected-note {{'foo' previously declared here}} let foo = foo // expected-error {{invalid redeclaration of 'foo'}} } test { let (foo, foo) = (5, 6) // expected-error {{invalid redeclaration of 'foo'}} expected-note {{'foo' previously declared here}} } } func test_pattern_ambiguity_doesnot_crash_compiler() { enum E { case hello(result: Int) // expected-note 2 {{found this candidate}} case hello(status: Int) // expected-note 2 {{found this candidate}} } let _: (E) -> Void = { switch $0 { case .hello(_): break // expected-error {{ambiguous use of 'hello'}} } } let _: (E) -> Void = { switch $0 { case let E.hello(x): print(x) // expected-error {{ambiguous use of 'hello'}} default: break } } } func test_taps_type_checked_with_correct_decl_context() { struct Path { func contains<T>(_: T) -> Bool where T: StringProtocol { return false } } let paths: [Path] = [] let strs: [String] = [] _ = paths.filter { path in for str in strs where path.contains("\(str).hello") { return true } return false } } // rdar://90347159 - in pattern matching context `case` should be preferred over static declarations func test_pattern_matches_only_cases() { enum ParsingError : Error { case ok(Int) case failed([Error], Int) static var ok: Int { 42 } static func failed(_: [Error], at: Any) -> Self { fatalError() } } let _: (ParsingError) -> Void = { switch $0 { case let ParsingError.failed(errors, _): print(errors) // Ok default: break } switch $0 { case let ParsingError.ok(result): print(result) // Ok default: break } } } // rdar://91225620 - type of expression is ambiguous without more context in closure func test_wrapped_var_without_initializer() { @propertyWrapper struct Wrapper { private let name: String var wrappedValue: Bool { didSet {} } init(name: String) { self.wrappedValue = false self.name = name } } func fn(_: () -> Void) {} fn { @Wrapper(name: "foo") var v; } } // rdar://92366212 - crash in ConstraintSystem::getType func test_unknown_refs_in_tilde_operator() { enum E { } let _: (E) -> Void = { // expected-error {{unable to infer closure type in the current context}} if case .test(unknown) = $0 { // expected-error@-1 2 {{cannot find 'unknown' in scope}} } } } // rdar://92347054 - crash during conjunction processing func test_no_crash_with_circular_ref_due_to_error() { struct S { // expected-note {{did you mean 'S'?}} var x: Int? } func test(v: Int?, arr: [S]) -> Int { // expected-note {{did you mean 'v'?}} // There is missing `f` here which made body of the // `if` a multiple statement closure instead that uses // `next` inside. i let x = v, let next = arr.first?.x { // expected-error {{cannot find 'i' in scope}} // expected-error@-1 {{consecutive statements on a line must be separated by ';'}} // expected-error@-2 {{'let' cannot appear nested inside another 'var' or 'let' pattern}} // expected-error@-3 {{cannot call value of non-function type 'Int?'}} print(next) return x } return 0 } } func test_diagnosing_on_missing_member_in_case() { enum E { case one } func test(_: (E) -> Void) {} test { switch $0 { case .one: break case .unknown: break // expected-error {{type 'E' has no member 'unknown'}} } } } // rdar://92757114 - fallback diagnostic when member doesn't exist in a nested closure func test_diagnose_missing_member_in_inner_closure() { struct B { static var member: any StringProtocol = "" } struct Cont<T, E: Error> { func resume(returning value: T) {} } func withCont<T>(function: String = #function, _ body: (Cont<T, Never>) -> Void) -> T { fatalError() } func test(vals: [Int]?) -> [Int] { withCont { continuation in guard let vals = vals else { return continuation.resume(returning: []) } B.member.get(0, // expected-error {{value of type 'any StringProtocol' has no member 'get'}} type: "type", withinSecs: Int(60*60)) { arr in let result = arr.compactMap { $0 } return continuation.resume(returning: result) } } } } // Type finder shouldn't bring external closure result type // into the scope of an inner closure e.g. while solving // init of pattern binding `x`. func test_type_finder_doesnt_walk_into_inner_closures() { func test<T>(fn: () -> T) -> T { fn() } _ = test { // Ok let x = test { 42 } let _ = test { test { "" } } // multi-statement let _ = test { _ = 42 return test { "" } } return x } } // rdar://94049113 - compiler accepts non-optional `guard let` in a closure func test_non_optional_guard_let_is_diagnosed() { func fn(_: (Int) -> Void) {} fn { if true { guard let v = $0 else { // expected-error {{initializer for conditional binding must have Optional type, not 'Int'}} return } print(v) } } fn { switch $0 { case (let val): fn { guard let x = val else { // expected-error {{initializer for conditional binding must have Optional type, not 'Int'}} return } print($0 + x) } default: break } } } // rdar://93796211 (issue#59035) - crash during solution application to fallthrough statement func test_fallthrough_stmt() { { var collector: [Void] = [] for _: Void in [] { switch (() as Void?, ()) { case (let a?, let b): // expected-warning@-1 {{constant 'b' inferred to have type '()', which may be unexpected}} // expected-note@-2 {{add an explicit type annotation to silence this warning}} collector.append(a) fallthrough case (nil, let b): // expected-warning@-1 {{constant 'b' inferred to have type '()', which may be unexpected}} // expected-note@-2 {{add an explicit type annotation to silence this warning}} collector.append(b) } } }() } // rdar://93061432 - No diagnostic for invalid `for-in` statement func test_missing_conformance_diagnostics_in_for_sequence() { struct Event {} struct S { struct Iterator: IteratorProtocol { typealias Element = (event: Event, timestamp: Double) mutating func next() -> Element? { return nil } } } func fn(_: () -> Void) {} func test(_ iter: inout S.Iterator) { fn { for v in iter.next() { // expected-error {{for-in loop requires 'S.Iterator.Element?' (aka 'Optional<(event: Event, timestamp: Double)>') to conform to 'Sequence'; did you mean to unwrap optional?}} _ = v.event } } fn { while let v = iter.next() { // ok _ = v.event } } } } func test_conflicting_pattern_vars() { enum E { case a(Int, String) case b(String, Int) } func fn(_: (E) -> Void) {} func fn<T>(_: (E) -> T) {} func test(e: E) { fn { switch $0 { case .a(let x, let y), .b(let x, let y): // expected-error@-1 {{pattern variable bound to type 'String', expected type 'Int'}} // expected-error@-2 {{pattern variable bound to type 'Int', expected type 'String'}} _ = x _ = y } } fn { switch $0 { case .a(let x, let y), .b(let y, let x): // Ok _ = x _ = y } } } }
apache-2.0
a22eb9f2e664186671dbbe248cdcbd18
20.963504
204
0.572782
3.600359
false
true
false
false
parkera/swift
test/attr/attr_availability.swift
2
73052
// RUN: %target-typecheck-verify-swift @available(*, unavailable) func unavailable_func() {} @available(*, unavailable, message: "message") func unavailable_func_with_message() {} @available(tvOS, unavailable) @available(watchOS, unavailable) @available(iOS, unavailable) @available(OSX, unavailable) func unavailable_multiple_platforms() {} @available // expected-error {{expected '(' in 'available' attribute}} func noArgs() {} @available(*) // expected-error {{expected ',' in 'available' attribute}} func noKind() {} @available(badPlatform, unavailable) // expected-warning {{unknown platform 'badPlatform' for attribute 'available'}} func unavailable_bad_platform() {} // Handle unknown platform. @available(HAL9000, unavailable) // expected-warning {{unknown platform 'HAL9000'}} func availabilityUnknownPlatform() {} // <rdar://problem/17669805> Availability can't appear on a typealias @available(*, unavailable, message: "oh no you don't") typealias int = Int // expected-note {{'int' has been explicitly marked unavailable here}} @available(*, unavailable, renamed: "Float") typealias float = Float // expected-note {{'float' has been explicitly marked unavailable here}} protocol MyNewerProtocol {} @available(*, unavailable, renamed: "MyNewerProtocol") protocol MyOlderProtocol {} // expected-note {{'MyOlderProtocol' has been explicitly marked unavailable here}} extension Int: MyOlderProtocol {} // expected-error {{'MyOlderProtocol' has been renamed to 'MyNewerProtocol'}} struct MyCollection<Element> { @available(*, unavailable, renamed: "Element") typealias T = Element // expected-note 2{{'T' has been explicitly marked unavailable here}} func foo(x: T) { } // expected-error {{'T' has been renamed to 'Element'}} {{15-16=Element}} } extension MyCollection { func append(element: T) { } // expected-error {{'T' has been renamed to 'Element'}} {{24-25=Element}} } @available(*, unavailable, renamed: "MyCollection") typealias YourCollection<Element> = MyCollection<Element> // expected-note {{'YourCollection' has been explicitly marked unavailable here}} var x : YourCollection<Int> // expected-error {{'YourCollection' has been renamed to 'MyCollection'}}{{9-23=MyCollection}} var y : int // expected-error {{'int' is unavailable: oh no you don't}} var z : float // expected-error {{'float' has been renamed to 'Float'}}{{9-14=Float}} // Encoded message @available(*, unavailable, message: "This message has a double quote \"") func unavailableWithDoubleQuoteInMessage() {} // expected-note {{'unavailableWithDoubleQuoteInMessage()' has been explicitly marked unavailable here}} func useWithEscapedMessage() { unavailableWithDoubleQuoteInMessage() // expected-error {{'unavailableWithDoubleQuoteInMessage()' is unavailable: This message has a double quote \"}} } // More complicated parsing. @available(OSX, message: "x", unavailable) let _: Int @available(OSX, introduced: 1, deprecated: 2.0, obsoleted: 3.0.0) let _: Int @available(OSX, introduced: 1.0.0, deprecated: 2.0, obsoleted: 3, unavailable, renamed: "x") let _: Int // Meaningless but accepted. @available(OSX, message: "x") let _: Int // Parse errors. @available() // expected-error{{expected platform name or '*' for 'available' attribute}} let _: Int @available(OSX,) // expected-error{{expected 'available' option such as 'unavailable', 'introduced', 'deprecated', 'obsoleted', 'message', or 'renamed'}} let _: Int @available(OSX, message) // expected-error{{expected ':' after 'message' in 'available' attribute}} let _: Int @available(OSX, message: ) // expected-error{{expected string literal in 'available' attribute}} let _: Int @available(OSX, message: x) // expected-error{{expected string literal in 'available' attribute}} let _: Int @available(OSX, unavailable:) // expected-error{{expected ')' in 'available' attribute}} expected-error{{expected declaration}} let _: Int @available(OSX, introduced) // expected-error{{expected ':' after 'introduced' in 'available' attribute}} let _: Int @available(OSX, introduced: ) // expected-error{{expected version number in 'available' attribute}} let _: Int @available(OSX, introduced: x) // expected-error{{expected version number in 'available' attribute}} let _: Int @available(OSX, introduced: 1.x) // expected-error{{expected ')' in 'available' attribute}} expected-error {{expected declaration}} let _: Int @available(OSX, introduced: 1.0.x) // expected-error{{expected version number in 'available' attribute}} let _: Int @available(OSX, introduced: 0x1) // expected-error{{expected version number in 'available' attribute}} let _: Int @available(OSX, introduced: 1.0e4) // expected-error{{expected version number in 'available' attribute}} let _: Int @available(OSX, introduced: -1) // expected-error{{expected version number in 'available' attribute}} expected-error{{expected declaration}} let _: Int @available(OSX, introduced: 1.0.1e4) // expected-error{{expected version number in 'available' attribute}} let _: Int @available(OSX, introduced: 1.0.0x4) // expected-error{{expected version number in 'available' attribute}} let _: Int @available(*, renamed: "bad name") // expected-error{{'renamed' argument of 'available' attribute must be an operator, identifier, or full function name, optionally prefixed by a type name}} let _: Int @available(*, renamed: "_") // expected-error{{'renamed' argument of 'available' attribute must be an operator, identifier, or full function name, optionally prefixed by a type name}} let _: Int @available(*, renamed: "a+b") // expected-error{{'renamed' argument of 'available' attribute must be an operator, identifier, or full function name, optionally prefixed by a type name}} let _: Int @available(*, renamed: "a(") // expected-error{{'renamed' argument of 'available' attribute must be an operator, identifier, or full function name, optionally prefixed by a type name}} let _: Int @available(*, renamed: "a(:)") // expected-error{{'renamed' argument of 'available' attribute must be an operator, identifier, or full function name, optionally prefixed by a type name}} let _: Int @available(*, renamed: "a(:b:)") // expected-error{{'renamed' argument of 'available' attribute must be an operator, identifier, or full function name, optionally prefixed by a type name}} let _: Int @available(*, deprecated, unavailable, message: "message") // expected-error{{'available' attribute cannot be both unconditionally 'unavailable' and 'deprecated'}} struct BadUnconditionalAvailability { }; @available(*, unavailable, message="oh no you don't") // expected-error {{'=' has been replaced with ':' in attribute arguments}} {{35-36=: }} typealias EqualFixIt1 = Int @available(*, unavailable, message = "oh no you don't") // expected-error {{'=' has been replaced with ':' in attribute arguments}} {{36-37=:}} typealias EqualFixIt2 = Int // Encoding in messages @available(*, deprecated, message: "Say \"Hi\"") func deprecated_func_with_message() {} // 'PANDA FACE' (U+1F43C) @available(*, deprecated, message: "Pandas \u{1F43C} are cute") struct DeprecatedTypeWithMessage { } func use_deprecated_with_message() { deprecated_func_with_message() // expected-warning{{'deprecated_func_with_message()' is deprecated: Say \"Hi\"}} var _: DeprecatedTypeWithMessage // expected-warning{{'DeprecatedTypeWithMessage' is deprecated: Pandas \u{1F43C} are cute}} } @available(*, deprecated, message: "message") func use_deprecated_func_with_message2() { deprecated_func_with_message() // no diagnostic } @available(*, deprecated, renamed: "blarg") func deprecated_func_with_renamed() {} @available(*, deprecated, message: "blarg is your friend", renamed: "blarg") func deprecated_func_with_message_renamed() {} @available(*, deprecated, renamed: "wobble") struct DeprecatedTypeWithRename { } func use_deprecated_with_renamed() { deprecated_func_with_renamed() // expected-warning{{'deprecated_func_with_renamed()' is deprecated: renamed to 'blarg'}} // expected-note@-1{{use 'blarg'}}{{3-31=blarg}} deprecated_func_with_message_renamed() //expected-warning{{'deprecated_func_with_message_renamed()' is deprecated: blarg is your friend}} // expected-note@-1{{use 'blarg'}}{{3-39=blarg}} var _: DeprecatedTypeWithRename // expected-warning{{'DeprecatedTypeWithRename' is deprecated: renamed to 'wobble'}} // expected-note@-1{{use 'wobble'}}{{10-34=wobble}} } // Short form of @available() @available(iOS 8.0, *) func functionWithShortFormIOSAvailable() {} @available(iOS 8, *) func functionWithShortFormIOSVersionNoPointAvailable() {} @available(iOS 8.0, OSX 10.10.3, *) func functionWithShortFormIOSOSXAvailable() {} @available(iOS 8.0 // expected-error {{must handle potential future platforms with '*'}} {{19-19=, *}} func shortFormMissingParen() { // expected-error {{expected ')' in 'available' attribute}} } @available(iOS 8.0, // expected-error {{expected platform name}} func shortFormMissingPlatform() { } @available(iOS 8.0, iDishwasherOS 22.0, *) // expected-warning {{unrecognized platform name 'iDishwasherOS'}} func shortFormWithUnrecognizedPlatform() { } @available(iOS 8.0, iDishwasherOS 22.0, iRefrigeratorOS 18.0, *) // expected-warning@-1 {{unrecognized platform name 'iDishwasherOS'}} // expected-warning@-2 {{unrecognized platform name 'iRefrigeratorOS'}} func shortFormWithTwoUnrecognizedPlatforms() { } // Make sure that even after the parser hits an unrecognized // platform it validates the availability. @available(iOS 8.0, iDishwasherOS 22.0, iOS 9.0, *) // expected-warning@-1 {{unrecognized platform name 'iDishwasherOS'}} // expected-error@-2 {{version for 'iOS' already specified}} func shortFormWithUnrecognizedPlatformContinueValidating() { } @available(iOS 8.0, * func shortFormMissingParenAfterWildcard() { // expected-error {{expected ')' in 'available' attribute}} } @available(*) // expected-error {{expected ',' in 'available' attribute}} func onlyWildcardInAvailable() {} @available(iOS 8.0, *, OSX 10.10.3) func shortFormWithWildcardInMiddle() {} @available(iOS 8.0, OSX 10.10.3) // expected-error {{must handle potential future platforms with '*'}} {{32-32=, *}} func shortFormMissingWildcard() {} @availability(OSX, introduced: 10.10) // expected-error {{'@availability' has been renamed to '@available'}} {{2-14=available}} func someFuncUsingOldAttribute() { } // <rdar://problem/23853709> Compiler crash on call to unavailable "print" @available(*, unavailable, message: "Please use the 'to' label for the target stream: 'print((...), to: &...)'") func print<T>(_: T, _: inout TextOutputStream) {} // expected-note {{}} func TextOutputStreamTest(message: String, to: inout TextOutputStream) { print(message, &to) // expected-error {{'print' is unavailable: Please use the 'to' label for the target stream: 'print((...), to: &...)'}} } struct DummyType {} @available(*, unavailable, renamed: "&+") func +(x: DummyType, y: DummyType) {} // expected-note {{here}} @available(*, deprecated, renamed: "&-") func -(x: DummyType, y: DummyType) {} func testOperators(x: DummyType, y: DummyType) { x + y // expected-error {{'+' has been renamed to '&+'}} {{5-6=&+}} x - y // expected-warning {{'-' is deprecated: renamed to '&-'}} expected-note {{use '&-' instead}} {{5-6=&-}} } @available(*, unavailable, renamed: "DummyType.foo") func unavailableMember() {} // expected-note {{here}} @available(*, deprecated, renamed: "DummyType.bar") func deprecatedMember() {} @available(*, unavailable, renamed: "DummyType.Inner.foo") func unavailableNestedMember() {} // expected-note {{here}} @available(*, unavailable, renamed: "DummyType.Foo") struct UnavailableType {} // expected-note {{here}} @available(*, deprecated, renamed: "DummyType.Bar") typealias DeprecatedType = Int func testGlobalToMembers() { unavailableMember() // expected-error {{'unavailableMember()' has been renamed to 'DummyType.foo'}} {{3-20=DummyType.foo}} deprecatedMember() // expected-warning {{'deprecatedMember()' is deprecated: renamed to 'DummyType.bar'}} expected-note {{use 'DummyType.bar' instead}} {{3-19=DummyType.bar}} unavailableNestedMember() // expected-error {{'unavailableNestedMember()' has been renamed to 'DummyType.Inner.foo'}} {{3-26=DummyType.Inner.foo}} let x: UnavailableType? = nil // expected-error {{'UnavailableType' has been renamed to 'DummyType.Foo'}} {{10-25=DummyType.Foo}} _ = x let y: DeprecatedType? = nil // expected-warning {{'DeprecatedType' is deprecated: renamed to 'DummyType.Bar'}} expected-note {{use 'DummyType.Bar' instead}} {{10-24=DummyType.Bar}} _ = y } @available(*, unavailable, renamed: "shinyLabeledArguments(example:)") func unavailableArgNames(a: Int) {} // expected-note {{here}} @available(*, deprecated, renamed: "moreShinyLabeledArguments(example:)") func deprecatedArgNames(b: Int) {} @available(*, unavailable, renamed: "DummyType.shinyLabeledArguments(example:)") func unavailableMemberArgNames(a: Int) {} // expected-note {{here}} @available(*, deprecated, renamed: "DummyType.moreShinyLabeledArguments(example:)") func deprecatedMemberArgNames(b: Int) {} @available(*, unavailable, renamed: "DummyType.shinyLabeledArguments(example:)", message: "ha") func unavailableMemberArgNamesMsg(a: Int) {} // expected-note {{here}} @available(*, deprecated, renamed: "DummyType.moreShinyLabeledArguments(example:)", message: "ha") func deprecatedMemberArgNamesMsg(b: Int) {} @available(*, unavailable, renamed: "shinyLabeledArguments()") func unavailableNoArgs() {} // expected-note {{here}} @available(*, unavailable, renamed: "shinyLabeledArguments(a:)") func unavailableSame(a: Int) {} // expected-note {{here}} @available(*, unavailable, renamed: "shinyLabeledArguments(example:)") func unavailableUnnamed(_ a: Int) {} // expected-note {{here}} @available(*, unavailable, renamed: "shinyLabeledArguments(_:)") func unavailableUnnamedSame(_ a: Int) {} // expected-note {{here}} @available(*, unavailable, renamed: "shinyLabeledArguments(_:)") func unavailableNewlyUnnamed(a: Int) {} // expected-note {{here}} @available(*, unavailable, renamed: "shinyLabeledArguments(veryLongNameToOverflowASmallStringABCDEFGHIJKLMNOPQRSTUVWXYZ:)") func unavailableVeryLongArgNames(a: Int) {} // expected-note {{here}} @available(*, unavailable, renamed: "shinyLabeledArguments(a:b:)") func unavailableMultiSame(a: Int, b: Int) {} // expected-note {{here}} @available(*, unavailable, renamed: "shinyLabeledArguments(example:another:)") func unavailableMultiUnnamed(_ a: Int, _ b: Int) {} // expected-note {{here}} @available(*, unavailable, renamed: "shinyLabeledArguments(_:_:)") func unavailableMultiUnnamedSame(_ a: Int, _ b: Int) {} // expected-note {{here}} @available(*, unavailable, renamed: "shinyLabeledArguments(_:_:)") func unavailableMultiNewlyUnnamed(a: Int, b: Int) {} // expected-note {{here}} @available(*, unavailable, renamed: "Int.init(other:)") func unavailableInit(a: Int) {} // expected-note 2 {{here}} @available(*, unavailable, renamed: "Foo.Bar.init(other:)") func unavailableNestedInit(a: Int) {} // expected-note 2 {{here}} func testArgNames() { unavailableArgNames(a: 0) // expected-error {{'unavailableArgNames(a:)' has been renamed to 'shinyLabeledArguments(example:)'}} {{3-22=shinyLabeledArguments}} {{23-24=example}} deprecatedArgNames(b: 1) // expected-warning {{'deprecatedArgNames(b:)' is deprecated: renamed to 'moreShinyLabeledArguments(example:)'}} expected-note {{use 'moreShinyLabeledArguments(example:)' instead}} {{3-21=moreShinyLabeledArguments}} {{22-23=example}} unavailableMemberArgNames(a: 0) // expected-error {{'unavailableMemberArgNames(a:)' has been replaced by 'DummyType.shinyLabeledArguments(example:)'}} {{3-28=DummyType.shinyLabeledArguments}} {{29-30=example}} deprecatedMemberArgNames(b: 1) // expected-warning {{'deprecatedMemberArgNames(b:)' is deprecated: replaced by 'DummyType.moreShinyLabeledArguments(example:)'}} expected-note {{use 'DummyType.moreShinyLabeledArguments(example:)' instead}} {{3-27=DummyType.moreShinyLabeledArguments}} {{28-29=example}} unavailableMemberArgNamesMsg(a: 0) // expected-error {{'unavailableMemberArgNamesMsg(a:)' has been replaced by 'DummyType.shinyLabeledArguments(example:)': ha}} {{3-31=DummyType.shinyLabeledArguments}} {{32-33=example}} deprecatedMemberArgNamesMsg(b: 1) // expected-warning {{'deprecatedMemberArgNamesMsg(b:)' is deprecated: ha}} expected-note {{use 'DummyType.moreShinyLabeledArguments(example:)' instead}} {{3-30=DummyType.moreShinyLabeledArguments}} {{31-32=example}} unavailableNoArgs() // expected-error {{'unavailableNoArgs()' has been renamed to 'shinyLabeledArguments()'}} {{3-20=shinyLabeledArguments}} unavailableSame(a: 0) // expected-error {{'unavailableSame(a:)' has been renamed to 'shinyLabeledArguments(a:)'}} {{3-18=shinyLabeledArguments}} unavailableUnnamed(0) // expected-error {{'unavailableUnnamed' has been renamed to 'shinyLabeledArguments(example:)'}} {{3-21=shinyLabeledArguments}} {{22-22=example: }} unavailableUnnamedSame(0) // expected-error {{'unavailableUnnamedSame' has been renamed to 'shinyLabeledArguments(_:)'}} {{3-25=shinyLabeledArguments}} unavailableNewlyUnnamed(a: 0) // expected-error {{'unavailableNewlyUnnamed(a:)' has been renamed to 'shinyLabeledArguments(_:)'}} {{3-26=shinyLabeledArguments}} {{27-30=}} unavailableVeryLongArgNames(a: 0) // expected-error {{'unavailableVeryLongArgNames(a:)' has been renamed to 'shinyLabeledArguments(veryLongNameToOverflowASmallStringABCDEFGHIJKLMNOPQRSTUVWXYZ:)'}} {{3-30=shinyLabeledArguments}} {{31-32=veryLongNameToOverflowASmallStringABCDEFGHIJKLMNOPQRSTUVWXYZ}} unavailableMultiSame(a: 0, b: 1) // expected-error {{'unavailableMultiSame(a:b:)' has been renamed to 'shinyLabeledArguments(a:b:)'}} {{3-23=shinyLabeledArguments}} unavailableMultiUnnamed(0, 1) // expected-error {{'unavailableMultiUnnamed' has been renamed to 'shinyLabeledArguments(example:another:)'}} {{3-26=shinyLabeledArguments}} {{27-27=example: }} {{30-30=another: }} unavailableMultiUnnamedSame(0, 1) // expected-error {{'unavailableMultiUnnamedSame' has been renamed to 'shinyLabeledArguments(_:_:)'}} {{3-30=shinyLabeledArguments}} unavailableMultiNewlyUnnamed(a: 0, b: 1) // expected-error {{'unavailableMultiNewlyUnnamed(a:b:)' has been renamed to 'shinyLabeledArguments(_:_:)'}} {{3-31=shinyLabeledArguments}} {{32-35=}} {{38-41=}} unavailableInit(a: 0) // expected-error {{'unavailableInit(a:)' has been replaced by 'Int.init(other:)'}} {{3-18=Int}} {{19-20=other}} let fn = unavailableInit // expected-error {{'unavailableInit(a:)' has been replaced by 'Int.init(other:)'}} {{12-27=Int.init}} fn(1) unavailableNestedInit(a: 0) // expected-error {{'unavailableNestedInit(a:)' has been replaced by 'Foo.Bar.init(other:)'}} {{3-24=Foo.Bar}} {{25-26=other}} let fn2 = unavailableNestedInit // expected-error {{'unavailableNestedInit(a:)' has been replaced by 'Foo.Bar.init(other:)'}} {{13-34=Foo.Bar.init}} fn2(1) } @available(*, unavailable, renamed: "shinyLabeledArguments()") func unavailableTooFew(a: Int) {} // expected-note {{here}} @available(*, unavailable, renamed: "shinyLabeledArguments()") func unavailableTooFewUnnamed(_ a: Int) {} // expected-note {{here}} @available(*, unavailable, renamed: "shinyLabeledArguments(a:b:)") func unavailableTooMany(a: Int) {} // expected-note {{here}} @available(*, unavailable, renamed: "shinyLabeledArguments(a:b:)") func unavailableTooManyUnnamed(_ a: Int) {} // expected-note {{here}} @available(*, unavailable, renamed: "shinyLabeledArguments(a:)") func unavailableNoArgsTooMany() {} // expected-note {{here}} func testRenameArgMismatch() { unavailableTooFew(a: 0) // expected-error{{'unavailableTooFew(a:)' has been renamed to 'shinyLabeledArguments()'}} {{3-20=shinyLabeledArguments}} unavailableTooFewUnnamed(0) // expected-error{{'unavailableTooFewUnnamed' has been renamed to 'shinyLabeledArguments()'}} {{3-27=shinyLabeledArguments}} unavailableTooMany(a: 0) // expected-error{{'unavailableTooMany(a:)' has been renamed to 'shinyLabeledArguments(a:b:)'}} {{3-21=shinyLabeledArguments}} unavailableTooManyUnnamed(0) // expected-error{{'unavailableTooManyUnnamed' has been renamed to 'shinyLabeledArguments(a:b:)'}} {{3-28=shinyLabeledArguments}} unavailableNoArgsTooMany() // expected-error{{'unavailableNoArgsTooMany()' has been renamed to 'shinyLabeledArguments(a:)'}} {{3-27=shinyLabeledArguments}} } @available(*, unavailable, renamed: "Int.foo(self:)") func unavailableInstance(a: Int) {} // expected-note 2 {{here}} @available(*, unavailable, renamed: "Int.foo(self:)") func unavailableInstanceUnlabeled(_ a: Int) {} // expected-note {{here}} @available(*, unavailable, renamed: "Int.foo(self:other:)") func unavailableInstanceFirst(a: Int, b: Int) {} // expected-note {{here}} @available(*, unavailable, renamed: "Int.foo(other:self:)") func unavailableInstanceSecond(a: Int, b: Int) {} // expected-note {{here}} @available(*, unavailable, renamed: "Int.foo(_:self:c:)") func unavailableInstanceSecondOfThree(a: Int, b: Int, c: Int) {} // expected-note {{here}} @available(*, unavailable, renamed: "Int.foo(self:)", message: "blah") func unavailableInstanceMessage(a: Int) {} // expected-note {{here}} @available(*, deprecated, renamed: "Int.foo(self:)") func deprecatedInstance(a: Int) {} @available(*, deprecated, renamed: "Int.foo(self:)", message: "blah") func deprecatedInstanceMessage(a: Int) {} @available(*, unavailable, renamed: "Foo.Bar.foo(self:)") func unavailableNestedInstance(a: Int) {} // expected-note {{here}} func testRenameInstance() { unavailableInstance(a: 0) // expected-error{{'unavailableInstance(a:)' has been replaced by instance method 'Int.foo()'}} {{3-22=0.foo}} {{23-27=}} unavailableInstanceUnlabeled(0) // expected-error{{'unavailableInstanceUnlabeled' has been replaced by instance method 'Int.foo()'}} {{3-31=0.foo}} {{32-33=}} unavailableInstanceFirst(a: 0, b: 1) // expected-error{{'unavailableInstanceFirst(a:b:)' has been replaced by instance method 'Int.foo(other:)'}} {{3-27=0.foo}} {{28-34=}} {{34-35=other}} unavailableInstanceSecond(a: 0, b: 1) // expected-error{{'unavailableInstanceSecond(a:b:)' has been replaced by instance method 'Int.foo(other:)'}} {{3-28=1.foo}} {{29-30=other}} {{33-39=}} unavailableInstanceSecondOfThree(a: 0, b: 1, c: 2) // expected-error{{'unavailableInstanceSecondOfThree(a:b:c:)' has been replaced by instance method 'Int.foo(_:c:)'}} {{3-35=1.foo}} {{36-39=}} {{42-48=}} unavailableInstance(a: 0 + 0) // expected-error{{'unavailableInstance(a:)' has been replaced by instance method 'Int.foo()'}} {{3-22=(0 + 0).foo}} {{23-31=}} unavailableInstanceMessage(a: 0) // expected-error{{'unavailableInstanceMessage(a:)' has been replaced by instance method 'Int.foo()': blah}} {{3-29=0.foo}} {{30-34=}} deprecatedInstance(a: 0) // expected-warning{{'deprecatedInstance(a:)' is deprecated: replaced by instance method 'Int.foo()'}} expected-note{{use 'Int.foo()' instead}} {{3-21=0.foo}} {{22-26=}} deprecatedInstanceMessage(a: 0) // expected-warning{{'deprecatedInstanceMessage(a:)' is deprecated: blah}} expected-note{{use 'Int.foo()' instead}} {{3-28=0.foo}} {{29-33=}} unavailableNestedInstance(a: 0) // expected-error{{'unavailableNestedInstance(a:)' has been replaced by instance method 'Foo.Bar.foo()'}} {{3-28=0.foo}} {{29-33=}} } @available(*, unavailable, renamed: "Int.shinyLabeledArguments(self:)") func unavailableInstanceTooFew(a: Int, b: Int) {} // expected-note {{here}} @available(*, unavailable, renamed: "Int.shinyLabeledArguments(self:)") func unavailableInstanceTooFewUnnamed(_ a: Int, _ b: Int) {} // expected-note {{here}} @available(*, unavailable, renamed: "Int.shinyLabeledArguments(self:b:)") func unavailableInstanceTooMany(a: Int) {} // expected-note {{here}} @available(*, unavailable, renamed: "Int.shinyLabeledArguments(self:b:)") func unavailableInstanceTooManyUnnamed(_ a: Int) {} // expected-note {{here}} @available(*, unavailable, renamed: "Int.shinyLabeledArguments(self:)") func unavailableInstanceNoArgsTooMany() {} // expected-note {{here}} func testRenameInstanceArgMismatch() { unavailableInstanceTooFew(a: 0, b: 1) // expected-error{{'unavailableInstanceTooFew(a:b:)' has been replaced by instance method 'Int.shinyLabeledArguments()'}} {{none}} unavailableInstanceTooFewUnnamed(0, 1) // expected-error{{'unavailableInstanceTooFewUnnamed' has been replaced by instance method 'Int.shinyLabeledArguments()'}} {{none}} unavailableInstanceTooMany(a: 0) // expected-error{{'unavailableInstanceTooMany(a:)' has been replaced by instance method 'Int.shinyLabeledArguments(b:)'}} {{none}} unavailableInstanceTooManyUnnamed(0) // expected-error{{'unavailableInstanceTooManyUnnamed' has been replaced by instance method 'Int.shinyLabeledArguments(b:)'}} {{none}} unavailableInstanceNoArgsTooMany() // expected-error{{'unavailableInstanceNoArgsTooMany()' has been replaced by instance method 'Int.shinyLabeledArguments()'}} {{none}} } @available(*, unavailable, renamed: "getter:Int.prop(self:)") func unavailableInstanceProperty(a: Int) {} // expected-note 2 {{here}} @available(*, unavailable, renamed: "getter:Int.prop(self:)") func unavailableInstancePropertyUnlabeled(_ a: Int) {} // expected-note 2 {{here}} @available(*, unavailable, renamed: "getter:Int.prop()") func unavailableClassProperty() {} // expected-note {{here}} @available(*, unavailable, renamed: "getter:global()") func unavailableGlobalProperty() {} // expected-note {{here}} @available(*, unavailable, renamed: "getter:Int.prop(self:)", message: "blah") func unavailableInstancePropertyMessage(a: Int) {} // expected-note {{here}} @available(*, unavailable, renamed: "getter:Int.prop()", message: "blah") func unavailableClassPropertyMessage() {} // expected-note {{here}} @available(*, unavailable, renamed: "getter:global()", message: "blah") func unavailableGlobalPropertyMessage() {} // expected-note {{here}} @available(*, deprecated, renamed: "getter:Int.prop(self:)") func deprecatedInstanceProperty(a: Int) {} @available(*, deprecated, renamed: "getter:Int.prop()") func deprecatedClassProperty() {} @available(*, deprecated, renamed: "getter:global()") func deprecatedGlobalProperty() {} @available(*, deprecated, renamed: "getter:Int.prop(self:)", message: "blah") func deprecatedInstancePropertyMessage(a: Int) {} @available(*, deprecated, renamed: "getter:Int.prop()", message: "blah") func deprecatedClassPropertyMessage() {} @available(*, deprecated, renamed: "getter:global()", message: "blah") func deprecatedGlobalPropertyMessage() {} func testRenameGetters() { unavailableInstanceProperty(a: 1) // expected-error{{'unavailableInstanceProperty(a:)' has been replaced by property 'Int.prop'}} {{3-30=1.prop}} {{30-36=}} unavailableInstancePropertyUnlabeled(1) // expected-error{{'unavailableInstancePropertyUnlabeled' has been replaced by property 'Int.prop'}} {{3-39=1.prop}} {{39-42=}} unavailableInstanceProperty(a: 1 + 1) // expected-error{{'unavailableInstanceProperty(a:)' has been replaced by property 'Int.prop'}} {{3-30=(1 + 1).prop}} {{30-40=}} unavailableInstancePropertyUnlabeled(1 + 1) // expected-error{{'unavailableInstancePropertyUnlabeled' has been replaced by property 'Int.prop'}} {{3-39=(1 + 1).prop}} {{39-46=}} unavailableClassProperty() // expected-error{{'unavailableClassProperty()' has been replaced by property 'Int.prop'}} {{3-27=Int.prop}} {{27-29=}} unavailableGlobalProperty() // expected-error{{'unavailableGlobalProperty()' has been replaced by 'global'}} {{3-28=global}} {{28-30=}} unavailableInstancePropertyMessage(a: 1) // expected-error{{'unavailableInstancePropertyMessage(a:)' has been replaced by property 'Int.prop': blah}} {{3-37=1.prop}} {{37-43=}} unavailableClassPropertyMessage() // expected-error{{'unavailableClassPropertyMessage()' has been replaced by property 'Int.prop': blah}} {{3-34=Int.prop}} {{34-36=}} unavailableGlobalPropertyMessage() // expected-error{{'unavailableGlobalPropertyMessage()' has been replaced by 'global': blah}} {{3-35=global}} {{35-37=}} deprecatedInstanceProperty(a: 1) // expected-warning {{'deprecatedInstanceProperty(a:)' is deprecated: replaced by property 'Int.prop'}} expected-note{{use 'Int.prop' instead}} {{3-29=1.prop}} {{29-35=}} deprecatedClassProperty() // expected-warning {{'deprecatedClassProperty()' is deprecated: replaced by property 'Int.prop'}} expected-note{{use 'Int.prop' instead}} {{3-26=Int.prop}} {{26-28=}} deprecatedGlobalProperty() // expected-warning {{'deprecatedGlobalProperty()' is deprecated: replaced by 'global'}} expected-note{{use 'global' instead}} {{3-27=global}} {{27-29=}} deprecatedInstancePropertyMessage(a: 1) // expected-warning {{'deprecatedInstancePropertyMessage(a:)' is deprecated: blah}} expected-note{{use 'Int.prop' instead}} {{3-36=1.prop}} {{36-42=}} deprecatedClassPropertyMessage() // expected-warning {{'deprecatedClassPropertyMessage()' is deprecated: blah}} expected-note{{use 'Int.prop' instead}} {{3-33=Int.prop}} {{33-35=}} deprecatedGlobalPropertyMessage() // expected-warning {{'deprecatedGlobalPropertyMessage()' is deprecated: blah}} expected-note{{use 'global' instead}} {{3-34=global}} {{34-36=}} } @available(*, unavailable, renamed: "setter:Int.prop(self:_:)") func unavailableSetInstanceProperty(a: Int, b: Int) {} // expected-note 2 {{here}} @available(*, unavailable, renamed: "setter:Int.prop(_:self:)") func unavailableSetInstancePropertyReverse(a: Int, b: Int) {} // expected-note 2 {{here}} @available(*, unavailable, renamed: "setter:Int.prop(self:newValue:)") func unavailableSetInstancePropertyUnlabeled(_ a: Int, _ b: Int) {} // expected-note 2 {{here}} @available(*, unavailable, renamed: "setter:Int.prop(newValue:self:)") func unavailableSetInstancePropertyUnlabeledReverse(_ a: Int, _ b: Int) {} // expected-note 2 {{here}} @available(*, unavailable, renamed: "setter:Int.prop(x:)") func unavailableSetClassProperty(a: Int) {} // expected-note {{here}} @available(*, unavailable, renamed: "setter:global(_:)") func unavailableSetGlobalProperty(_ a: Int) {} // expected-note {{here}} @available(*, unavailable, renamed: "setter:Int.prop(self:_:)") func unavailableSetInstancePropertyInout(a: inout Int, b: Int) {} // expected-note {{here}} func testRenameSetters() { unavailableSetInstanceProperty(a: 1, b: 2) // expected-error{{'unavailableSetInstanceProperty(a:b:)' has been replaced by property 'Int.prop'}} {{3-33=1.prop}} {{33-43= = }} {{44-45=}} unavailableSetInstancePropertyUnlabeled(1, 2) // expected-error{{'unavailableSetInstancePropertyUnlabeled' has been replaced by property 'Int.prop'}} {{3-42=1.prop}} {{42-46= = }} {{47-48=}} unavailableSetInstancePropertyReverse(a: 1, b: 2) // expected-error{{'unavailableSetInstancePropertyReverse(a:b:)' has been replaced by property 'Int.prop'}} {{3-40=2.prop}} {{40-44= = }} {{45-52=}} unavailableSetInstancePropertyUnlabeledReverse(1, 2) // expected-error{{'unavailableSetInstancePropertyUnlabeledReverse' has been replaced by property 'Int.prop'}} {{3-49=2.prop}} {{49-50= = }} {{51-55=}} unavailableSetInstanceProperty(a: 1 + 1, b: 2 + 2) // expected-error{{'unavailableSetInstanceProperty(a:b:)' has been replaced by property 'Int.prop'}} {{3-33=(1 + 1).prop}} {{33-47= = }} {{52-53=}} unavailableSetInstancePropertyUnlabeled(1 + 1, 2 + 2) // expected-error{{'unavailableSetInstancePropertyUnlabeled' has been replaced by property 'Int.prop'}} {{3-42=(1 + 1).prop}} {{42-50= = }} {{55-56=}} unavailableSetInstancePropertyReverse(a: 1 + 1, b: 2 + 2) // expected-error{{'unavailableSetInstancePropertyReverse(a:b:)' has been replaced by property 'Int.prop'}} {{3-40=(2 + 2).prop}} {{40-44= = }} {{49-60=}} unavailableSetInstancePropertyUnlabeledReverse(1 + 1, 2 + 2) // expected-error{{'unavailableSetInstancePropertyUnlabeledReverse' has been replaced by property 'Int.prop'}} {{3-49=(2 + 2).prop}} {{49-50= = }} {{55-63=}} unavailableSetClassProperty(a: 1) // expected-error{{'unavailableSetClassProperty(a:)' has been replaced by property 'Int.prop'}} {{3-30=Int.prop}} {{30-34= = }} {{35-36=}} unavailableSetGlobalProperty(1) // expected-error{{'unavailableSetGlobalProperty' has been replaced by 'global'}} {{3-31=global}} {{31-32= = }} {{33-34=}} var x = 0 unavailableSetInstancePropertyInout(a: &x, b: 2) // expected-error{{'unavailableSetInstancePropertyInout(a:b:)' has been replaced by property 'Int.prop'}} {{3-38=x.prop}} {{38-49= = }} {{50-51=}} } @available(*, unavailable, renamed: "Int.foo(self:execute:)") func trailingClosure(_ value: Int, fn: () -> Void) {} // expected-note {{here}} @available(*, unavailable, renamed: "Int.foo(self:bar:execute:)") func trailingClosureArg(_ value: Int, _ other: Int, fn: () -> Void) {} // expected-note {{here}} @available(*, unavailable, renamed: "Int.foo(bar:self:execute:)") func trailingClosureArg2(_ value: Int, _ other: Int, fn: () -> Void) {} // expected-note {{here}} func testInstanceTrailingClosure() { // FIXME: regression in fixit due to noescape-by-default trailingClosure(0) {} // expected-error {{'trailingClosure(_:fn:)' has been replaced by instance method 'Int.foo(execute:)'}} // FIXME: {{3-18=0.foo}} {{19-20=}} trailingClosureArg(0, 1) {} // expected-error {{'trailingClosureArg(_:_:fn:)' has been replaced by instance method 'Int.foo(bar:execute:)'}} // FIXME: {{3-21=0.foo}} {{22-25=}} {{25-25=bar: }} trailingClosureArg2(0, 1) {} // expected-error {{'trailingClosureArg2(_:_:fn:)' has been replaced by instance method 'Int.foo(bar:execute:)'}} // FIXME: {{3-22=1.foo}} {{23-23=bar: }} {{24-27=}} } @available(*, unavailable, renamed: "+") func add(_ value: Int, _ other: Int) {} // expected-note {{here}} infix operator *** @available(*, unavailable, renamed: "add") func ***(value: (), other: ()) {} // expected-note {{here}} @available(*, unavailable, renamed: "Int.foo(self:_:)") func ***(value: Int, other: Int) {} // expected-note {{here}} prefix operator *** @available(*, unavailable, renamed: "add") prefix func ***(value: Int?) {} // expected-note {{here}} @available(*, unavailable, renamed: "Int.foo(self:)") prefix func ***(value: Int) {} // expected-note {{here}} postfix operator *** @available(*, unavailable, renamed: "add") postfix func ***(value: Int?) {} // expected-note {{here}} @available(*, unavailable, renamed: "Int.foo(self:)") postfix func ***(value: Int) {} // expected-note {{here}} func testOperators() { add(0, 1) // expected-error {{'add' has been renamed to '+'}} {{none}} () *** () // expected-error {{'***' has been renamed to 'add'}} {{none}} 0 *** 1 // expected-error {{'***' has been replaced by instance method 'Int.foo(_:)'}} {{none}} ***nil // expected-error {{'***' has been renamed to 'add'}} {{none}} ***0 // expected-error {{'***' has been replaced by instance method 'Int.foo()'}} {{none}} nil*** // expected-error {{'***' has been renamed to 'add'}} {{none}} 0*** // expected-error {{'***' has been replaced by instance method 'Int.foo()'}} {{none}} } extension Int { @available(*, unavailable, renamed: "init(other:)") @discardableResult static func factory(other: Int) -> Int { return other } // expected-note 2 {{here}} @available(*, unavailable, renamed: "Int.init(other:)") @discardableResult static func factory2(other: Int) -> Int { return other } // expected-note 2 {{here}} static func testFactoryMethods() { factory(other: 1) // expected-error {{'factory(other:)' has been replaced by 'init(other:)'}} {{none}} factory2(other: 1) // expected-error {{'factory2(other:)' has been replaced by 'Int.init(other:)'}} {{5-13=Int}} } } func testFactoryMethods() { Int.factory(other: 1) // expected-error {{'factory(other:)' has been replaced by 'init(other:)'}} {{6-14=}} Int.factory2(other: 1) // expected-error {{'factory2(other:)' has been replaced by 'Int.init(other:)'}} {{3-15=Int}} } class Base { @available(*, unavailable) func bad() {} // expected-note {{here}} @available(*, unavailable, message: "it was smelly") func smelly() {} // expected-note {{here}} @available(*, unavailable, renamed: "new") func old() {} // expected-note {{here}} @available(*, unavailable, renamed: "new", message: "it was smelly") func oldAndSmelly() {} // expected-note {{here}} @available(*, unavailable) func expendable() {} @available(*, unavailable) var badProp: Int { return 0 } // expected-note {{here}} @available(*, unavailable, message: "it was smelly") var smellyProp: Int { return 0 } // expected-note {{here}} @available(*, unavailable, renamed: "new") var oldProp: Int { return 0 } // expected-note {{here}} @available(*, unavailable, renamed: "new", message: "it was smelly") var oldAndSmellyProp: Int { return 0 } // expected-note {{here}} @available(*, unavailable) var expendableProp: Int { return 0 } @available(*, unavailable, renamed: "init") func nowAnInitializer() {} // expected-note {{here}} @available(*, unavailable, renamed: "init()") func nowAnInitializer2() {} // expected-note {{here}} @available(*, unavailable, renamed: "foo") init(nowAFunction: Int) {} // expected-note {{here}} @available(*, unavailable, renamed: "foo(_:)") init(nowAFunction2: Int) {} // expected-note {{here}} @available(*, unavailable, renamed: "shinyLabeledArguments(example:)") func unavailableArgNames(a: Int) {} // expected-note {{here}} @available(*, unavailable, renamed: "shinyLabeledArguments(example:)") func unavailableArgRenamed(a: Int) {} // expected-note {{here}} @available(*, unavailable, renamed: "shinyLabeledArguments()") func unavailableNoArgs() {} // expected-note {{here}} @available(*, unavailable, renamed: "shinyLabeledArguments(a:)") func unavailableSame(a: Int) {} // expected-note {{here}} @available(*, unavailable, renamed: "shinyLabeledArguments(example:)") func unavailableUnnamed(_ a: Int) {} // expected-note {{here}} @available(*, unavailable, renamed: "shinyLabeledArguments(_:)") func unavailableUnnamedSame(_ a: Int) {} // expected-note {{here}} @available(*, unavailable, renamed: "shinyLabeledArguments(_:)") func unavailableNewlyUnnamed(a: Int) {} // expected-note {{here}} @available(*, unavailable, renamed: "shinyLabeledArguments(a:b:)") func unavailableMultiSame(a: Int, b: Int) {} // expected-note {{here}} @available(*, unavailable, renamed: "shinyLabeledArguments(example:another:)") func unavailableMultiUnnamed(_ a: Int, _ b: Int) {} // expected-note {{here}} @available(*, unavailable, renamed: "shinyLabeledArguments(_:_:)") func unavailableMultiUnnamedSame(_ a: Int, _ b: Int) {} // expected-note {{here}} @available(*, unavailable, renamed: "shinyLabeledArguments(_:_:)") func unavailableMultiNewlyUnnamed(a: Int, b: Int) {} // expected-note {{here}} @available(*, unavailable, renamed: "init(shinyNewName:)") init(unavailableArgNames: Int) {} // expected-note{{here}} @available(*, unavailable, renamed: "init(a:)") init(_ unavailableUnnamed: Int) {} // expected-note{{here}} @available(*, unavailable, renamed: "init(_:)") init(unavailableNewlyUnnamed: Int) {} // expected-note{{here}} @available(*, unavailable, renamed: "init(a:b:)") init(_ unavailableMultiUnnamed: Int, _ b: Int) {} // expected-note{{here}} @available(*, unavailable, renamed: "init(_:_:)") init(unavailableMultiNewlyUnnamed a: Int, b: Int) {} // expected-note{{here}} @available(*, unavailable, renamed: "shinyLabeledArguments(x:)") func unavailableTooFew(a: Int, b: Int) {} // expected-note {{here}} @available(*, unavailable, renamed: "shinyLabeledArguments(x:b:)") func unavailableTooMany(a: Int) {} // expected-note {{here}} @available(*, unavailable, renamed: "shinyLabeledArguments(x:)") func unavailableNoArgsTooMany() {} // expected-note {{here}} @available(*, unavailable, renamed: "Base.shinyLabeledArguments()") func unavailableHasType() {} // expected-note {{here}} } class Sub : Base { override func bad() {} // expected-error {{cannot override 'bad' which has been marked unavailable}} {{none}} expected-note {{remove 'override' modifier to declare a new 'bad'}} {{3-12=}} override func smelly() {} // expected-error {{cannot override 'smelly' which has been marked unavailable: it was smelly}} {{none}} expected-note {{remove 'override' modifier to declare a new 'smelly'}} {{3-12=}} override func old() {} // expected-error {{'old()' has been renamed to 'new'}} {{17-20=new}} expected-note {{remove 'override' modifier to declare a new 'old'}} {{3-12=}} override func oldAndSmelly() {} // expected-error {{'oldAndSmelly()' has been renamed to 'new': it was smelly}} {{17-29=new}} expected-note {{remove 'override' modifier to declare a new 'oldAndSmelly'}} {{3-12=}} func expendable() {} // no-error override var badProp: Int { return 0 } // expected-error {{cannot override 'badProp' which has been marked unavailable}} {{none}} expected-note {{remove 'override' modifier to declare a new 'badProp'}} {{3-12=}} override var smellyProp: Int { return 0 } // expected-error {{cannot override 'smellyProp' which has been marked unavailable: it was smelly}} {{none}} expected-note {{remove 'override' modifier to declare a new 'smellyProp'}} {{3-12=}} override var oldProp: Int { return 0 } // expected-error {{'oldProp' has been renamed to 'new'}} {{16-23=new}} expected-note {{remove 'override' modifier to declare a new 'oldProp'}} {{3-12=}} override var oldAndSmellyProp: Int { return 0 } // expected-error {{'oldAndSmellyProp' has been renamed to 'new': it was smelly}} {{16-32=new}} expected-note {{remove 'override' modifier to declare a new 'oldAndSmellyProp'}} {{3-12=}} var expendableProp: Int { return 0 } // no-error override func nowAnInitializer() {} // expected-error {{'nowAnInitializer()' has been replaced by 'init'}} {{none}} expected-note {{remove 'override' modifier to declare a new 'nowAnInitializer'}} {{3-12=}} override func nowAnInitializer2() {} // expected-error {{'nowAnInitializer2()' has been replaced by 'init()'}} {{none}} expected-note {{remove 'override' modifier to declare a new 'nowAnInitializer2'}} {{3-12=}} override init(nowAFunction: Int) {} // expected-error {{'init(nowAFunction:)' has been renamed to 'foo'}} {{none}} expected-note {{remove 'override' modifier to declare a new 'init'}} {{3-12=}} override init(nowAFunction2: Int) {} // expected-error {{'init(nowAFunction2:)' has been renamed to 'foo(_:)'}} {{none}} expected-note {{remove 'override' modifier to declare a new 'init'}} {{3-12=}} override func unavailableArgNames(a: Int) {} // expected-error {{'unavailableArgNames(a:)' has been renamed to 'shinyLabeledArguments(example:)'}} {{17-36=shinyLabeledArguments}} {{37-37=example }} expected-note {{remove 'override' modifier to declare a new 'unavailableArgNames'}} {{3-12=}} override func unavailableArgRenamed(a param: Int) {} // expected-error {{'unavailableArgRenamed(a:)' has been renamed to 'shinyLabeledArguments(example:)'}} {{17-38=shinyLabeledArguments}} {{39-40=example}} expected-note {{remove 'override' modifier to declare a new 'unavailableArgRenamed'}} {{3-12=}} override func unavailableNoArgs() {} // expected-error {{'unavailableNoArgs()' has been renamed to 'shinyLabeledArguments()'}} {{17-34=shinyLabeledArguments}} expected-note {{remove 'override' modifier to declare a new 'unavailableNoArgs'}} {{3-12=}} override func unavailableSame(a: Int) {} // expected-error {{'unavailableSame(a:)' has been renamed to 'shinyLabeledArguments(a:)'}} {{17-32=shinyLabeledArguments}} expected-note {{remove 'override' modifier to declare a new 'unavailableSame'}} {{3-12=}} override func unavailableUnnamed(_ a: Int) {} // expected-error {{'unavailableUnnamed' has been renamed to 'shinyLabeledArguments(example:)'}} {{17-35=shinyLabeledArguments}} {{36-37=example}} expected-note {{remove 'override' modifier to declare a new 'unavailableUnnamed'}} {{3-12=}} override func unavailableUnnamedSame(_ a: Int) {} // expected-error {{'unavailableUnnamedSame' has been renamed to 'shinyLabeledArguments(_:)'}} {{17-39=shinyLabeledArguments}} expected-note {{remove 'override' modifier to declare a new 'unavailableUnnamedSame'}} {{3-12=}} override func unavailableNewlyUnnamed(a: Int) {} // expected-error {{'unavailableNewlyUnnamed(a:)' has been renamed to 'shinyLabeledArguments(_:)'}} {{17-40=shinyLabeledArguments}} {{41-41=_ }} expected-note {{remove 'override' modifier to declare a new 'unavailableNewlyUnnamed'}} {{3-12=}} override func unavailableMultiSame(a: Int, b: Int) {} // expected-error {{'unavailableMultiSame(a:b:)' has been renamed to 'shinyLabeledArguments(a:b:)'}} {{17-37=shinyLabeledArguments}} expected-note {{remove 'override' modifier to declare a new 'unavailableMultiSame'}} {{3-12=}} override func unavailableMultiUnnamed(_ a: Int, _ b: Int) {} // expected-error {{'unavailableMultiUnnamed' has been renamed to 'shinyLabeledArguments(example:another:)'}} {{17-40=shinyLabeledArguments}} {{41-42=example}} {{51-52=another}} expected-note {{remove 'override' modifier to declare a new 'unavailableMultiUnnamed'}} {{3-12=}} override func unavailableMultiUnnamedSame(_ a: Int, _ b: Int) {} // expected-error {{'unavailableMultiUnnamedSame' has been renamed to 'shinyLabeledArguments(_:_:)'}} {{17-44=shinyLabeledArguments}} expected-note {{remove 'override' modifier to declare a new 'unavailableMultiUnnamedSame'}} {{3-12=}} override func unavailableMultiNewlyUnnamed(a: Int, b: Int) {} // expected-error {{'unavailableMultiNewlyUnnamed(a:b:)' has been renamed to 'shinyLabeledArguments(_:_:)'}} {{17-45=shinyLabeledArguments}} {{46-46=_ }} {{54-54=_ }} expected-note {{remove 'override' modifier to declare a new 'unavailableMultiNewlyUnnamed'}} {{3-12=}} override init(unavailableArgNames: Int) {} // expected-error {{'init(unavailableArgNames:)' has been renamed to 'init(shinyNewName:)'}} {{17-17=shinyNewName }} expected-note {{remove 'override' modifier to declare a new 'init'}} {{3-12=}} override init(_ unavailableUnnamed: Int) {} // expected-error {{'init(_:)' has been renamed to 'init(a:)'}} {{17-18=a}} expected-note {{remove 'override' modifier to declare a new 'init'}} {{3-12=}} override init(unavailableNewlyUnnamed: Int) {} // expected-error {{'init(unavailableNewlyUnnamed:)' has been renamed to 'init(_:)'}} {{17-17=_ }} expected-note {{remove 'override' modifier to declare a new 'init'}} {{3-12=}} override init(_ unavailableMultiUnnamed: Int, _ b: Int) {} // expected-error {{'init(_:_:)' has been renamed to 'init(a:b:)'}} {{17-18=a}} {{49-51=}} expected-note {{remove 'override' modifier to declare a new 'init'}} {{3-12=}} override init(unavailableMultiNewlyUnnamed a: Int, b: Int) {} // expected-error {{'init(unavailableMultiNewlyUnnamed:b:)' has been renamed to 'init(_:_:)'}} {{17-45=_}} {{54-54=_ }} expected-note {{remove 'override' modifier to declare a new 'init'}} {{3-12=}} override func unavailableTooFew(a: Int, b: Int) {} // expected-error {{'unavailableTooFew(a:b:)' has been renamed to 'shinyLabeledArguments(x:)'}} {{none}} expected-note {{remove 'override' modifier to declare a new 'unavailableTooFew'}} {{3-12=}} override func unavailableTooMany(a: Int) {} // expected-error {{'unavailableTooMany(a:)' has been renamed to 'shinyLabeledArguments(x:b:)'}} {{none}} expected-note {{remove 'override' modifier to declare a new 'unavailableTooMany'}} {{3-12=}} override func unavailableNoArgsTooMany() {} // expected-error {{'unavailableNoArgsTooMany()' has been renamed to 'shinyLabeledArguments(x:)'}} {{none}} expected-note {{remove 'override' modifier to declare a new 'unavailableNoArgsTooMany'}} {{3-12=}} override func unavailableHasType() {} // expected-error {{'unavailableHasType()' has been replaced by 'Base.shinyLabeledArguments()'}} {{none}} expected-note {{remove 'override' modifier to declare a new 'unavailableHasType'}} {{3-12=}} } // U: Unnamed, L: Labeled @available(*, unavailable, renamed: "after(fn:)") func closure_U_L(_ x: () -> Int) {} // expected-note 3 {{here}} @available(*, unavailable, renamed: "after(fn:)") func closure_L_L(x: () -> Int) {} // expected-note 3 {{here}} @available(*, unavailable, renamed: "after(_:)") func closure_L_U(x: () -> Int) {} // expected-note 3 {{here}} @available(*, unavailable, renamed: "after(arg:fn:)") func closure_UU_LL(_ x: Int, _ y: () -> Int) {} // expected-note 2 {{here}} @available(*, unavailable, renamed: "after(arg:fn:)") func closure_LU_LL(x: Int, _ y: () -> Int) {} // expected-note 2 {{here}} @available(*, unavailable, renamed: "after(arg:fn:)") func closure_LL_LL(x: Int, y: () -> Int) {} // expected-note 2 {{here}} @available(*, unavailable, renamed: "after(arg:fn:)") func closure_UU_LL_ne(_ x: Int, _ y: () -> Int) {} // expected-note 2 {{here}} @available(*, unavailable, renamed: "after(arg:_:)") func closure_UU_LU(_ x: Int, _ closure: () -> Int) {} // expected-note 2 {{here}} @available(*, unavailable, renamed: "after(arg:_:)") func closure_LU_LU(x: Int, _ closure: () -> Int) {} // expected-note 2 {{here}} @available(*, unavailable, renamed: "after(arg:_:)") func closure_LL_LU(x: Int, y: () -> Int) {} // expected-note 2 {{here}} @available(*, unavailable, renamed: "after(arg:_:)") func closure_UU_LU_ne(_ x: Int, _ y: () -> Int) {} // expected-note 2 {{here}} func testTrailingClosure() { closure_U_L { 0 } // expected-error {{'closure_U_L' has been renamed to 'after(fn:)'}} {{3-14=after}} {{none}} closure_U_L() { 0 } // expected-error {{'closure_U_L' has been renamed to 'after(fn:)'}} {{3-14=after}} {{none}} closure_U_L({ 0 }) // expected-error {{'closure_U_L' has been renamed to 'after(fn:)'}} {{3-14=after}} {{15-15=fn: }} {{none}} closure_L_L { 0 } // expected-error {{'closure_L_L(x:)' has been renamed to 'after(fn:)'}} {{3-14=after}} {{none}} closure_L_L() { 0 } // expected-error {{'closure_L_L(x:)' has been renamed to 'after(fn:)'}} {{3-14=after}} {{none}} closure_L_L(x: { 0 }) // expected-error {{'closure_L_L(x:)' has been renamed to 'after(fn:)'}} {{3-14=after}} {{15-16=fn}} {{none}} closure_L_U { 0 } // expected-error {{'closure_L_U(x:)' has been renamed to 'after(_:)'}} {{3-14=after}} {{none}} closure_L_U() { 0 } // expected-error {{'closure_L_U(x:)' has been renamed to 'after(_:)'}} {{3-14=after}} {{none}} closure_L_U(x: { 0 }) // expected-error {{'closure_L_U(x:)' has been renamed to 'after(_:)'}} {{3-14=after}} {{15-18=}} {{none}} closure_UU_LL(0) { 0 } // expected-error {{'closure_UU_LL' has been renamed to 'after(arg:fn:)'}} {{3-16=after}} {{17-17=arg: }} {{none}} closure_UU_LL(0, { 0 }) // expected-error {{'closure_UU_LL' has been renamed to 'after(arg:fn:)'}} {{3-16=after}} {{17-17=arg: }} {{20-20=fn: }} {{none}} closure_LU_LL(x: 0) { 0 } // expected-error {{'closure_LU_LL(x:_:)' has been renamed to 'after(arg:fn:)'}} {{3-16=after}} {{17-18=arg}} {{none}} closure_LU_LL(x: 0, { 0 }) // expected-error {{'closure_LU_LL(x:_:)' has been renamed to 'after(arg:fn:)'}} {{3-16=after}} {{17-18=arg}} {{23-23=fn: }} {{none}} closure_LL_LL(x: 1) { 1 } // expected-error {{'closure_LL_LL(x:y:)' has been renamed to 'after(arg:fn:)'}} {{3-16=after}} {{17-18=arg}} {{none}} closure_LL_LL(x: 1, y: { 0 }) // expected-error {{'closure_LL_LL(x:y:)' has been renamed to 'after(arg:fn:)'}} {{3-16=after}} {{17-18=arg}} {{23-24=fn}} {{none}} closure_UU_LL_ne(1) { 1 } // expected-error {{'closure_UU_LL_ne' has been renamed to 'after(arg:fn:)'}} {{3-19=after}} {{20-20=arg: }} {{none}} closure_UU_LL_ne(1, { 0 }) // expected-error {{'closure_UU_LL_ne' has been renamed to 'after(arg:fn:)'}} {{3-19=after}} {{20-20=arg: }} {{23-23=fn: }} {{none}} closure_UU_LU(0) { 0 } // expected-error {{'closure_UU_LU' has been renamed to 'after(arg:_:)'}} {{3-16=after}} {{17-17=arg: }} {{none}} closure_UU_LU(0, { 0 }) // expected-error {{'closure_UU_LU' has been renamed to 'after(arg:_:)'}} {{3-16=after}} {{17-17=arg: }} {{none}} closure_LU_LU(x: 0) { 0 } // expected-error {{'closure_LU_LU(x:_:)' has been renamed to 'after(arg:_:)'}} {{3-16=after}} {{17-18=arg}} {{none}} closure_LU_LU(x: 0, { 0 }) // expected-error {{'closure_LU_LU(x:_:)' has been renamed to 'after(arg:_:)'}} {{3-16=after}} {{17-18=arg}} {{none}} closure_LL_LU(x: 1) { 1 } // expected-error {{'closure_LL_LU(x:y:)' has been renamed to 'after(arg:_:)'}} {{3-16=after}} {{17-18=arg}} {{none}} closure_LL_LU(x: 1, y: { 0 }) // expected-error {{'closure_LL_LU(x:y:)' has been renamed to 'after(arg:_:)'}} {{3-16=after}} {{17-18=arg}} {{23-26=}} {{none}} closure_UU_LU_ne(1) { 1 } // expected-error {{'closure_UU_LU_ne' has been renamed to 'after(arg:_:)'}} {{3-19=after}} {{20-20=arg: }} {{none}} closure_UU_LU_ne(1, { 0 }) // expected-error {{'closure_UU_LU_ne' has been renamed to 'after(arg:_:)'}} {{3-19=after}} {{20-20=arg: }} {{none}} } @available(*, unavailable, renamed: "after(x:)") func defaultUnnamed(_ a: Int = 1) {} // expected-note 2 {{here}} @available(*, unavailable, renamed: "after(x:y:)") func defaultBeforeRequired(a: Int = 1, b: Int) {} // expected-note {{here}} @available(*, unavailable, renamed: "after(x:y:z:)") func defaultPlusTrailingClosure(a: Int = 1, b: Int = 2, c: () -> Void) {} // expected-note 3 {{here}} func testDefaults() { defaultUnnamed() // expected-error {{'defaultUnnamed' has been renamed to 'after(x:)'}} {{3-17=after}} {{none}} defaultUnnamed(1) // expected-error {{'defaultUnnamed' has been renamed to 'after(x:)'}} {{3-17=after}} {{18-18=x: }} {{none}} defaultBeforeRequired(b: 5) // expected-error {{'defaultBeforeRequired(a:b:)' has been renamed to 'after(x:y:)'}} {{3-24=after}} {{25-26=y}} {{none}} defaultPlusTrailingClosure {} // expected-error {{'defaultPlusTrailingClosure(a:b:c:)' has been renamed to 'after(x:y:z:)'}} {{3-29=after}} {{none}} defaultPlusTrailingClosure(c: {}) // expected-error {{'defaultPlusTrailingClosure(a:b:c:)' has been renamed to 'after(x:y:z:)'}} {{3-29=after}} {{30-31=z}} {{none}} defaultPlusTrailingClosure(a: 1) {} // expected-error {{'defaultPlusTrailingClosure(a:b:c:)' has been renamed to 'after(x:y:z:)'}} {{3-29=after}} {{30-31=x}} {{none}} } @available(*, unavailable, renamed: "after(x:y:)") func variadic1(a: Int ..., b: Int = 0) {} // expected-note 2 {{here}} @available(*, unavailable, renamed: "after(x:y:)") func variadic2(a: Int, _ b: Int ...) {} // expected-note {{here}} @available(*, unavailable, renamed: "after(x:_:y:z:)") func variadic3(_ a: Int, b: Int ..., c: String = "", d: String) {} // expected-note 2 {{here}} func testVariadic() { variadic1(a: 1, 2) // expected-error {{'variadic1(a:b:)' has been renamed to 'after(x:y:)'}} {{3-12=after}} {{13-14=x}} {{none}} variadic1(a: 1, 2, b: 3) // expected-error {{'variadic1(a:b:)' has been renamed to 'after(x:y:)'}} {{3-12=after}} {{13-14=x}} {{22-23=y}} {{none}} variadic2(a: 1, 2, 3) // expected-error {{'variadic2(a:_:)' has been renamed to 'after(x:y:)'}} {{3-12=after}} {{13-14=x}} {{19-19=y: }} {{none}} variadic3(1, b: 2, 3, d: "test") // expected-error {{'variadic3(_:b:c:d:)' has been renamed to 'after(x:_:y:z:)'}} {{3-12=after}} {{13-13=x: }} {{16-19=}} {{25-26=z}} {{none}} variadic3(1, d:"test") // expected-error {{'variadic3(_:b:c:d:)' has been renamed to 'after(x:_:y:z:)'}} {{3-12=after}} {{13-13=x: }} {{16-17=z}} {{none}} } enum E_32526620 { case foo case bar func set() {} } @available(*, unavailable, renamed: "E_32526620.set(self:)") func rdar32526620_1(a: E_32526620) {} // expected-note {{here}} rdar32526620_1(a: .foo) // expected-error@-1 {{'rdar32526620_1(a:)' has been replaced by instance method 'E_32526620.set()'}} {{1-15=E_32526620.foo.set}} {{16-23=}} @available(*, unavailable, renamed: "E_32526620.set(a:self:)") func rdar32526620_2(a: Int, b: E_32526620) {} // expected-note {{here}} rdar32526620_2(a: 42, b: .bar) // expected-error@-1 {{'rdar32526620_2(a:b:)' has been replaced by instance method 'E_32526620.set(a:)'}} {{1-15=E_32526620.bar.set}} {{21-30=}} @available(*, unavailable, renamed: "E_32526620.set(a:self:c:)") func rdar32526620_3(a: Int, b: E_32526620, c: String) {} // expected-note {{here}} rdar32526620_3(a: 42, b: .bar, c: "question") // expected-error@-1 {{'rdar32526620_3(a:b:c:)' has been replaced by instance method 'E_32526620.set(a:c:)'}} {{1-15=E_32526620.bar.set}} {{23-32=}} var deprecatedGetter: Int { @available(*, deprecated) get { return 0 } set {} } var deprecatedGetterOnly: Int { @available(*, deprecated) get { return 0 } } var deprecatedSetter: Int { get { return 0 } @available(*, deprecated) set {} } var deprecatedBoth: Int { @available(*, deprecated) get { return 0 } @available(*, deprecated) set {} } var deprecatedMessage: Int { @available(*, deprecated, message: "bad getter") get { return 0 } @available(*, deprecated, message: "bad setter") set {} } var deprecatedRename: Int { @available(*, deprecated, renamed: "betterThing()") get { return 0 } @available(*, deprecated, renamed: "setBetterThing(_:)") set {} } @available(*, deprecated, message: "bad variable") var deprecatedProperty: Int { @available(*, deprecated, message: "bad getter") get { return 0 } @available(*, deprecated, message: "bad setter") set {} } _ = deprecatedGetter // expected-warning {{getter for 'deprecatedGetter' is deprecated}} {{none}} deprecatedGetter = 0 deprecatedGetter += 1 // expected-warning {{getter for 'deprecatedGetter' is deprecated}} {{none}} _ = deprecatedGetterOnly // expected-warning {{getter for 'deprecatedGetterOnly' is deprecated}} {{none}} _ = deprecatedSetter deprecatedSetter = 0 // expected-warning {{setter for 'deprecatedSetter' is deprecated}} {{none}} deprecatedSetter += 1 // expected-warning {{setter for 'deprecatedSetter' is deprecated}} {{none}} _ = deprecatedBoth // expected-warning {{getter for 'deprecatedBoth' is deprecated}} {{none}} deprecatedBoth = 0 // expected-warning {{setter for 'deprecatedBoth' is deprecated}} {{none}} deprecatedBoth += 1 // expected-warning {{getter for 'deprecatedBoth' is deprecated}} {{none}} expected-warning {{setter for 'deprecatedBoth' is deprecated}} {{none}} _ = deprecatedMessage // expected-warning {{getter for 'deprecatedMessage' is deprecated: bad getter}} {{none}} deprecatedMessage = 0 // expected-warning {{setter for 'deprecatedMessage' is deprecated: bad setter}} {{none}} deprecatedMessage += 1 // expected-warning {{getter for 'deprecatedMessage' is deprecated: bad getter}} {{none}} expected-warning {{setter for 'deprecatedMessage' is deprecated: bad setter}} {{none}} _ = deprecatedRename // expected-warning {{getter for 'deprecatedRename' is deprecated: renamed to 'betterThing()'}} {{none}} deprecatedRename = 0 // expected-warning {{setter for 'deprecatedRename' is deprecated: renamed to 'setBetterThing(_:)'}} {{none}} deprecatedRename += 1 // expected-warning {{getter for 'deprecatedRename' is deprecated: renamed to 'betterThing()'}} {{none}} expected-warning {{setter for 'deprecatedRename' is deprecated: renamed to 'setBetterThing(_:)'}} {{none}} _ = deprecatedProperty // expected-warning {{'deprecatedProperty' is deprecated: bad variable}} {{none}} deprecatedProperty = 0 // expected-warning {{'deprecatedProperty' is deprecated: bad variable}} {{none}} deprecatedProperty += 1 // expected-warning {{'deprecatedProperty' is deprecated: bad variable}} {{none}} var unavailableGetter: Int { @available(*, unavailable) get { return 0 } // expected-note * {{here}} set {} } var unavailableGetterOnly: Int { @available(*, unavailable) get { return 0 } // expected-note * {{here}} } var unavailableSetter: Int { get { return 0 } @available(*, unavailable) set {} // expected-note * {{here}} } var unavailableBoth: Int { @available(*, unavailable) get { return 0 } // expected-note * {{here}} @available(*, unavailable) set {} // expected-note * {{here}} } var unavailableMessage: Int { @available(*, unavailable, message: "bad getter") get { return 0 } // expected-note * {{here}} @available(*, unavailable, message: "bad setter") set {} // expected-note * {{here}} } var unavailableRename: Int { @available(*, unavailable, renamed: "betterThing()") get { return 0 } // expected-note * {{here}} @available(*, unavailable, renamed: "setBetterThing(_:)") set {} // expected-note * {{here}} } @available(*, unavailable, message: "bad variable") var unavailableProperty: Int { // expected-note * {{here}} @available(*, unavailable, message: "bad getter") get { return 0 } @available(*, unavailable, message: "bad setter") set {} } _ = unavailableGetter // expected-error {{getter for 'unavailableGetter' is unavailable}} {{none}} unavailableGetter = 0 unavailableGetter += 1 // expected-error {{getter for 'unavailableGetter' is unavailable}} {{none}} _ = unavailableGetterOnly // expected-error {{getter for 'unavailableGetterOnly' is unavailable}} {{none}} _ = unavailableSetter unavailableSetter = 0 // expected-error {{setter for 'unavailableSetter' is unavailable}} {{none}} unavailableSetter += 1 // expected-error {{setter for 'unavailableSetter' is unavailable}} {{none}} _ = unavailableBoth // expected-error {{getter for 'unavailableBoth' is unavailable}} {{none}} unavailableBoth = 0 // expected-error {{setter for 'unavailableBoth' is unavailable}} {{none}} unavailableBoth += 1 // expected-error {{getter for 'unavailableBoth' is unavailable}} {{none}} expected-error {{setter for 'unavailableBoth' is unavailable}} {{none}} _ = unavailableMessage // expected-error {{getter for 'unavailableMessage' is unavailable: bad getter}} {{none}} unavailableMessage = 0 // expected-error {{setter for 'unavailableMessage' is unavailable: bad setter}} {{none}} unavailableMessage += 1 // expected-error {{getter for 'unavailableMessage' is unavailable: bad getter}} {{none}} expected-error {{setter for 'unavailableMessage' is unavailable: bad setter}} {{none}} _ = unavailableRename // expected-error {{getter for 'unavailableRename' has been renamed to 'betterThing()'}} {{none}} unavailableRename = 0 // expected-error {{setter for 'unavailableRename' has been renamed to 'setBetterThing(_:)'}} {{none}} unavailableRename += 1 // expected-error {{getter for 'unavailableRename' has been renamed to 'betterThing()'}} {{none}} expected-error {{setter for 'unavailableRename' has been renamed to 'setBetterThing(_:)'}} {{none}} _ = unavailableProperty // expected-error {{'unavailableProperty' is unavailable: bad variable}} {{none}} unavailableProperty = 0 // expected-error {{'unavailableProperty' is unavailable: bad variable}} {{none}} unavailableProperty += 1 // expected-error {{'unavailableProperty' is unavailable: bad variable}} {{none}} struct DeprecatedAccessors { var deprecatedMessage: Int { @available(*, deprecated, message: "bad getter") get { return 0 } @available(*, deprecated, message: "bad setter") set {} } static var staticDeprecated: Int { @available(*, deprecated, message: "bad getter") get { return 0 } @available(*, deprecated, message: "bad setter") set {} } @available(*, deprecated, message: "bad property") var deprecatedProperty: Int { @available(*, deprecated, message: "bad getter") get { return 0 } @available(*, deprecated, message: "bad setter") set {} } subscript(_: Int) -> Int { @available(*, deprecated, message: "bad subscript getter") get { return 0 } @available(*, deprecated, message: "bad subscript setter") set {} } @available(*, deprecated, message: "bad subscript!") subscript(alsoDeprecated _: Int) -> Int { @available(*, deprecated, message: "bad subscript getter") get { return 0 } @available(*, deprecated, message: "bad subscript setter") set {} } mutating func testAccessors(other: inout DeprecatedAccessors) { _ = deprecatedMessage // expected-warning {{getter for 'deprecatedMessage' is deprecated: bad getter}} {{none}} deprecatedMessage = 0 // expected-warning {{setter for 'deprecatedMessage' is deprecated: bad setter}} {{none}} deprecatedMessage += 1 // expected-warning {{getter for 'deprecatedMessage' is deprecated: bad getter}} {{none}} expected-warning {{setter for 'deprecatedMessage' is deprecated: bad setter}} {{none}} _ = other.deprecatedMessage // expected-warning {{getter for 'deprecatedMessage' is deprecated: bad getter}} {{none}} other.deprecatedMessage = 0 // expected-warning {{setter for 'deprecatedMessage' is deprecated: bad setter}} {{none}} other.deprecatedMessage += 1 // expected-warning {{getter for 'deprecatedMessage' is deprecated: bad getter}} {{none}} expected-warning {{setter for 'deprecatedMessage' is deprecated: bad setter}} {{none}} _ = other.deprecatedProperty // expected-warning {{'deprecatedProperty' is deprecated: bad property}} {{none}} other.deprecatedProperty = 0 // expected-warning {{'deprecatedProperty' is deprecated: bad property}} {{none}} other.deprecatedProperty += 1 // expected-warning {{'deprecatedProperty' is deprecated: bad property}} {{none}} _ = DeprecatedAccessors.staticDeprecated // expected-warning {{getter for 'staticDeprecated' is deprecated: bad getter}} {{none}} DeprecatedAccessors.staticDeprecated = 0 // expected-warning {{setter for 'staticDeprecated' is deprecated: bad setter}} {{none}} DeprecatedAccessors.staticDeprecated += 1 // expected-warning {{getter for 'staticDeprecated' is deprecated: bad getter}} {{none}} expected-warning {{setter for 'staticDeprecated' is deprecated: bad setter}} {{none}} _ = other[0] // expected-warning {{getter for 'subscript(_:)' is deprecated: bad subscript getter}} {{none}} other[0] = 0 // expected-warning {{setter for 'subscript(_:)' is deprecated: bad subscript setter}} {{none}} other[0] += 1 // expected-warning {{getter for 'subscript(_:)' is deprecated: bad subscript getter}} {{none}} expected-warning {{setter for 'subscript(_:)' is deprecated: bad subscript setter}} {{none}} _ = other[alsoDeprecated: 0] // expected-warning {{'subscript(alsoDeprecated:)' is deprecated: bad subscript!}} {{none}} other[alsoDeprecated: 0] = 0 // expected-warning {{'subscript(alsoDeprecated:)' is deprecated: bad subscript!}} {{none}} other[alsoDeprecated: 0] += 1 // expected-warning {{'subscript(alsoDeprecated:)' is deprecated: bad subscript!}} {{none}} } } struct UnavailableAccessors { var unavailableMessage: Int { @available(*, unavailable, message: "bad getter") get { return 0 } // expected-note * {{here}} @available(*, unavailable, message: "bad setter") set {} // expected-note * {{here}} } static var staticUnavailable: Int { @available(*, unavailable, message: "bad getter") get { return 0 } // expected-note * {{here}} @available(*, unavailable, message: "bad setter") set {} // expected-note * {{here}} } @available(*, unavailable, message: "bad property") var unavailableProperty: Int { // expected-note * {{here}} @available(*, unavailable, message: "bad getter") get { return 0 } @available(*, unavailable, message: "bad setter") set {} } subscript(_: Int) -> Int { @available(*, unavailable, message: "bad subscript getter") get { return 0 } // expected-note * {{here}} @available(*, unavailable, message: "bad subscript setter") set {} // expected-note * {{here}} } @available(*, unavailable, message: "bad subscript!") subscript(alsoUnavailable _: Int) -> Int { // expected-note * {{here}} @available(*, unavailable, message: "bad subscript getter") get { return 0 } @available(*, unavailable, message: "bad subscript setter") set {} } mutating func testAccessors(other: inout UnavailableAccessors) { _ = unavailableMessage // expected-error {{getter for 'unavailableMessage' is unavailable: bad getter}} {{none}} unavailableMessage = 0 // expected-error {{setter for 'unavailableMessage' is unavailable: bad setter}} {{none}} unavailableMessage += 1 // expected-error {{getter for 'unavailableMessage' is unavailable: bad getter}} {{none}} expected-error {{setter for 'unavailableMessage' is unavailable: bad setter}} {{none}} _ = other.unavailableMessage // expected-error {{getter for 'unavailableMessage' is unavailable: bad getter}} {{none}} other.unavailableMessage = 0 // expected-error {{setter for 'unavailableMessage' is unavailable: bad setter}} {{none}} other.unavailableMessage += 1 // expected-error {{getter for 'unavailableMessage' is unavailable: bad getter}} {{none}} expected-error {{setter for 'unavailableMessage' is unavailable: bad setter}} {{none}} _ = other.unavailableProperty // expected-error {{'unavailableProperty' is unavailable: bad property}} {{none}} other.unavailableProperty = 0 // expected-error {{'unavailableProperty' is unavailable: bad property}} {{none}} other.unavailableProperty += 1 // expected-error {{'unavailableProperty' is unavailable: bad property}} {{none}} _ = UnavailableAccessors.staticUnavailable // expected-error {{getter for 'staticUnavailable' is unavailable: bad getter}} {{none}} UnavailableAccessors.staticUnavailable = 0 // expected-error {{setter for 'staticUnavailable' is unavailable: bad setter}} {{none}} UnavailableAccessors.staticUnavailable += 1 // expected-error {{getter for 'staticUnavailable' is unavailable: bad getter}} {{none}} expected-error {{setter for 'staticUnavailable' is unavailable: bad setter}} {{none}} _ = other[0] // expected-error {{getter for 'subscript(_:)' is unavailable: bad subscript getter}} {{none}} other[0] = 0 // expected-error {{setter for 'subscript(_:)' is unavailable: bad subscript setter}} {{none}} other[0] += 1 // expected-error {{getter for 'subscript(_:)' is unavailable: bad subscript getter}} {{none}} expected-error {{setter for 'subscript(_:)' is unavailable: bad subscript setter}} {{none}} _ = other[alsoUnavailable: 0] // expected-error {{'subscript(alsoUnavailable:)' is unavailable: bad subscript!}} {{none}} other[alsoUnavailable: 0] = 0 // expected-error {{'subscript(alsoUnavailable:)' is unavailable: bad subscript!}} {{none}} other[alsoUnavailable: 0] += 1 // expected-error {{'subscript(alsoUnavailable:)' is unavailable: bad subscript!}} {{none}} } } class BaseDeprecatedInit { @available(*, deprecated) init(bad: Int) { } } class SubInheritedDeprecatedInit: BaseDeprecatedInit { } _ = SubInheritedDeprecatedInit(bad: 0) // expected-warning {{'init(bad:)' is deprecated}} // Should produce no warnings. enum SR8634_Enum: Int { case a @available(*, deprecated, message: "I must not be raised in synthesized code") case b case c } struct SR8634_Struct: Equatable { @available(*, deprecated, message: "I must not be raised in synthesized code", renamed: "x") let a: Int } @available(*, deprecated, message: "This is a message", message: "This is another message") // expected-warning@-1 {{'message' argument has already been specified}} func rdar46348825_message() {} @available(*, deprecated, renamed: "rdar46348825_message", renamed: "unavailable_func_with_message") // expected-warning@-1 {{'renamed' argument has already been specified}} func rdar46348825_renamed() {} @available(swift, introduced: 4.0, introduced: 4.0) // expected-warning@-1 {{'introduced' argument has already been specified}} func rdar46348825_introduced() {} @available(swift, deprecated: 4.0, deprecated: 4.0) // expected-warning@-1 {{'deprecated' argument has already been specified}} func rdar46348825_deprecated() {} @available(swift, obsoleted: 4.0, obsoleted: 4.0) // expected-warning@-1 {{'obsoleted' argument has already been specified}} func rdar46348825_obsoleted() {} // Referencing unavailable types in signatures of unavailable functions should be accepted @available(*, unavailable) protocol UnavailableProto { } @available(*, unavailable) func unavailableFunc(_ arg: UnavailableProto) -> UnavailableProto {} @available(*, unavailable) struct S { var a: UnavailableProto } // Bad rename. struct BadRename { @available(*, deprecated, renamed: "init(range:step:)") init(from: Int, to: Int, step: Int = 1) { } init(range: Range<Int>, step: Int) { } } func testBadRename() { _ = BadRename(from: 5, to: 17) // expected-warning{{'init(from:to:step:)' is deprecated: replaced by 'init(range:step:)'}} // expected-note@-1{{use 'init(range:step:)' instead}} } struct AvailableGenericParam<@available(*, deprecated) T> {} // expected-error@-1 {{'@available' attribute cannot be applied to this declaration}} class UnavailableNoArgsSuperclassInit { @available(*, unavailable) init() {} // expected-note {{'init()' has been explicitly marked unavailable here}} } class UnavailableNoArgsSubclassInit: UnavailableNoArgsSuperclassInit { init(marker: ()) {} // expected-error@-1 {{'init()' is unavailable}} // expected-note@-2 {{call to unavailable initializer 'init()' from superclass 'UnavailableNoArgsSuperclassInit' occurs implicitly at the end of this initializer}} }
apache-2.0
87d766a3b2ef9e5b5af2e31dfa53089b
63.647788
338
0.697134
3.923519
false
false
false
false
liuxuan30/SwiftCharts
Examples/Examples/Examples/ScrollExample.swift
5
5408
// // ScrollExample.swift // SwiftCharts // // Created by ischuetz on 04/05/15. // Copyright (c) 2015 ivanschuetz. All rights reserved. // import UIKit class ScrollExample: UIViewController { private var chart: Chart? // arc override func viewDidLoad() { super.viewDidLoad() let labelSettings = ChartLabelSettings(font: ExamplesDefaults.labelFont) let chartPoints0 = [ self.createChartPoint(2, 2, labelSettings), self.createChartPoint(4, -4, labelSettings), self.createChartPoint(7, 1, labelSettings), self.createChartPoint(8.3, 11.5, labelSettings), self.createChartPoint(9, 15.9, labelSettings), self.createChartPoint(10.8, 3, labelSettings), self.createChartPoint(13, 24, labelSettings), self.createChartPoint(15, 0, labelSettings), self.createChartPoint(17.2, 29, labelSettings), self.createChartPoint(20, 10, labelSettings), self.createChartPoint(22.3, 10, labelSettings), self.createChartPoint(27, 15, labelSettings), self.createChartPoint(30, 6, labelSettings), self.createChartPoint(40, 10, labelSettings), self.createChartPoint(50, 2, labelSettings), ] let chartPoints1 = [ self.createChartPoint(2, 5, labelSettings), self.createChartPoint(3, 7, labelSettings), self.createChartPoint(5, 9, labelSettings), self.createChartPoint(8, 6, labelSettings), self.createChartPoint(9, 10, labelSettings), self.createChartPoint(10, 20, labelSettings), self.createChartPoint(12, 19, labelSettings), self.createChartPoint(13, 20, labelSettings), self.createChartPoint(14, 25, labelSettings), self.createChartPoint(16, 28, labelSettings), self.createChartPoint(17, 15, labelSettings), self.createChartPoint(19, 6, labelSettings), self.createChartPoint(25, 3, labelSettings), self.createChartPoint(30, 10, labelSettings), self.createChartPoint(45, 15, labelSettings), self.createChartPoint(50, 20, labelSettings), ] let xValues = Array(stride(from: 2, through: 50, by: 1)).map {ChartAxisValueFloat($0, labelSettings: labelSettings)} let yValues = ChartAxisValuesGenerator.generateYAxisValuesWithChartPoints(chartPoints0, minSegmentCount: 10, maxSegmentCount: 20, multiple: 2, axisValueGenerator: {ChartAxisValueFloat($0, labelSettings: labelSettings)}, addPaddingSegmentIfEdge: false) let xModel = ChartAxisModel(axisValues: xValues, axisTitleLabel: ChartAxisLabel(text: "Axis title", settings: labelSettings)) let yModel = ChartAxisModel(axisValues: yValues, axisTitleLabel: ChartAxisLabel(text: "Axis title", settings: labelSettings.defaultVertical())) let scrollViewFrame = ExamplesDefaults.chartFrame(self.view.bounds) let chartFrame = CGRectMake(0, 0, 1400, scrollViewFrame.size.height) // calculate coords space in the background to keep UI smooth dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) { let coordsSpace = ChartCoordsSpaceLeftBottomSingleAxis(chartSettings: ExamplesDefaults.chartSettings, chartFrame: chartFrame, xModel: xModel, yModel: yModel) dispatch_async(dispatch_get_main_queue()) { let (xAxis, yAxis, innerFrame) = (coordsSpace.xAxis, coordsSpace.yAxis, coordsSpace.chartInnerFrame) let lineModel0 = ChartLineModel(chartPoints: chartPoints0, lineColor: UIColor.redColor(), animDuration: 1, animDelay: 0) let lineModel1 = ChartLineModel(chartPoints: chartPoints1, lineColor: UIColor.blueColor(), animDuration: 1, animDelay: 0) let chartPointsLineLayer = ChartPointsLineLayer(xAxis: xAxis, yAxis: yAxis, innerFrame: innerFrame, lineModels: [lineModel0, lineModel1]) var settings = ChartGuideLinesDottedLayerSettings(linesColor: UIColor.blackColor(), linesWidth: ExamplesDefaults.guidelinesWidth) let guidelinesLayer = ChartGuideLinesDottedLayer(xAxis: xAxis, yAxis: yAxis, innerFrame: innerFrame, settings: settings) let scrollView = UIScrollView(frame: scrollViewFrame) scrollView.contentSize = CGSizeMake(chartFrame.size.width, scrollViewFrame.size.height) // self.automaticallyAdjustsScrollViewInsets = false // nested view controller - this is in parent let chart = Chart( frame: chartFrame, layers: [ xAxis, yAxis, guidelinesLayer, chartPointsLineLayer ] ) scrollView.addSubview(chart.view) self.view.addSubview(scrollView) self.chart = chart } } } private func createChartPoint(x: CGFloat, _ y: CGFloat, _ labelSettings: ChartLabelSettings) -> ChartPoint { return ChartPoint(x: ChartAxisValueFloat(x, labelSettings: labelSettings), y: ChartAxisValueFloat(y)) } }
apache-2.0
cf484a4d84b9c7ba828abf457a56e4fa
51
259
0.639793
5.359762
false
false
false
false
bingFly/weibo
weibo/weibo/Classes/Tools/SwiftDictModel.swift
1
6660
// // SwiftDictModel.swift // 字典转模型 // // Created by hanbing on 15/3/3. // Copyright (c) 2015年 fly. All rights reserved. // import Foundation /** * 定义协议 */ @objc public protocol DictModelProtocol{ static func customClassMapping() -> [String: String]? } /** * 字典转模型 */ public class SwiftDictModel: NSObject{ //// 提供全局访问接口 public static let sharedManager = SwiftDictModel() /** 将字典转换成模型对象 :param: dict 数据字典 :param: cls 模型类 :returns: 实例化的类对象 */ public func objectWithDictionary(dict: NSDictionary, cls: AnyClass) -> AnyObject?{ let dictInfo = fullModelInfo(cls) var obj: AnyObject = cls.alloc() /** * 类信息字典 */ for (k, v) in dictInfo { /// 取出数据字典中的内容 if let value: AnyObject = dict[k] { // 系统自带的类型 if v.isEmpty { if !(value === NSNull()) { obj.setValue(value, forKey: k) } } else { // 自定义的类型 let type = "\(value.classForCoder)" if type == "NSDictionary" { /// 递归遍历 if let subObj: AnyObject? = objectWithDictionary(value as! NSDictionary, cls: NSClassFromString(v)) { obj.setValue(subObj, forKey: k) } } else if type == "NSArray" { if let subObj: AnyObject? = objectWithArray(value as! NSArray, cls:NSClassFromString(v)) { obj.setValue(subObj, forKey: k) } } } } } return obj } /** 将数组转化成模型 :param: array 数据数组 :param: cls 模型类 :returns: 返回实例化对象数组 */ func objectWithArray(array: NSArray, cls: AnyClass) -> [AnyObject]? { var result = [AnyObject]() for value in array { let type = "\(value.classForCoder)" if type == "NSDictionary" { //MARK: - 这里可能不是cls,如果换了一种类呢? if let subObj: AnyObject = objectWithDictionary(value as! NSDictionary, cls: cls) { result.append(subObj) } } else if type == "NSArray" { /// 递归调用 if let subObj: AnyObject = objectWithArray(value as! NSArray, cls: cls) { result.append(subObj) } } } return result } /// 缓存字典 格式[类名: 模型字典, 类名2: 模型字典] var modelCache = [String: [String: String]]() /** 获取类的完整信息 eg:[b: , info: 字典转模型Tests.Info, others: 字典转模型Tests.Info, i: , f: , num: , other: 字典转模型Tests.Info, str2: , d: , str1: ] :param: cls 给定类 :returns: 返回所有信息 */ func fullModelInfo(cls: AnyClass) -> [String: String] { if let cache = modelCache["\(cls)"] { // println("\(cls)已经被缓存") return cache } var currentCls: AnyClass = cls var dictInfo = [String: String]() while let parent: AnyClass = currentCls.superclass() { dictInfo.merge(modelInfo(currentCls)) currentCls = parent } // 写入缓存 modelCache["\(cls)"] = dictInfo return dictInfo } /** 获取给定类信息 :param: cls 给定类 */ func modelInfo(cls: AnyClass) -> [String: String]{ if let cache = modelCache["\(cls)"] { // println("\(cls)已经被缓存") return cache } var mapping: [String: String]? if cls.respondsToSelector("customClassMapping") { // println("实现了协议") mapping = cls.customClassMapping() } var count: UInt32 = 0 let ivars = class_copyIvarList(cls, &count) // println("属性个数=\(count)") var dictInfo = [String: String]() for i in 0..<count { let v = ivars[Int(i)] let cname = ivar_getName(v) let name = String.fromCString(cname)! var type = mapping?[name] ?? "" // 设置字典 dictInfo[name] = type } free(ivars) modelCache["\(cls)"] = dictInfo return dictInfo } //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ func loadProperty(cls: AnyClass){ var count: UInt32 = 0 let properties = class_copyPropertyList(cls, &count) for i in 0..<count { let property = properties[Int(i)] let cname = property_getName(property) let name = String.fromCString(cname)! let ctype = property_getAttributes(property) let type = String.fromCString(ctype)! } free(properties) } func loadIvars(cls: AnyClass){ var count: UInt32 = 0 let ivars = class_copyIvarList(cls, &count) for i in 0..<count { // 获取属性名称 let v = ivars[Int(i)] let cname = ivar_getName(v) let name = String.fromCString(cname)! let ctype = ivar_getTypeEncoding(v) let type = String.fromCString(ctype)! } free(ivars) } } extension Dictionary{ /** 合并字典的分类 泛型 :param: dict 要合并的字典 */ mutating func merge<K,V>(dict:[K: V]){ for (k,v) in dict { self.updateValue(v as! Value, forKey: k as! Key) } } }
mit
b16cc8ee5bce89843e7777a0774c7be8
23.995968
125
0.429977
4.849765
false
false
false
false
smileyborg/PureLayout
PureLayout/Example-iOS/Demos/iOSDemo6ViewController.swift
4
2171
// // iOSDemo6ViewController.swift // PureLayout Example-iOS // // Copyright (c) 2015 Tyler Fox // https://github.com/PureLayout/PureLayout // import UIKit import PureLayout @objc(iOSDemo6ViewController) class iOSDemo6ViewController: UIViewController { let blueView: UIView = { let view = UIView.newAutoLayout() view.backgroundColor = .blue return view }() var didSetupConstraints = false override func loadView() { view = UIView() view.backgroundColor = UIColor(white: 0.1, alpha: 1.0) view.addSubview(blueView) view.setNeedsUpdateConstraints() // bootstrap Auto Layout } override func updateViewConstraints() { if (!didSetupConstraints) { // Center the blueView in its superview, and match its width to its height blueView.autoCenterInSuperview() blueView.autoMatch(.width, to: .height, of: blueView) // Make sure the blueView is always at least 20 pt from any edge blueView.autoPin(toTopLayoutGuideOf: self, withInset: 20.0, relation: .greaterThanOrEqual) blueView.autoPin(toBottomLayoutGuideOf: self, withInset: 20.0, relation: .greaterThanOrEqual) blueView.autoPinEdge(toSuperviewEdge: .left, withInset: 20.0, relation: .greaterThanOrEqual) blueView.autoPinEdge(toSuperviewEdge: .right, withInset: 20.0, relation: .greaterThanOrEqual) // Add constraints that set the size of the blueView to a ridiculously large size, but set the priority of these constraints // to a lower value than Required. This allows the Auto Layout solver to let these constraints be broken if one or both of // them conflict with higher-priority constraint(s), such as the above 4 edge constraints. NSLayoutConstraint.autoSetPriority(UILayoutPriorityDefaultHigh) { self.blueView.autoSetDimensions(to: CGSize(width: 10000.0, height: 10000.0)) } didSetupConstraints = true } super.updateViewConstraints() } }
mit
ff2398dc145a2dd2b0e5043d72dd7b57
37.767857
136
0.651313
5.14455
false
false
false
false
TucoBZ/GitHub_APi_Test
GitHub_API/RepositoryViewController.swift
1
5005
// // RepositoryViewController.swift // GitHub_API // // Created by Túlio Bazan da Silva on 11/01/16. // Copyright © 2016 TulioBZ. All rights reserved. // import UIKit import PINRemoteImage final class RepositoryViewController: UIViewController { // MARK: - Variables var repo : Array<Repository>? var filteredArray : Array<Repository>? var connection : APIConnection? var searchController : UISearchController! var shouldShowSearchResults = false @IBOutlet var tableView: UITableView! // MARK: - Initialization override func viewDidLoad() { super.viewDidLoad() repo = [] filteredArray = [] configureSearchController() configureConnection() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func configureConnection(){ connection = APIConnection.init(connectionDelegate: self, currentView: self.view) connection?.getRepositories(0) } func configureSearchController() { // Initialize and perform a minimum configuration to the search controller. searchController = UISearchController(searchResultsController: nil) searchController.searchResultsUpdater = self searchController.dimsBackgroundDuringPresentation = false searchController.searchBar.placeholder = "Search here..." searchController.searchBar.delegate = self searchController.searchBar.sizeToFit() // Place the search bar view to the tableview headerview. tableView.tableHeaderView = searchController.searchBar } } // MARK: - UITableViewDelegate extension RepositoryViewController: UITableViewDelegate { func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {} } // MARK: - UITableViewDataSource extension RepositoryViewController: UITableViewDataSource { func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if shouldShowSearchResults { return filteredArray?.count ?? 0 } return repo?.count ?? 0 } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { var cell = UITableViewCell() if let reuseblecell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as? UITableViewCell { if shouldShowSearchResults { //Repository Name and Description if let name = filteredArray?[indexPath.row].name{ reuseblecell.textLabel?.text = name } if let description = filteredArray?[indexPath.row].description { reuseblecell.detailTextLabel?.text = description } } else { //Repository Name and Description if let description = repo?[indexPath.row].description{ reuseblecell.detailTextLabel?.text = description } if let name = repo?[indexPath.row].name,let id = repo?[indexPath.row].id{ reuseblecell.textLabel?.text = "\(name) - ID: \(id)" if repo!.count-1 == indexPath.row{ connection?.getRepositories(id) } } } //Image reuseblecell.imageView?.image = UIImage(named: "githubPlaceHolder") cell = reuseblecell } return cell } } // MARK: - UISearchBarDelegate extension RepositoryViewController: UISearchBarDelegate { func updateSearchResultsForSearchController(searchController: UISearchController) {} } // MARK: - UISearchResultsUpdating extension RepositoryViewController: UISearchResultsUpdating { func searchBarTextDidBeginEditing(searchBar: UISearchBar) { shouldShowSearchResults = false filteredArray = [] } func searchBarCancelButtonClicked(searchBar: UISearchBar) { shouldShowSearchResults = false filteredArray = [] tableView.reloadData() } func searchBarSearchButtonClicked(searchBar: UISearchBar) { if !shouldShowSearchResults { shouldShowSearchResults = true connection?.searchForRepositories(searchBar.text!) } searchController.searchBar.resignFirstResponder() } } // MARK: - ConnectionDelegate extension RepositoryViewController: ConnectionDelegate { func updatedUsers(users: Array<User>) {} func updatedSearchUsers(users: Array<User>) {} func updatedRepositories(repositories: Array<Repository>) { repo?.appendAll(repositories) tableView?.reloadData() } func updatedSearchRepositories(repositories: Array<Repository>){ filteredArray = repositories tableView?.reloadData() } }
mit
86a642596cf65eb1c21e159eb3614980
32.804054
128
0.652808
5.90673
false
false
false
false
ProjectDent/ARKit-CoreLocation
Sources/ARKit-CoreLocation/SceneLocationView.swift
1
20980
// // SceneLocationView.swift // ARKit+CoreLocation // // Created by Andrew Hart on 02/07/2017. // Copyright © 2017 Project Dent. All rights reserved. // import Foundation import ARKit import CoreLocation import MapKit //Should conform to delegate here, add in future commit @available(iOS 11.0, *) /// `SceneLocationView` is the `ARSCNView` subclass used to render an ARCL scene. /// /// Note that all of the standard SceneKit/ARKit delegates and delegate methods are used /// internally by ARCL. The delegate functions declared in `ARSCNViewDelegate`, `ARSessionObserver`, and `ARSCNView` are /// shadowed by `ARSCNViewDelegate` and invoked on the `SceneLocationView`'s `arDelegate`. If you need to receive /// any of these callbacks, implement them on your `arDelegate`. open class SceneLocationView: ARSCNView { /// The limit to the scene, in terms of what data is considered reasonably accurate. /// Measured in meters. static let sceneLimit = 100.0 /// The type of tracking to use. /// /// - orientationTracking: Informs the `SceneLocationView` to use Device Orientation tracking only. /// Useful when your nodes are all CLLocation based, and are not synced to real world planes /// See [Apple's documentation](https://developer.apple.com/documentation/arkit/arorientationtrackingconfiguration) /// - worldTracking: Informs the `SceneLocationView` to use a World Tracking Configuration. /// Useful when you have nodes that attach themselves to real world planes /// See [Apple's documentation](https://developer.apple.com/documentation/arkit/arworldtrackingconfiguration#overview) public enum ARTrackingType { case orientationTracking case worldTracking } public weak var locationViewDelegate: SceneLocationViewDelegate? public weak var locationEstimateDelegate: SceneLocationViewEstimateDelegate? public weak var locationNodeTouchDelegate: LNTouchDelegate? public weak var sceneTrackingDelegate: SceneTrackingDelegate? public let sceneLocationManager = SceneLocationManager() /// Addresses [Issue #196](https://github.com/ProjectDent/ARKit-CoreLocation/issues/196) - /// Delegate issue when assigned to self (no location nodes render). If the user /// tries to set the delegate, perform an assertionFailure and tell them to set the `arViewDelegate` instead. open override var delegate: ARSCNViewDelegate? { set { if let newValue = newValue, !(newValue is SceneLocationView) { assertionFailure("Set the arViewDelegate instead") } else if self.delegate != nil, newValue == nil { assertionFailure("Attempted to nil the existing delegate (it must be self). Set the arViewDelegate instead") } super.delegate = newValue } get { return super.delegate } } /// If you wish to receive delegate `ARSCNViewDelegate` events, use this instead of the `delegate` property. /// The `delegate` property is reserved for this class itself and trying to set it will result in an assertionFailure /// and in production, things just won't work as you expect. public weak var arViewDelegate: ARSCNViewDelegate? /// The method to use for determining locations. /// Not advisable to change this as the scene is ongoing. public var locationEstimateMethod: LocationEstimateMethod { get { return sceneLocationManager.locationEstimateMethod } set { sceneLocationManager.locationEstimateMethod = newValue locationNodes.forEach { $0.locationEstimateMethod = newValue } } } /// When set to true, displays an axes node at the start of the scene public var showAxesNode = false public internal(set) var sceneNode: SCNNode? { didSet { guard sceneNode != nil else { return } locationNodes.forEach { sceneNode?.addChildNode($0) } locationViewDelegate?.didSetupSceneNode(sceneLocationView: self, sceneNode: sceneNode!) } } /// Only to be overrided if you plan on manually setting True North. /// When true, sets up the scene to face what the device considers to be True North. /// This can be inaccurate, hence the option to override it. /// The functions for altering True North can be used irrespective of this value, /// but if the scene is oriented to true north, it will update without warning, /// thus affecting your alterations. /// The initial value of this property is respected. public var orientToTrueNorth = true /// Whether debugging feature points should be displayed. /// Defaults to false public var showFeaturePoints = false // MARK: Scene location estimates public var currentScenePosition: SCNVector3? { guard let pointOfView = pointOfView else { return nil } return scene.rootNode.convertPosition(pointOfView.position, to: sceneNode) } public var currentEulerAngles: SCNVector3? { return pointOfView?.eulerAngles } public internal(set) var locationNodes = [LocationNode]() public internal(set) var polylineNodes = [PolylineNode]() public internal(set) var arTrackingType: ARTrackingType = .worldTracking // MARK: Internal desclarations internal var didFetchInitialLocation = false // MARK: Setup /// This initializer allows you to specify the type of tracking configuration (defaults to world tracking) as well as /// some other optional values. /// /// - Parameters: /// - trackingType: The type of AR Tracking configuration (defaults to world tracking). /// - frame: The CGRect for the frame (defaults to .zero). /// - options: The rendering options for the `SCNView`. public convenience init(trackingType: ARTrackingType = .worldTracking, frame: CGRect = .zero, options: [String: Any]? = nil) { self.init(frame: frame, options: options) self.arTrackingType = trackingType } public override init(frame: CGRect, options: [String: Any]? = nil) { super.init(frame: frame, options: options) finishInitialization() } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) finishInitialization() } private func finishInitialization() { sceneLocationManager.sceneLocationDelegate = self delegate = self // Show statistics such as fps and timing information showsStatistics = false debugOptions = showFeaturePoints ? [ARSCNDebugOptions.showFeaturePoints] : debugOptions let touchGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(sceneLocationViewTouched(sender:))) self.addGestureRecognizer(touchGestureRecognizer) } /// Resets the scene heading to 0 func resetSceneHeading() { sceneNode?.eulerAngles.y = 0 } func confirmLocationOfLocationNode(_ locationNode: LocationNode) { locationNode.location = locationOfLocationNode(locationNode) locationViewDelegate?.didConfirmLocationOfNode(sceneLocationView: self, node: locationNode) } /// Gives the best estimate of the location of a node public func locationOfLocationNode(_ locationNode: LocationNode) -> CLLocation { if locationNode.locationConfirmed || locationEstimateMethod == .coreLocationDataOnly { return locationNode.location! } if let bestLocationEstimate = sceneLocationManager.bestLocationEstimate, locationNode.location == nil || bestLocationEstimate.location.horizontalAccuracy < locationNode.location!.horizontalAccuracy { return bestLocationEstimate.translatedLocation(to: locationNode.position) } else { return locationNode.location! } } } @available(iOS 11.0, *) public extension SceneLocationView { func run() { switch arTrackingType { case .worldTracking: let configuration = ARWorldTrackingConfiguration() configuration.planeDetection = .horizontal configuration.worldAlignment = orientToTrueNorth ? .gravityAndHeading : .gravity session.run(configuration) case .orientationTracking: let configuration = AROrientationTrackingConfiguration() configuration.worldAlignment = orientToTrueNorth ? .gravityAndHeading : .gravity session.run(configuration) } sceneLocationManager.run() } func pause() { session.pause() sceneLocationManager.pause() } // MARK: True North /// iOS can be inaccurate when setting true north /// The scene is oriented to true north, and will update its heading when it gets a more accurate reading /// You can disable this through setting the /// These functions provide manual overriding of the scene heading, /// if you have a more precise idea of where True North is /// The goal is for the True North orientation problems to be resolved /// At which point these functions would no longer be useful /// Moves the scene heading clockwise by 1 degree /// Intended for correctional purposes func moveSceneHeadingClockwise() { sceneNode?.eulerAngles.y -= Float(1).degreesToRadians } /// Moves the scene heading anti-clockwise by 1 degree /// Intended for correctional purposes func moveSceneHeadingAntiClockwise() { sceneNode?.eulerAngles.y += Float(1).degreesToRadians } // MARK: LocationNodes /// Upon being added, a node's location, locationConfirmed and position may be modified and should not be changed externally. /// Silently fails and returns without adding the node to the scene if any of `currentScenePosition`, /// `sceneLocationManager.currentLocation`, or `sceneNode` is `nil`. func addLocationNodeForCurrentPosition(locationNode: LocationNode) { guard let currentPosition = currentScenePosition, let currentLocation = sceneLocationManager.currentLocation, let sceneNode = sceneNode else { return } locationNode.location = currentLocation locationNode.position = currentPosition locationNodes.append(locationNode) sceneNode.addChildNode(locationNode) } /// Each node's addition to the scene can silently fail; See `addLocationNodeForCurrentPosition(locationNode:)`. /// /// Why would we want to add multiple nodes at the current position? func addLocationNodesForCurrentPosition(locationNodes: [LocationNode]) { locationNodes.forEach { addLocationNodeForCurrentPosition(locationNode: $0) } } /// Silently fails and returns without adding the node unless`location` is not `nil` and `locationConfirmed` is `true`. /// Upon being added, a node's position will be modified internally and should not be changed externally. /// `location` will not be modified, but taken as accurate. func addLocationNodeWithConfirmedLocation(locationNode: LocationNode) { if locationNode.location == nil || locationNode.locationConfirmed == false { return } let locationNodeLocation = locationOfLocationNode(locationNode) locationNode.updatePositionAndScale(setup: true, scenePosition: currentScenePosition, locationNodeLocation: locationNodeLocation, locationManager: sceneLocationManager) { self.locationViewDelegate? .didUpdateLocationAndScaleOfLocationNode(sceneLocationView: self, locationNode: locationNode) } locationNodes.append(locationNode) sceneNode?.addChildNode(locationNode) } @objc func sceneLocationViewTouched(sender: UITapGestureRecognizer) { guard let touchedView = sender.view as? SCNView else { return } let coordinates = sender.location(in: touchedView) let hitTests = touchedView.hitTest(coordinates) guard let firstHitTest = hitTests.first else { return } if let touchedNode = firstHitTest.node as? AnnotationNode { self.locationNodeTouchDelegate?.annotationNodeTouched(node: touchedNode) } else if let locationNode = firstHitTest.node.parent as? LocationNode { self.locationNodeTouchDelegate?.locationNodeTouched(node: locationNode) } } /// Each node's addition to the scene can silently fail; See `addLocationNodeWithConfirmedLocation(locationNode:)`. func addLocationNodesWithConfirmedLocation(locationNodes: [LocationNode]) { locationNodes.forEach { addLocationNodeWithConfirmedLocation(locationNode: $0) } } func removeAllNodes() { locationNodes.removeAll() guard let childNodes = sceneNode?.childNodes else { return } for node in childNodes { node.removeFromParentNode() } } /// Determine if scene contains a node with the specified tag /// /// - Parameter tag: tag text /// - Returns: true if a LocationNode with the tag exists; false otherwise func sceneContainsNodeWithTag(_ tag: String) -> Bool { return findNodes(tagged: tag).count > 0 } /// Find all location nodes in the scene tagged with `tag` /// /// - Parameter tag: The tag text for which to search nodes. /// - Returns: A list of all matching tags func findNodes(tagged tag: String) -> [LocationNode] { guard tag.count > 0 else { return [] } return locationNodes.filter { $0.tag == tag } } func removeLocationNode(locationNode: LocationNode) { if let index = locationNodes.firstIndex(of: locationNode) { locationNodes.remove(at: index) } locationNode.removeFromParentNode() } func removeLocationNodes(locationNodes: [LocationNode]) { locationNodes.forEach { removeLocationNode(locationNode: $0) } } } @available(iOS 11.0, *) public extension SceneLocationView { /// Adds routes to the scene and lets you specify the geometry prototype for the box. /// Note: You can provide your own SCNBox prototype to base the direction nodes from. /// /// - Parameters: /// - routes: The MKRoute of directions /// - boxBuilder: A block that will customize how a box is built. func addRoutes(routes: [MKRoute], boxBuilder: BoxBuilder? = nil) { addRoutes(polylines: routes.map { AttributedType(type: $0.polyline, attribute: $0.name) }, boxBuilder: boxBuilder) } /// Adds polylines to the scene and lets you specify the geometry prototype for the box. /// Note: You can provide your own SCNBox prototype to base the direction nodes from. /// /// - Parameters: /// - polylines: The list of attributed MKPolyline to rendered /// - Δaltitude: difference between box and current user altitude /// - boxBuilder: A block that will customize how a box is built. func addRoutes(polylines: [AttributedType<MKPolyline>], Δaltitude: CLLocationDistance = -2.0, boxBuilder: BoxBuilder? = nil) { guard let altitude = sceneLocationManager.currentLocation?.altitude else { return assertionFailure("we don't have an elevation") } let polyNodes = polylines.map { PolylineNode(polyline: $0.type, altitude: altitude + Δaltitude, tag: $0.attribute, boxBuilder: boxBuilder) } polylineNodes.append(contentsOf: polyNodes) polyNodes.forEach { $0.locationNodes.forEach { let locationNodeLocation = self.locationOfLocationNode($0) $0.updatePositionAndScale(setup: true, scenePosition: currentScenePosition, locationNodeLocation: locationNodeLocation, locationManager: sceneLocationManager, onCompletion: {}) sceneNode?.addChildNode($0) } } } func removeRoutes(routes: [MKRoute]) { routes.forEach { route in if let index = polylineNodes.firstIndex(where: { $0.polyline == route.polyline }) { polylineNodes.remove(at: index) } } } } @available(iOS 11.0, *) public extension SceneLocationView { /// Adds polylines to the scene and lets you specify the geometry prototype for the box. /// Note: You can provide your own SCNBox prototype to base the direction nodes from. /// /// - Parameters: /// - polylines: A set of MKPolyline. /// - boxBuilder: A block that will customize how a box is built. func addPolylines(polylines: [MKPolyline], boxBuilder: BoxBuilder? = nil) { guard let altitude = sceneLocationManager.currentLocation?.altitude else { return assertionFailure("we don't have an elevation") } polylines.forEach { (polyline) in polylineNodes.append(PolylineNode(polyline: polyline, altitude: altitude - 2.0, boxBuilder: boxBuilder)) } polylineNodes.forEach { $0.locationNodes.forEach { let locationNodeLocation = self.locationOfLocationNode($0) $0.updatePositionAndScale(setup: true, scenePosition: currentScenePosition, locationNodeLocation: locationNodeLocation, locationManager: sceneLocationManager, onCompletion: {}) sceneNode?.addChildNode($0) } } } func removePolylines(polylines: [MKPolyline]) { polylines.forEach { polyline in if let index = polylineNodes.firstIndex(where: { $0.polyline == polyline }) { polylineNodes.remove(at: index) } } } } @available(iOS 11.0, *) extension SceneLocationView: SceneLocationManagerDelegate { var scenePosition: SCNVector3? { return currentScenePosition } func confirmLocationOfDistantLocationNodes() { guard let currentPosition = currentScenePosition else { return } locationNodes.filter { !$0.locationConfirmed }.forEach { let currentPoint = CGPoint.pointWithVector(vector: currentPosition) let locationNodePoint = CGPoint.pointWithVector(vector: $0.position) if !currentPoint.radiusContainsPoint(radius: CGFloat(SceneLocationView.sceneLimit), point: locationNodePoint) { confirmLocationOfLocationNode($0) } } } /// Updates the position and scale of the `polylineNodes` and the `locationNodes`. func updatePositionAndScaleOfLocationNodes() { polylineNodes.filter { $0.continuallyUpdatePositionAndScale }.forEach { node in node.locationNodes.forEach { node in let locationNodeLocation = self.locationOfLocationNode(node) node.updatePositionAndScale( setup: false, scenePosition: currentScenePosition, locationNodeLocation: locationNodeLocation, locationManager: sceneLocationManager) { self.locationViewDelegate?.didUpdateLocationAndScaleOfLocationNode( sceneLocationView: self, locationNode: node) } // updatePositionAndScale } // foreach Location node } // foreach Polyline node locationNodes.filter { $0.continuallyUpdatePositionAndScale }.forEach { node in let locationNodeLocation = locationOfLocationNode(node) node.updatePositionAndScale( scenePosition: currentScenePosition, locationNodeLocation: locationNodeLocation, locationManager: sceneLocationManager) { self.locationViewDelegate?.didUpdateLocationAndScaleOfLocationNode( sceneLocationView: self, locationNode: node) } } } func didAddSceneLocationEstimate(position: SCNVector3, location: CLLocation) { locationEstimateDelegate?.didAddSceneLocationEstimate(sceneLocationView: self, position: position, location: location) } func didRemoveSceneLocationEstimate(position: SCNVector3, location: CLLocation) { locationEstimateDelegate?.didRemoveSceneLocationEstimate(sceneLocationView: self, position: position, location: location) } }
mit
ee29c36bb0629ab75de4a1e5c1e82209
41.375758
130
0.662233
5.061776
false
false
false
false
naokits/my-programming-marathon
iPhoneSensorDemo/Pods/RxCocoa/RxCocoa/Common/Observables/NSURLSession+Rx.swift
7
8194
// // NSURLSession+Rx.swift // RxCocoa // // Created by Krunoslav Zaher on 3/23/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // import Foundation #if !RX_NO_MODULE import RxSwift #endif /** RxCocoa URL errors. */ public enum RxCocoaURLError : ErrorType , CustomDebugStringConvertible { /** Unknown error occurred. */ case Unknown /** Response is not NSHTTPURLResponse */ case NonHTTPResponse(response: NSURLResponse) /** Response is not successful. (not in `200 ..< 300` range) */ case HTTPRequestFailed(response: NSHTTPURLResponse, data: NSData?) /** Deserialization error. */ case DeserializationError(error: ErrorType) } public extension RxCocoaURLError { /** A textual representation of `self`, suitable for debugging. */ public var debugDescription: String { switch self { case .Unknown: return "Unknown error has occurred." case let .NonHTTPResponse(response): return "Response is not NSHTTPURLResponse `\(response)`." case let .HTTPRequestFailed(response, _): return "HTTP request failed with `\(response.statusCode)`." case let .DeserializationError(error): return "Error during deserialization of the response: \(error)" } } } func escapeTerminalString(value: String) -> String { return value.stringByReplacingOccurrencesOfString("\"", withString: "\\\"", options:[], range: nil) } func convertURLRequestToCurlCommand(request: NSURLRequest) -> String { let method = request.HTTPMethod ?? "GET" var returnValue = "curl -X \(method) " if request.HTTPMethod == "POST" && request.HTTPBody != nil { let maybeBody = NSString(data: request.HTTPBody!, encoding: NSUTF8StringEncoding) as? String if let body = maybeBody { returnValue += "-d \"\(escapeTerminalString(body))\" " } } for (key, value) in request.allHTTPHeaderFields ?? [:] { let escapedKey = escapeTerminalString((key as String) ?? "") let escapedValue = escapeTerminalString((value as String) ?? "") returnValue += "\n -H \"\(escapedKey): \(escapedValue)\" " } let URLString = request.URL?.absoluteString ?? "<unknown url>" returnValue += "\n\"\(escapeTerminalString(URLString))\"" returnValue += " -i -v" return returnValue } func convertResponseToString(data: NSData!, _ response: NSURLResponse!, _ error: NSError!, _ interval: NSTimeInterval) -> String { let ms = Int(interval * 1000) if let response = response as? NSHTTPURLResponse { if 200 ..< 300 ~= response.statusCode { return "Success (\(ms)ms): Status \(response.statusCode)" } else { return "Failure (\(ms)ms): Status \(response.statusCode)" } } if let error = error { if error.domain == NSURLErrorDomain && error.code == NSURLErrorCancelled { return "Cancelled (\(ms)ms)" } return "Failure (\(ms)ms): NSError > \(error)" } return "<Unhandled response from server>" } extension NSURLSession { /** Observable sequence of responses for URL request. Performing of request starts after observer is subscribed and not after invoking this method. **URL requests will be performed per subscribed observer.** Any error during fetching of the response will cause observed sequence to terminate with error. - parameter request: URL request. - returns: Observable sequence of URL responses. */ @warn_unused_result(message="http://git.io/rxs.uo") public func rx_response(request: NSURLRequest) -> Observable<(NSData, NSHTTPURLResponse)> { return Observable.create { observer in // smart compiler should be able to optimize this out var d: NSDate? if Logging.URLRequests(request) { d = NSDate() } let task = self.dataTaskWithRequest(request) { (data, response, error) in if Logging.URLRequests(request) { let interval = NSDate().timeIntervalSinceDate(d ?? NSDate()) print(convertURLRequestToCurlCommand(request)) print(convertResponseToString(data, response, error, interval)) } guard let response = response, data = data else { observer.on(.Error(error ?? RxCocoaURLError.Unknown)) return } guard let httpResponse = response as? NSHTTPURLResponse else { observer.on(.Error(RxCocoaURLError.NonHTTPResponse(response: response))) return } observer.on(.Next(data, httpResponse)) observer.on(.Completed) } let t = task t.resume() return AnonymousDisposable { task.cancel() } } } /** Observable sequence of response data for URL request. Performing of request starts after observer is subscribed and not after invoking this method. **URL requests will be performed per subscribed observer.** Any error during fetching of the response will cause observed sequence to terminate with error. If response is not HTTP response with status code in the range of `200 ..< 300`, sequence will terminate with `(RxCocoaErrorDomain, RxCocoaError.NetworkError)`. - parameter request: URL request. - returns: Observable sequence of response data. */ @warn_unused_result(message="http://git.io/rxs.uo") public func rx_data(request: NSURLRequest) -> Observable<NSData> { return rx_response(request).map { (data, response) -> NSData in if 200 ..< 300 ~= response.statusCode { return data } else { throw RxCocoaURLError.HTTPRequestFailed(response: response, data: data) } } } /** Observable sequence of response JSON for URL request. Performing of request starts after observer is subscribed and not after invoking this method. **URL requests will be performed per subscribed observer.** Any error during fetching of the response will cause observed sequence to terminate with error. If response is not HTTP response with status code in the range of `200 ..< 300`, sequence will terminate with `(RxCocoaErrorDomain, RxCocoaError.NetworkError)`. If there is an error during JSON deserialization observable sequence will fail with that error. - parameter request: URL request. - returns: Observable sequence of response JSON. */ @warn_unused_result(message="http://git.io/rxs.uo") public func rx_JSON(request: NSURLRequest) -> Observable<AnyObject> { return rx_data(request).map { (data) -> AnyObject in do { return try NSJSONSerialization.JSONObjectWithData(data, options: []) } catch let error { throw RxCocoaURLError.DeserializationError(error: error) } } } /** Observable sequence of response JSON for GET request with `URL`. Performing of request starts after observer is subscribed and not after invoking this method. **URL requests will be performed per subscribed observer.** Any error during fetching of the response will cause observed sequence to terminate with error. If response is not HTTP response with status code in the range of `200 ..< 300`, sequence will terminate with `(RxCocoaErrorDomain, RxCocoaError.NetworkError)`. If there is an error during JSON deserialization observable sequence will fail with that error. - parameter URL: URL of `NSURLRequest` request. - returns: Observable sequence of response JSON. */ @warn_unused_result(message="http://git.io/rxs.uo") public func rx_JSON(URL: NSURL) -> Observable<AnyObject> { return rx_JSON(NSURLRequest(URL: URL)) } }
mit
4b8f6365445b97bc59da866f53f2df7d
33.1375
130
0.629196
5.175616
false
false
false
false
mvader/advent-of-code
2020/12/02.swift
1
2335
import Foundation struct Instruction { let action: String let value: Int } let directions: [Direction] = [.north, .east, .south, .west] enum Direction { case north, south, west, east } struct Waypoint { var x: (Int, Direction) var y: (Int, Direction) mutating func rotate(_ angle: Int) { let dirs = angle > 0 ? directions : directions.reversed() let xdir = dirs[(Int(dirs.firstIndex(of: x.1)!) + (abs(angle) / 90)) % dirs.count] let ydir = dirs[(Int(dirs.firstIndex(of: y.1)!) + (abs(angle) / 90)) % dirs.count] let swap = (abs(angle) / 90) % 2 != 0 let (newx, newy) = (abs(swap ? y.0 : x.0), abs(swap ? x.0 : y.0)) x = (newx, swap ? ydir : xdir) y = (newy, swap ? xdir : ydir) } mutating func move(_ dir: Direction, _ n: Int) { switch dir { case .east, .west: if dir == x.1 { x = (x.0 + n, dir) } else if x.0 < n { x = (n - x.0, x.1 == .east ? .west : .east) } else { x = (x.0 - n, x.1) } case .north, .south: if dir == y.1 { y = (y.0 + n, dir) } else if y.0 < n { y = (n - y.0, y.1 == .north ? .south : .north) } else { y = (y.0 - n, y.1) } } } } struct Ship { var x: Int var y: Int mutating func move(_ dir: Direction, _ n: Int) { switch dir { case .east: x += n case .west: x -= n case .north: y += n case .south: y -= n } } } func navigate(_ instructions: [Instruction]) -> (Int, Int) { var waypoint = Waypoint(x: (10, .east), y: (1, .north)) var ship = Ship(x: 0, y: 0) for i in instructions { switch i.action { case "N": waypoint.move(.north, i.value) case "S": waypoint.move(.south, i.value) case "E": waypoint.move(.east, i.value) case "W": waypoint.move(.west, i.value) case "L": waypoint.rotate(-i.value) case "R": waypoint.rotate(i.value) case "F": ship.move(waypoint.x.1, waypoint.x.0 * i.value) ship.move(waypoint.y.1, waypoint.y.0 * i.value) default: continue } } return (ship.x, ship.y) } let instructions = try String(contentsOfFile: "./input.txt", encoding: .utf8) .components(separatedBy: "\n") .map { s in Instruction(action: String(s.prefix(1)), value: Int(String(s.dropFirst()))!) } let (x, y) = navigate(instructions) print(abs(x) + abs(y))
mit
bfa911dacee6b512e1f5761e0c18fb37
24.107527
92
0.546895
2.847561
false
false
false
false
Faryn/CycleMaps
CycleMaps/MapViewController.swift
1
11527
// // ViewController.swift // CycleMaps // // Created by Paul Pfeiffer on 05/02/17. // Copyright © 2017 Paul Pfeiffer. All rights reserved. // import UIKit import MapKit protocol HandleMapSearch: class { func dropPinZoomIn(_ placemark: MKPlacemark) } class MapViewController: UIViewController, MKMapViewDelegate, CLLocationManagerDelegate, UISearchBarDelegate, UIPopoverPresentationControllerDelegate, SettingsViewControllerDelegate, FilesViewControllerDelegate, UIGestureRecognizerDelegate, SettingDetailViewControllerDelegate { let locationManager = CLLocationManager() var resultSearchController: UISearchController? var selectedPin: MKPlacemark? let settings = SettingsStore() var filesViewController: FilesViewController? var quickZoomStart: CGFloat? var quickZoomStartLevel: Double? var tapGestureRecognizer: UITapGestureRecognizer? var quickZoomGestureRecognizer: UILongPressGestureRecognizer? override func viewDidLoad() { super.viewDidLoad() navigationItem.largeTitleDisplayMode = .never locationManager.delegate = self locationManager.requestWhenInUseAuthorization() map.tileSource = settings.tileSource setupSearchBar() addTrackButton() tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(self.toggleBarsOnTap(_:))) tapGestureRecognizer!.delegate = self self.view.addGestureRecognizer(tapGestureRecognizer!) quickZoomGestureRecognizer = UILongPressGestureRecognizer(target: self, action: #selector(self.handleQuickZoom(_:))) quickZoomGestureRecognizer!.numberOfTapsRequired = 1 quickZoomGestureRecognizer!.minimumPressDuration = 0.1 self.view.addGestureRecognizer(quickZoomGestureRecognizer!) } func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRequireFailureOf otherGestureRecognizer: UIGestureRecognizer) -> Bool { if gestureRecognizer == self.tapGestureRecognizer && otherGestureRecognizer == quickZoomGestureRecognizer { return true } return false } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) if settings.idleTimerDisabled { UIApplication.shared.isIdleTimerDisabled = true } } func importFile() { self.performSegue(withIdentifier: Constants.Storyboard.filesSegueIdentifier, sender: self) if filesViewController != nil { filesViewController?.initiateImport() } } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) if UIApplication.shared.isIdleTimerDisabled { UIApplication.shared.isIdleTimerDisabled = false } } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) self.navigationController?.setNavigationBarHidden(false, animated: true) self.navigationController?.setToolbarHidden(false, animated: true) } func clearCache() { map.tileSourceOverlay?.clearCache() } func changedSetting(setting: String?) { switch setting! { case Constants.Settings.cacheDisabled: if let overlay = map.overlays.last as? OverlayTile { overlay.enableCache = !settings.cacheDisabled } case Constants.Settings.tileSource: map.tileSource = settings.tileSource default: return } } private func addTrackButton() { let trackButton = MKUserTrackingBarButtonItem(mapView: map) self.toolbarItems?.insert(trackButton, at: 0) } private func setupSearchBar() { if let locationSearchTable = storyboard!.instantiateViewController(withIdentifier: "LocationSearchTable") as? LocationSearchTable { resultSearchController = UISearchController(searchResultsController: locationSearchTable) resultSearchController?.searchResultsUpdater = locationSearchTable let searchBar = resultSearchController!.searchBar searchBar.delegate = self searchBar.placeholder = NSLocalizedString("SearchForPlaces", comment: "Displayed as Search String") searchBar.sizeToFit() searchBar.searchBarStyle = .minimal navigationItem.titleView = resultSearchController?.searchBar resultSearchController?.hidesNavigationBarDuringPresentation = false resultSearchController?.obscuresBackgroundDuringPresentation = true definesPresentationContext = true locationSearchTable.mapView = map locationSearchTable.handleMapSearchDelegate = self locationSearchTable.searchBar = searchBar } } internal func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) { resultSearchController?.searchResultsUpdater?.updateSearchResults(for: resultSearchController!) } func searchBarCancelButtonClicked(_ searchBar: UISearchBar) { searchBar.showsCancelButton = false if selectedPin != nil { map.removeAnnotation(selectedPin!) selectedPin = nil } } func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer { if overlay is OverlayTile { return MKTileOverlayRenderer(tileOverlay: (overlay as? MKTileOverlay)!) } if overlay is MKPolyline { let renderer = MKPolylineRenderer(overlay: overlay) renderer.strokeColor = Constants.Visual.polylineColor renderer.lineWidth = 6 return renderer } else { return MKOverlayRenderer(overlay: overlay) } } // Will be called shortly after locationmanager is instantiated // Map is initialized in following mode so we only need to disable if permission is missing func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) { if status == .denied || status == .restricted { map.userTrackingMode = .none } if status == .notDetermined { locationManager.requestWhenInUseAuthorization() } } func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) { print("Failed to find user's location: \(error.localizedDescription)") } @IBOutlet weak var map: MapView! { didSet { map.delegate = self map.setUserTrackingMode(.follow, animated: true) } } @objc func toggleBarsOnTap(_ sender: UITapGestureRecognizer) { let hidden = !(self.navigationController?.isNavigationBarHidden)! self.navigationController?.setNavigationBarHidden(hidden, animated: true) self.navigationController?.setToolbarHidden(hidden, animated: true) } @objc func handleQuickZoom(_ sender: UILongPressGestureRecognizer) { switch sender.state { case .began: self.quickZoomStart = sender.location(in: sender.view).y self.quickZoomStartLevel = map.zoomLevel case .changed: if self.quickZoomStart != nil { var newZoomLevel = quickZoomStartLevel! var distance = self.quickZoomStart! - sender.location(in: sender.view).y if distance > 1 { distance = pow(1.02, distance) } else if distance < -1 { distance = pow(0.98, distance*(-1)) } else { distance = 1 } print(distance) newZoomLevel = self.quickZoomStartLevel! * Double(distance) map.zoomLevel = newZoomLevel } default: break } } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if let identifier = segue.identifier { switch identifier { case Constants.Storyboard.settingsSegueIdentifier: if let nvc = segue.destination as? UINavigationController { if let svc = nvc.topViewController as? SettingsViewController { svc.delegate = self } } case Constants.Storyboard.filesSegueIdentifier: self.filesViewController = segue.destination as? FilesViewController filesViewController?.delegate = self case Constants.Storyboard.mapStyleSegueIdentifier: if let nvc = segue.destination as? UINavigationController { if let svc = nvc.topViewController as? SettingDetailViewController { svc.navigationItem.title = Constants.Settings.mapStyleTitle svc.delegate = self svc.generator.prepare() } } default: break } } } // MARK: - FilesViewDelegate func selectedFile(name: String, url: URL) { GPX.parse(url as URL) { if let gpx = $0 { self.map.displayGpx(name: name, gpx: gpx) self.filesViewController?.tableView.reloadData() } } } func deselectedFile(name: String) { map.removeOverlay(name: name) filesViewController?.tableView.reloadData() } func isSelected(name: String) -> Bool { return map.namedOverlays[name] != nil } func changedMapStyle() { changedSetting(setting: Constants.Settings.tileSource) } } extension MapViewController: HandleMapSearch { func dropPinZoomIn(_ placemark: MKPlacemark) { // cache the pin selectedPin = placemark // clear existing pins map.removeAnnotations(map.annotations) let annotation = MKPointAnnotation() annotation.coordinate = placemark.coordinate annotation.title = placemark.name if let userLocation = locationManager.location { let distance = userLocation.distance(from: CLLocation( latitude: annotation.coordinate.latitude, longitude: annotation.coordinate.longitude)) if Constants.Settings.useKilometers { annotation.subtitle = String(format: "%.2f km", distance*0.001) } else { annotation.subtitle = String(format: "%.2f mi", distance*0.000621371) } } map.addAnnotation(annotation) let span = MKCoordinateSpan.init(latitudeDelta: 0.05, longitudeDelta: 0.05) let region = MKCoordinateRegion.init(center: placemark.coordinate, span: span) map.setRegion(region, animated: true) } } extension GPX.Waypoint: MKAnnotation { // MARK: - MKAnnotation var coordinate: CLLocationCoordinate2D { return CLLocationCoordinate2D(latitude: latitude, longitude: longitude) } var title: String? { return name } var subtitle: String? { return info } } private extension MKPolyline { convenience init(coordinates coords: [CLLocationCoordinate2D]) { let unsafeCoordinates = UnsafeMutablePointer<CLLocationCoordinate2D>.allocate(capacity: coords.count) unsafeCoordinates.initialize(from: coords, count: coords.count) self.init(coordinates: unsafeCoordinates, count: coords.count) unsafeCoordinates.deallocate() } }
mit
dcfb7b5d3dab4f26a0ae5499901bf5bd
38.608247
115
0.653306
5.700297
false
false
false
false
KiranJasvanee/KJExpandableTableTree
Example_Static_Init_Using_Index/KJExpandableTableTree/ViewController.swift
1
8466
// // ViewController.swift // KJExpandableTableTree // // Created by KiranJasvanee on 05/12/2017. // Copyright (c) 2017 KiranJasvanee. All rights reserved. // import UIKit import KJExpandableTableTree class ViewController: UIViewController { // KJ Tree instances ------------------------- var arrayTree:[Parent] = [] var kjtreeInstance: KJTree = KJTree() // Tableview instance @IBOutlet weak var tableview: UITableView! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. kjtreeInstance = KJTree(indices: ["1.1", "2.1.1", "2.1.2.1", "2.1.3.2", "2.1.3.3", "3.1", "3.2", "3.3"] ) kjtreeInstance.isInitiallyExpanded = true tableview.dataSource = self tableview.delegate = self tableview.rowHeight = UITableView.automaticDimension tableview.estimatedRowHeight = 44 tableview.tableFooterView = UIView(frame: .zero) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } } extension ViewController: UITableViewDataSource, UITableViewDelegate { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { let total = kjtreeInstance.tableView(tableView, numberOfRowsInSection: section) return total } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let node = kjtreeInstance.cellIdentifierUsingTableView(tableView, cellForRowAt: indexPath) if node.givenIndex == "1" || node.givenIndex == "2" || node.givenIndex == "3"{ let cellIdentifier = "_dot1_TableViewCellIdentity" var cell: _dot1_TableViewCell? = tableView.dequeueReusableCell(withIdentifier: cellIdentifier) as? _dot1_TableViewCell if cell == nil { tableView.register(UINib(nibName: "_dot1_TableViewCell", bundle: nil), forCellReuseIdentifier: cellIdentifier) cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier) as? _dot1_TableViewCell } cell?.cellFillUp(indexParam: node.givenIndex) cell?.selectionStyle = .none if node.state == .open { cell?.buttonState.setImage(UIImage(named: "minus"), for: .normal) }else if node.state == .close { cell?.buttonState.setImage(UIImage(named: "plus"), for: .normal) }else{ cell?.buttonState.setImage(nil, for: .normal) } return cell! } if node.givenIndex == "1.1" { let cellIdentifier = "index_1_1_TableViewCellIdentity" var cell: index_1_1_TableViewCell? = tableView.dequeueReusableCell(withIdentifier: cellIdentifier) as? index_1_1_TableViewCell if cell == nil { tableView.register(UINib(nibName: "index_1-1_TableViewCell", bundle: nil), forCellReuseIdentifier: cellIdentifier) cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier) as? index_1_1_TableViewCell } cell?.cellFillUp(indexParam: node.givenIndex) cell?.selectionStyle = .none return cell! } if node.givenIndex == "2.1" || node.givenIndex == "2.1.2" || node.givenIndex == "2.1.3"{ let cellIdentifier = "index_2_1_TableViewCellIdentity" var cell: index_2_1_TableViewCell? = tableView.dequeueReusableCell(withIdentifier: cellIdentifier) as? index_2_1_TableViewCell if cell == nil { tableView.register(UINib(nibName: "index_2_1_TableViewCell", bundle: nil), forCellReuseIdentifier: cellIdentifier) cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier) as? index_2_1_TableViewCell } cell?.selectionStyle = .none if node.givenIndex == "2.1" { cell?.imageviewBackground.image = UIImage(named: "expand_me") }else if node.givenIndex == "2.1.2" { cell?.imageviewBackground.image = UIImage(named: "more_expansion") }else if node.givenIndex == "2.1.3" { cell?.imageviewBackground.image = UIImage(named: "more_expansion_2") } if node.state == .open { cell?.buttonState.setImage(UIImage(named: "minus"), for: .normal) }else if node.state == .close { cell?.buttonState.setImage(UIImage(named: "plus"), for: .normal) }else{ cell?.buttonState.setImage(nil, for: .normal) } return cell! } if node.givenIndex == "2.1.1" { let cellIdentifier = "stepperTableViewCell" var cell: stepperTableViewCell? = tableView.dequeueReusableCell(withIdentifier: cellIdentifier) as? stepperTableViewCell if cell == nil { tableView.register(UINib(nibName: "stepperTableViewCell", bundle: nil), forCellReuseIdentifier: cellIdentifier) cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier) as? stepperTableViewCell } cell?.selectionStyle = .none return cell! } if node.givenIndex == "2.1.2.1" { let cellIdentifier = "segmentTableViewCell" var cell: segmentTableViewCell? = tableView.dequeueReusableCell(withIdentifier: cellIdentifier) as? segmentTableViewCell if cell == nil { tableView.register(UINib(nibName: "segmentTableViewCell", bundle: nil), forCellReuseIdentifier: cellIdentifier) cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier) as? segmentTableViewCell } cell?.selectionStyle = .none return cell! } if node.givenIndex == "2.1.3.2" { let cellIdentifier = "sliderTableViewCell" var cell: sliderTableViewCell? = tableView.dequeueReusableCell(withIdentifier: cellIdentifier) as? sliderTableViewCell if cell == nil { tableView.register(UINib(nibName: "sliderTableViewCell", bundle: nil), forCellReuseIdentifier: cellIdentifier) cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier) as? sliderTableViewCell } cell?.selectionStyle = .none return cell! } if node.givenIndex == "2.1.3.3" { let cellIdentifier = "progressbarTableViewCell" var cell: progressbarTableViewCell? = tableView.dequeueReusableCell(withIdentifier: cellIdentifier) as? progressbarTableViewCell if cell == nil { tableView.register(UINib(nibName: "progressbarTableViewCell", bundle: nil), forCellReuseIdentifier: cellIdentifier) cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier) as? progressbarTableViewCell } cell?.selectionStyle = .none return cell! } let cellIdentifier = "index_3_Leaf_TableViewCell" var cell: index_3_Leaf_TableViewCell? = tableView.dequeueReusableCell(withIdentifier: cellIdentifier) as? index_3_Leaf_TableViewCell if cell == nil { tableView.register(UINib(nibName: "index_3_Leaf_TableViewCell", bundle: nil), forCellReuseIdentifier: cellIdentifier) cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier) as? index_3_Leaf_TableViewCell } cell?.selectionStyle = .none cell?.labelIndex.text = "Index: \(node.givenIndex)" return cell! } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let node = kjtreeInstance.tableView(tableView, didSelectRowAt: indexPath) print(node.index) // if you've added any identifier or used indexing format print(node.givenIndex) } }
mit
cdec7c3d35684d1918b96c42ee1f2e70
41.757576
140
0.602173
5.115408
false
false
false
false
wordpress-mobile/WordPress-iOS
WordPress/Classes/ViewRelated/Jetpack/Branding/Fullscreen Overlay/JetpackFullscreenOverlayViewModel.swift
1
1084
import Foundation typealias JetpackOverlayDismissCallback = () -> Void /// Protocol used to configure `JetpackFullscreenOverlayViewController` protocol JetpackFullscreenOverlayViewModel { var title: String { get } var subtitle: String { get } var animationLtr: String { get } var animationRtl: String { get } var footnote: String? { get } var shouldShowLearnMoreButton: Bool { get } var switchButtonText: String { get } var continueButtonText: String? { get } var shouldShowCloseButton: Bool { get } var analyticsSource: String { get } var onDismiss: JetpackOverlayDismissCallback? { get } func trackOverlayDisplayed() func trackLearnMoreTapped() func trackSwitchButtonTapped() func trackCloseButtonTapped() func trackContinueButtonTapped() } extension JetpackFullscreenOverlayViewModel { var learnMoreButtonIsHidden: Bool { !shouldShowLearnMoreButton } var footnoteIsHidden: Bool { footnote == nil } var continueButtonIsHidden: Bool { continueButtonText == nil } }
gpl-2.0
2199a87d3e2ebd111b2efebcdc2a8b89
27.526316
71
0.712177
4.860987
false
false
false
false
jfosterdavis/FlashcardHero
FlashcardHero/GameDirectory.swift
1
2360
// // GameDirectory.swift // FlashcardHero // // Created by Jacob Foster Davis on 11/15/16. // Copyright © 2016 Zero Mu, LLC. All rights reserved. // import Foundation import UIKit struct GameDirectory { static let GameTrueFalse = Game(id: 0, name: "True or False", description: "Decide if the given text and image correspond to the given term.", iconImage: #imageLiteral(resourceName: "TrueFalseGameIcon"), storyboardId: "GameTrueFalse", isAvailable: true) static let allGames = [GameTrueFalse.id : GameTrueFalse] static let activeGames = [GameTrueFalse] static let activeGameVariants = [GameVariant(game: GameTrueFalse, gameProtocol: GameVariantProtocols.MaxPoints, description: "Simple Goal", icon: #imageLiteral(resourceName: "GemRed")), GameVariant(game: GameTrueFalse, gameProtocol: GameVariantProtocols.PerfectGame, description: "Limited Lives", icon: #imageLiteral(resourceName: "GemBlue"))] } struct GameVariant { let game: Game let gameProtocol: String let description: String let icon: UIImage init(game: Game, gameProtocol: String, description: String, icon: UIImage) { guard GameVariantProtocols.protocols.contains(gameProtocol) else { fatalError("couldn't set a GameVariant") } self.game = game self.gameProtocol = gameProtocol self.description = description self.icon = icon } } //A Game struct is an object that tracks a Game that may or may not be available to the player. These are placed in the GameDirectory. struct Game { let id: Int let name: String let description: String? let storyboardId: String let isAvailable: Bool var icon: UIImage? init(id: Int, name: String, description: String? = nil, iconImage: UIImage? = nil, storyboardId: String, isAvailable: Bool) { self.id = id self.name = name if let description = description { self.description = description } else { self.description = nil } if let image = iconImage { self.icon = image } else { self.icon = nil } self.storyboardId = storyboardId self.isAvailable = isAvailable } }
apache-2.0
98d700e6731e08d7f99499dc224ab835
30.878378
257
0.639678
4.519157
false
false
false
false
Aioria1314/WeiBo
WeiBo/WeiBo/Classes/Views/ZXCComposeToolBar.swift
1
2735
// // ZXCComposeToolBar.swift // WeiBo // // Created by Aioria on 2017/4/5. // Copyright © 2017年 Aioria. All rights reserved. // import UIKit enum ZXCToolBarButtonType: Int { case picture = 0 case mention = 1 case trend = 2 case emoticon = 3 case add = 4 } class ZXCComposeToolBar: UIStackView { var buttonClickClosuer: ((ZXCToolBarButtonType) -> ())? var btnEmoticon: UIButton? override init(frame: CGRect) { super.init(frame: frame) setupUI() } required init(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } fileprivate func setupUI () { self.axis = .horizontal self.distribution = .fillEqually creatChildButton(imgName: "compose_camerabutton_background", type: .picture) creatChildButton(imgName: "compose_mentionbutton_background", type: .mention) creatChildButton(imgName: "compose_trendbutton_background", type: .trend) btnEmoticon = creatChildButton(imgName: "compose_emoticonbutton_background", type: .emoticon) creatChildButton(imgName: "compose_add_background", type: .add) } @discardableResult fileprivate func creatChildButton(imgName: String, type: ZXCToolBarButtonType) -> UIButton { let btn = UIButton() btn.setImage(UIImage(named: imgName), for: .normal) btn.setImage(UIImage(named: imgName + "_highlighted"), for: .highlighted) btn.setBackgroundImage(UIImage(named: "compose_toolbar_background"), for: .normal) btn.adjustsImageWhenHighlighted = false btn.tag = type.rawValue btn.addTarget(self, action: #selector(btnAction(btn:)), for: .touchUpInside) addArrangedSubview(btn) return btn } @objc fileprivate func btnAction(btn: UIButton) { let type = btn.tag buttonClickClosuer?(ZXCToolBarButtonType(rawValue: type)!) } func switchEmoticon(isEmoticon: Bool) { if isEmoticon { btnEmoticon!.setImage(UIImage(named: "compose_keyboardbutton_background"), for: .normal) btnEmoticon!.setImage(UIImage(named: "compose_keyboardbutton_background_highlighted"), for: .highlighted) } else { btnEmoticon!.setImage(UIImage(named: "compose_emoticonbutton_background"), for: .normal) btnEmoticon!.setImage(UIImage(named: "compose_emoticonbutton_background_highlighted"), for: .highlighted) } } }
mit
22b3d97c4d99b462c92ad09f41d3e8c2
25.269231
117
0.601757
4.678082
false
false
false
false
stuartbreckenridge/SelfSizingCells
XMLExample/XMLParser.swift
1
2956
// // XMLParser.swift // XMLExample // // Created by Stuart Breckenridge on 12/8/14. // Copyright (c) 2014 Stuart Breckenridge. All rights reserved. // import Foundation protocol XMLParserNotifications { func didFinishParsingApps(apps:[App]) } class XMLParser: NSObject, NSXMLParserDelegate { // Constants let xmlURLEndpoint:NSURL = NSURL(string:"http://ax.itunes.apple.com/WebObjects/MZStoreServices.woa/ws/RSS/toppaidapplications/limit=25/xml")! //Variables var aName = String() var aSummary = String() var aPrice = String() var aRights = String() var currentElement = String() var appArray = [App]() var delegate: XMLParserNotifications? // MARK: Parse XML func parseXML() { var xmlParser:NSXMLParser = NSXMLParser(contentsOfURL: xmlURLEndpoint)! xmlParser.delegate = self xmlParser.shouldResolveExternalEntities = false xmlParser.parse() } // MARK: NSXMLParserDelegate methods func parser(parser: NSXMLParser!, didStartElement elementName: String!, namespaceURI: String!, qualifiedName qName: String!, attributes attributeDict: NSDictionary!) { currentElement = elementName // Start of entry. Reset title/rights if (elementName == "entry") { aRights = "" aName = "" aSummary = "" aPrice = "" } } func parser(parser: NSXMLParser!, foundCharacters string: String!) { // Append characters found from current element if (currentElement == "title") { aName += string } if (currentElement == "summary") { aSummary += string } if (currentElement == "rights") { aRights += string } if (currentElement == "im:price") { aPrice += string } } func parser(parser: NSXMLParser!, didEndElement elementName: String!, namespaceURI: String!, qualifiedName qName: String!) { // Finished parsing entry...create Song struct if (elementName == "entry") { var anApp = App(appName: aName, appSummary: aSummary, appPrice: aPrice, appRights: aRights) appArray.append(anApp) } currentElement = "" } func parserDidEndDocument(parser: NSXMLParser!) { dispatch_async(dispatch_get_main_queue(), { self.delegate?.didFinishParsingApps(self.appArray) () }) } } /** App is a struct of parsed XML data. :param: appName - parsed name of the app. :param: appSummary - parsed summary of the app. :param: appPrice - parsed price of the app. :param: appRights - parsed rights of the app. */ struct App { var appName = String() var appSummary = String() var appPrice = String() var appRights = String() }
mit
66e84bf7dbfb400ab5ced5a157816054
24.929825
169
0.595737
4.633229
false
false
false
false
ReduxKit/ReduxKit
ReduxKitTests/FluxStandardActionSpec.swift
1
1260
// // FluxStandardActionSpec.swift // ReduxKit // // Created by Aleksander Herforth Rendtslev on 06/11/15. // Copyright © 2015 Kare Media. All rights reserved. // import Quick import Nimble @testable import ReduxKit class FluxStandardActionSpec: QuickSpec { override func spec() { describe("FluxStandardAction") { // swiftlint:disable line_length it("should succesfully retrieve payload from FluxStandardAction types") { // Arrange let incrementAction = IncrementAction() as FluxStandardAction let pushAction = PushAction(payload: nil) as FluxStandardAction let updateTextFieldAction = UpdateTextFieldAction(payload: nil) as FluxStandardAction // Act let incrementPayload = incrementAction.payload let pushPayload = pushAction.payload let updateTextFieldPayload = updateTextFieldAction.payload // Assert expect(incrementPayload is Int).to(beTruthy()) expect(pushPayload is PushAction.Payload).to(beTruthy()) expect(updateTextFieldPayload is UpdateTextFieldAction.Payload).to(beTruthy()) } } } }
mit
47fc79bad73ddd0098a0824ce89136d6
31.282051
101
0.636219
5.076613
false
false
false
false
SusanDoggie/Doggie
Sources/DoggieGraphics/ColorModel/ColorBlendMode.swift
1
3986
// // ColorBlendMode.swift // // The MIT License // Copyright (c) 2015 - 2022 Susan Cheng. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // @frozen public struct ColorBlendMode: Hashable { @usableFromInline var rawValue: ColorBlendKernel.Type @inlinable init(rawValue: ColorBlendKernel.Type) { self.rawValue = rawValue } } extension ColorBlendMode { @inlinable public var identifier: ObjectIdentifier { return ObjectIdentifier(rawValue) } @inlinable public static func == (lhs: ColorBlendMode, rhs: ColorBlendMode) -> Bool { return lhs.identifier == rhs.identifier } @inlinable public func hash(into hasher: inout Hasher) { hasher.combine(identifier) } } extension ColorBlendMode { @inlinable @inline(__always) public static var `default`: ColorBlendMode { return .normal } } extension ColorBlendMode { /// B(cb, cs) = cs public static let normal = ColorBlendMode(rawValue: NormalBlendKernel.self) /// B(cb, cs) = cb * cs public static let multiply = ColorBlendMode(rawValue: MultiplyBlendKernel.self) /// B(cb, cs) = cb + cs - cb * cs public static let screen = ColorBlendMode(rawValue: ScreenBlendKernel.self) /// B(cb, cs) = cb < 0.5 ? 2 * cb * cs : 1 - 2 * (1 - cb) * (1 - cs) public static let overlay = ColorBlendMode(rawValue: OverlayBlendKernel.self) /// B(cb, cs) = min(cb, cs) public static let darken = ColorBlendMode(rawValue: DarkenBlendKernel.self) /// B(cb, cs) = max(cb, cs) public static let lighten = ColorBlendMode(rawValue: LightenBlendKernel.self) /// B(cb, cs) = cs < 1 ? min(1, cb / (1 - cs)) : 1 public static let colorDodge = ColorBlendMode(rawValue: ColorDodgeBlendKernel.self) /// B(cb, cs) = cs > 0 ? 1 - min(1, (1 - cb) / cs) : 0 public static let colorBurn = ColorBlendMode(rawValue: ColorBurnBlendKernel.self) /// B(cb, cs) = cs < 0.5 ? cb - (1 - 2 * cs) * cb * (1 - cb) : cb + (2 * cs - 1) * (D(cb) - cb) /// where D(x) = x < 0.25 ? ((16 * x - 12) * x + 4) * x : sqrt(x) public static let softLight = ColorBlendMode(rawValue: SoftLightBlendKernel.self) /// B(cb, cs) = Overlay(cs, cb) public static let hardLight = ColorBlendMode(rawValue: HardLightBlendKernel.self) /// B(cb, cs) = abs(cb - cs) public static let difference = ColorBlendMode(rawValue: DifferenceBlendKernel.self) /// B(cb, cs) = cb + cs - 2 * cb * cs public static let exclusion = ColorBlendMode(rawValue: ExclusionBlendKernel.self) /// B(cb, cs) = max(0, 1 - ((1 - cb) + (1 - cs))) public static let plusDarker = ColorBlendMode(rawValue: PlusDarkerBlendKernel.self) /// B(cb, cs) = min(1, cb + cs) public static let plusLighter = ColorBlendMode(rawValue: PlusLighterBlendKernel.self) }
mit
852be0f83fe54b57d9a71a5eac32a3cf
35.568807
99
0.658555
3.907843
false
false
false
false
skedgo/tripkit-ios
Sources/TripKit/model/TKTripPattern.swift
1
2184
// // TKTripPattern.swift // TripKit // // Created by Adrian Schoenig on 14/09/2016. // Copyright © 2016 SkedGo Pty Ltd. All rights reserved. // import Foundation import CoreLocation /// Simple dictionary representing a segment that can be /// used as input to `TKWaypointRouter`. public typealias TKSegmentPattern = TKWaypointRouter.Segment public enum TKTripPattern { /// - Returns: The trip pattern for a trip public static func pattern(for trip: Trip) -> [TKSegmentPattern] { return trip.segments.compactMap(\.pattern) } public static func od(for pattern: [TKSegmentPattern]) -> (o: CLLocationCoordinate2D, d: CLLocationCoordinate2D)? { if case .coordinate(let start) = pattern.first?.start, case .coordinate(let end) = pattern.last?.end { return (start, end) } else { return nil } } public static func modeLabels(for trip: Trip) -> [String] { return trip.segments.compactMap { segment in guard !segment.isStationary else { return nil } if let info = segment.modeInfo { return info.alt } else if let mode = segment.modeIdentifier { return TKRegionManager.shared.title(forModeIdentifier: mode) } else { return nil } } } public static func modeLabels(for pattern: [TKSegmentPattern]) -> [String] { return pattern.compactMap { pattern in if let mode = pattern.modes.first { return TKRegionManager.shared.title(forModeIdentifier: mode) } else { return nil } } } } extension TKSegment { fileprivate var pattern: TKSegmentPattern? { guard !isStationary else { return nil } guard let mode = modeIdentifier else { assertionFailure("Segment is missing mode: \(self)") return nil } guard let start = start, let end = end else { assertionFailure("Non-stationary segment without start & stop") return nil } // Previously also had: // pattern["preferredPublic"] = isPublicTransport ? modeInfo?.identifier : nil return .init( start: .coordinate(start.coordinate), end: .coordinate(end.coordinate), modes: [mode] ) } }
apache-2.0
61b68dddba2d53f796eb75cbc2ce7634
24.988095
117
0.657352
4.263672
false
false
false
false
dfortuna/theCraic3
theCraic3/Main/New Event/DeleteEvent.swift
1
6021
// // DeleteEvent.swift // The Craic // // Created by Denis Fortuna on 24/7/17. // Copyright © 2017 Denis. All rights reserved. // import Foundation import Firebase import FirebaseStorage protocol NewEventServicesProtocol: class { func handleStatusDelete(sender: DeleteEvent) func handleStatusUpdate(sender: UpdateEvent) } class DeleteEvent: NSObject { var eventID = String() var eventTags = [String: String]() var picturesFolderName = String() var eventPictures = [String: String]() var eventAttendees = [String]() var eventName = String() var eventCategory = String() var userID = String() var userName = String() let refUsers = Database.database().reference().child("users") let refEvents = Database.database().reference().child("events") let refTags = Database.database().reference().child("tags") let refStorage = Storage.storage().reference() weak var delegate: NewEventServicesProtocol? func deleteEventTrees(event: Event, userName: String, userID: String) { self.eventID = event.eventID self.eventTags = event.eventTags self.picturesFolderName = event.picturesFolderName self.eventPictures = event.eventPictures self.eventAttendees = event.eventAttendees self.eventName = event.eventName self.eventCategory = event.eventCategory self.userID = userID self.userName = userName insertMessageAttendeesMyCalendar() deleteEventFromMyEvents() deleteEventFromMyAgenda() deleteEventTagsFromTagTree() deleteEventPhotosFromStorage() deleteEventFromAttendeesMyAgenda() deleteFromFollowersFeed() self.delegate?.handleStatusDelete(sender: self) } func deleteFromFollowersFeed() { var followersID = [String]() refEvents.child(eventID).child("Posted to").observe(.childAdded, with: { (snapshot) in if let _ = snapshot.value as? [String: AnyObject] { let followerID = snapshot.key followersID.append(followerID) self.refUsers.child(followerID).child("Feed").child(self.eventID).removeValue() self.refEvents.child(self.eventID).child("Posted to").child(followerID).removeAllObservers() self.deletEventFromEventTree() } }) { (error) in print("Error deleting from user's Feed \(error)") } } func deleteEventFromMyEvents() { refUsers.child(userID).child("myEvents").child(eventID).removeValue(completionBlock: { (error, reference) in if error != nil { print("Error deleting event from myEvents") } }) } func deleteEventFromMyAgenda() { refUsers.child(userID).child("Agenda").child(eventID).removeValue(completionBlock: { (error, reference) in if error != nil { print("Error deleting event from Agenda") } }) } func deleteEventTagsFromTagTree() { for (_, tag) in eventTags { refTags.child(tag).child("Events").child(eventID).removeValue(completionBlock: { (error, reference) in if error != nil { print("Error deleting event from Agenda") } self.refTags.child(tag).observeSingleEvent(of: .value, with: { (snapshot) in if (!snapshot.hasChild("Events")) && (!snapshot.hasChild("Venues")) { self.refTags.child(tag).removeValue() } }) }) } } func deleteEventPhotosFromStorage() { for (picID, _) in eventPictures { let pic = "\(picID).png" refStorage.child(picturesFolderName).child(pic).delete { (error) in if error != nil { print("Error deleting Firebase Folder \(error) :/") } } } } func deleteEventFromAttendeesMyAgenda() { for ateendee in eventAttendees { refUsers.child(ateendee).child("Agenda").child(eventID).removeValue(completionBlock: { (error, reference) in if error != nil { print("Error deleting event from Agenda Attendee") } }) } } func deletEventFromEventTree() { refEvents.child(eventID).removeValue { (error, reference) in if error != nil { print("Error deleting event") } } } func insertMessageAttendeesMyCalendar() { refEvents.child(eventID).child("Attendees").child("Attendees COD").observeSingleEvent(of: .value, with: { (snapshot) in if let attendees = snapshot.value as? [String : String] { for (attendeeID, _) in attendees { if attendeeID != self.userID { let dateNow = Date() let msgValues = ["MessageType" : "Deletion", "SenderID": self.userID, "SenderName": self.userName, "SenderType": "user", "EventID": self.eventID, "EventName": self.eventName, "EventType": self.eventCategory, "TimestampSent": "\(dateNow)", "TitleMsg": "\(self.userName) canceled event \(self.eventName)", "SubTitleMsg": "", "TextMsg": "", "ReadMsg": "false"] self.refUsers.child(attendeeID).child("Messages").childByAutoId().setValue(msgValues) } } } }) } }
apache-2.0
11608a556033b71e54c24c1c86840fcb
37.101266
127
0.543688
4.991708
false
false
false
false
Otbivnoe/Framezilla
Example/FramezillaExample/ViewController.swift
1
2267
// // ViewController.swift // FramezillaExample // // Created by Nikita Ermolenko on 13/05/2017. // Copyright © 2017 Nikita Ermolenko. All rights reserved. // import UIKit import Framezilla class ViewController: UIViewController { let container = UIView() let content1 = UIView() let content2 = UIView() let content3 = UIView() let content4 = UIView() let label1 = UILabel() let label2 = UILabel() let label3 = UILabel() override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = .white container.backgroundColor = .yellow content1.backgroundColor = .red content2.backgroundColor = .black content3.backgroundColor = .green content4.backgroundColor = .gray label1.backgroundColor = .red label2.backgroundColor = .green label3.backgroundColor = .gray label1.numberOfLines = 0 label2.numberOfLines = 0 label3.numberOfLines = 0 label1.text = "Helloe Helloe Helloe Helloe Helloe Helloe Helloe Helloe Helloe Helloe Helloe" label2.text = "Helloe Helloe Helloe Helloe Helloe" label3.text = "Helloe" view.addSubview(container) } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() [content1, label1, label2, label3].configure(container: container, relation: .horizontal(left: 20, right: 20)) { content1.configureFrame { maker in maker.top(inset: 10) maker.size(width: 100, height: 60) maker.centerX() } label1.configureFrame { maker in maker.left().right().top(to: content1.nui_bottom, inset: 10) maker.heightToFit() } label2.configureFrame { maker in maker.left().right().top(to: label1.nui_bottom, inset: 10) maker.heightToFit() } label3.configureFrame { maker in maker.left().right().top(to: label2.nui_bottom, inset: 20) maker.heightToFit() } } container.configureFrame { maker in maker.centerX() maker.bottom(inset: 20) } } }
mit
b0e4cefb88284425987296c51f9dfa6c
25.97619
120
0.591792
4.451866
false
true
false
false
to4iki/conference-app-2017-ios
conference-app-2017/presentation/viewController/SessionViewController.swift
1
3743
import UIKit import Kingfisher import MarkdownView import OctavKit import Then final class SessionViewController: UIViewController { @IBOutlet fileprivate weak var contentView: UIView! @IBOutlet fileprivate weak var indicatorView: UIActivityIndicatorView! @IBOutlet fileprivate weak var titleLabel: UILabel! @IBOutlet fileprivate weak var startToEndLabel: UILabel! @IBOutlet fileprivate weak var tagCollectionView: UICollectionView! @IBOutlet fileprivate weak var avatarImageView: CircleImageView! @IBOutlet fileprivate weak var nicknameLabel: UILabel! @IBOutlet fileprivate weak var abstractMarkdownView: MarkdownView! @IBOutlet fileprivate weak var abstractMarkdownViewHeight: NSLayoutConstraint! fileprivate var session: Session! override func viewDidLoad() { super.viewDidLoad() tagCollectionView.dataSource = self tagCollectionView.delegate = self setupLayout(session: session) } } extension SessionViewController { static func instantiate(session: Session) -> SessionViewController { return Storyboard.session.instantiate(type: SessionViewController.self).then { $0.session = session } } } extension SessionViewController { fileprivate func setupLayout(session: Session) { setNoTitleBackButton() hideLayout() titleLabel.text = session.title startToEndLabel.text = session.startsOn.string(format: .custom("yyyy/MM/dd HH:mm")) avatarImageView.kf.setImage(with: session.speaker.avatarURL.secure) nicknameLabel.text = session.speaker.nickname abstractMarkdownView.load(markdown: session.abstract) abstractMarkdownView.isScrollEnabled = false abstractMarkdownView.onRendered = { [weak self] (height: CGFloat) in guard let strongSelf = self else { return } strongSelf.showLayout() strongSelf.abstractMarkdownViewHeight.constant = height strongSelf.view.setNeedsLayout() } abstractMarkdownView.onTouchLink = { [weak self] (request: URLRequest) -> Bool in guard let url = request.url, let scheme = url.scheme else { return false } switch scheme { case "file": return true case "http", "https": self?.presentSafariViewController(url: url, animated: true) return false default: return false } } } private func showLayout() { indicatorView.stopAnimating() indicatorView.isHidden = true contentView.isHidden = false } private func hideLayout() { indicatorView.startAnimating() indicatorView.isHidden = false contentView.isHidden = true } } // MARK: - UICollectionViewDataSource extension SessionViewController: UICollectionViewDataSource { func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return session.tags.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { return collectionView.dequeueReusableCell(with: TagCollectionViewCell.self, for: indexPath).then { $0.setup(name: session.tags[indexPath.row].rawValue) } } } // MARK: - UICollectionViewDelegateFlowLayout extension SessionViewController: UICollectionViewDelegateFlowLayout { func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { return TagCollectionViewCell.cellSize(by: session.tags[indexPath.row].rawValue) } }
apache-2.0
ae1b7f999374f42e15de206b81b6f4ae
37.587629
160
0.701576
5.480234
false
false
false
false
cdebortoli/JsonManagedObject-Swift
JsonManagedObject/JsonManagedObject/JsonManagedObject.swift
1
3820
// // JsonManagedObject.swift // JsonManagedObject-Swift // // Created by christophe on 08/06/14. // Copyright (c) 2014 cdebortoli. All rights reserved. // import Foundation public let jsonManagedObjectSharedInstance = JsonManagedObject() public class JsonManagedObject { public let dateFormatter = NSDateFormatter() internal lazy var configDatasource = JMOConfigDatasource() // Data from the template file public init() { dateFormatter.dateFormat = JMOConfig.dateFormat } // Analyze an array of Dictionary public func analyzeJsonArray(jsonArray:[AnyObject], forClass objectClass:AnyClass) -> [AnyObject] { var resultArray = [AnyObject]() for jsonArrayOccurence:AnyObject in jsonArray { if let jsonDict = jsonArrayOccurence as? [String: AnyObject] { if let objectFromJson : AnyObject = analyzeJsonDictionary(jsonDict, forClass: objectClass) { resultArray.append(objectFromJson) } } } return resultArray } // Analyze a dictionary public func analyzeJsonDictionary(jsonDictionary:[String: AnyObject], forClass objectClass:AnyClass) -> AnyObject? { // 1 - Find the config object for the specified class if let configObject = configDatasource[NSStringFromClass(objectClass)] { // 2 - Json Dictionary var jsonFormatedDictionary = jsonDictionary // Envelope if JMOConfig.jsonWithEnvelope { if let dictUnwrapped = jsonDictionary[configObject.classInfo.jsonKey]! as? [String: AnyObject] { jsonFormatedDictionary = dictUnwrapped } } // 3a - NSManagedObject Parse & init if class_getSuperclass(objectClass) is NSManagedObject.Type { if JMOConfig.managedObjectContext == nil { return nil } var managedObject:NSManagedObject if JMOConfig.temporaryNSManagedObjectInstance == false { managedObject = NSEntityDescription.insertNewObjectForEntityForName(NSStringFromClass(objectClass), inManagedObjectContext: JMOConfig.managedObjectContext!) as NSManagedObject for parameter in configObject.parameters { managedObject.setProperty(parameter, fromJson: jsonFormatedDictionary) } return managedObject } else { let entityDescriptionOptional = NSEntityDescription.entityForName(NSStringFromClass(objectClass), inManagedObjectContext: JMOConfig.managedObjectContext!) if let entityDescription = entityDescriptionOptional { managedObject = NSManagedObject(entity: entityDescription, insertIntoManagedObjectContext: nil) for parameter in configObject.parameters { managedObject.setProperty(parameter, fromJson: jsonFormatedDictionary) } return managedObject } } // 3b - CustomObject Parse & init } else if class_getSuperclass(objectClass) is JMOWrapper.Type { var classType: NSObject.Type = objectClass as NSObject.Type var cobject : AnyObject! = classType() (cobject as JMOWrapper).childrenClassReference = objectClass for parameter in configObject.parameters { (cobject as JMOWrapper).setParameter(parameter, fromJson: jsonFormatedDictionary) } return cobject } } return nil } }
mit
745d1d2b554c7ab60d3ed1de5a46e7ed
43.941176
195
0.610733
6.151369
false
true
false
false
Dormmate/DORMLibrary
DORM/Classes/iOSDevCenters+GIF.swift
1
4739
// // iOSDevCenters+GIF.swift // DORM // // Created by Dormmate on 2017. 5. 4.. // Copyright © 2017 Dormmate. All rights reserved. // import UIKit import ImageIO /* 사용법 : let launchGif = UIImage.gifImageWithName(name: "launchSplash") imageView = UIImageView(image: launchGif) imageView.frame = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.size.width, height: UIScreen.main.bounds.size.height) 사용 후 반드시 imageView 를 nil 로 해주고 removeAllSubviews */ extension UIImage { public class func gifImageWithData(data: NSData) -> UIImage? { guard let source = CGImageSourceCreateWithData(data, nil) else { print("image doesn't exist") return nil } return UIImage.animatedImageWithSource(source: source) } public class func gifImageWithName(name: String) -> UIImage? { guard let bundleURL = Bundle.main .url(forResource: name, withExtension: "gif") else { print("SwiftGif: This image named \"\(name)\" does not exist") return nil } guard let imageData = NSData(contentsOf: bundleURL) else { print("SwiftGif: Cannot turn image named \"\(name)\" into NSData") return nil } return gifImageWithData(data: imageData) } class func delayForImageAtIndex(index: Int, source: CGImageSource!) -> Double { var delay = 0.0 let cfProperties = CGImageSourceCopyPropertiesAtIndex(source, index, nil) let gifProperties: CFDictionary = unsafeBitCast( CFDictionaryGetValue(cfProperties, Unmanaged.passUnretained(kCGImagePropertyGIFDictionary).toOpaque()), to: CFDictionary.self) var delayObject: AnyObject = unsafeBitCast( CFDictionaryGetValue(gifProperties, Unmanaged.passUnretained(kCGImagePropertyGIFUnclampedDelayTime).toOpaque()), to: AnyObject.self) if delayObject.doubleValue == 0 { delayObject = unsafeBitCast(CFDictionaryGetValue(gifProperties, Unmanaged.passUnretained(kCGImagePropertyGIFDelayTime).toOpaque()), to: AnyObject.self) } delay = delayObject as! Double return delay } class func gcdForPair(a: Int?, _ b: Int?) -> Int { var a = a var b = b if b == nil || a == nil { if b != nil { return b! } else if a != nil { return a! } else { return 0 } } if a! < b! { let c = a a = b b = c } var rest: Int while true { rest = a! % b! if rest == 0 { return b! } else { a = b b = rest } } } class func gcdForArray(array: Array<Int>) -> Int { if array.isEmpty { return 1 } var gcd = array[0] for val in array { gcd = UIImage.gcdForPair(a:val, gcd) } return gcd } class func animatedImageWithSource(source: CGImageSource) -> UIImage? { let count = CGImageSourceGetCount(source) var images = [CGImage]() var delays = [Int]() for i in 0..<count { if let image = CGImageSourceCreateImageAtIndex(source, i, nil) { images.append(image) } let delaySeconds = UIImage.delayForImageAtIndex(index: Int(i), source: source) delays.append(Int(delaySeconds * 1000.0)) // Seconds to ms } let duration: Int = { var sum = 0 for val: Int in delays { sum += val } return sum }() let gcd = gcdForArray(array: delays) var frames = [UIImage]() var frame: UIImage var frameCount: Int for i in 0..<count { frame = UIImage(cgImage: images[Int(i)]) frameCount = Int(delays[Int(i)] / gcd) for _ in 0..<frameCount { frames.append(frame) } } let animation = UIImage.animatedImage(with: frames, duration: Double(duration) / 1000.0) return animation } }
mit
9e8d2af8b7c8b6496627d08ef906b5c7
28.4375
148
0.498089
5.119565
false
false
false
false
PANDA-Guide/PandaGuideApp
PandaGuide/AccountViewController.swift
1
7447
// // AccountViewController.swift // PandaGuide // // Created by Pierre Dulac on 27/05/2017. // Copyright © 2017 ESTHESIX. All rights reserved. // import UIKit import MessageUI import Cartography import PKHUD class AccountViewController: UIViewController { private let profilePictureImageView = UIImageView() private let userEmailAddressLabel = UILabel() private let contactByPhoneButton = FlatButton() private let contactByEmailButton = FlatButton() private let logoutButton = FlatButton() override func viewDidLoad() { super.viewDidLoad() title = NSLocalizedString("Mon Compte", comment: "") let arrowRect = CGRect(x: 0, y: 0, width: 20, height: 20) navigationItem.rightBarButtonItem = UIBarButtonItem(image: UIImage.imageWithBezier(UIBezierPath.forwardArrow(arrowRect), color: UIColor.black, inRect: arrowRect), style: .plain, target: self, action: #selector(self.handleBackToCameraButtonTapped)) navigationItem.rightBarButtonItem?.accessibilityHint = NSLocalizedString("Retour caméra", comment: "") view.backgroundColor = UIColor.brandExtraLightGray setupViewHierachy() view.setNeedsUpdateConstraints() loadUserInfos() } private func setupViewHierachy() { profilePictureImageView.translatesAutoresizingMaskIntoConstraints = false profilePictureImageView.image = #imageLiteral(resourceName: "unknown") profilePictureImageView.contentMode = .scaleAspectFill profilePictureImageView.layer.masksToBounds = true profilePictureImageView.layer.borderColor = UIColor.white.cgColor profilePictureImageView.layer.borderWidth = 3.0 view.addSubview(profilePictureImageView) userEmailAddressLabel.translatesAutoresizingMaskIntoConstraints = false userEmailAddressLabel.textAlignment = .center userEmailAddressLabel.textColor = UIColor.gray userEmailAddressLabel.font = UIFont.brandFont(weight: .Bold, forSize: UIFont.labelFontSize) userEmailAddressLabel.numberOfLines = 1 userEmailAddressLabel.text = "<Unknown>" view.addSubview(userEmailAddressLabel) contactByPhoneButton.translatesAutoresizingMaskIntoConstraints = false contactByPhoneButton.rounded = true contactByPhoneButton.normalBackgroundColor = UIColor.brandOrange contactByPhoneButton.setTitle(NSLocalizedString("Nous contacter par téléphone", comment: ""), for: .normal) contactByPhoneButton.setTitleColor(UIColor.white, for: .normal) contactByPhoneButton.addTarget(self, action: #selector(self.handleContactByPhoneButtonTapped), for: .touchUpInside) view.addSubview(contactByPhoneButton) contactByEmailButton.translatesAutoresizingMaskIntoConstraints = false contactByEmailButton.rounded = true contactByEmailButton.normalBackgroundColor = UIColor.brandBlue contactByEmailButton.setTitle(NSLocalizedString("Nous contacter par e-mail", comment: ""), for: .normal) contactByEmailButton.setTitleColor(UIColor.white, for: .normal) contactByEmailButton.addTarget(self, action: #selector(self.handleContactByEmailButtonTapped), for: .touchUpInside) view.addSubview(contactByEmailButton) logoutButton.translatesAutoresizingMaskIntoConstraints = false logoutButton.rounded = true logoutButton.normalBackgroundColor = UIColor.brandRed logoutButton.setTitle(NSLocalizedString("Se déconnecter", comment: ""), for: .normal) logoutButton.setTitleColor(UIColor.white, for: .normal) logoutButton.addTarget(self, action: #selector(self.handleLogoutButtonTapped), for: .touchUpInside) view.addSubview(logoutButton) // hide logout on Prod #if !DEBUG logoutButton.isHidden = true #endif } private var didSetupViewConstraints: Bool = false override func updateViewConstraints() { if !didSetupViewConstraints { didSetupViewConstraints = true setupViewConstraints() } super.updateViewConstraints() } private func setupViewConstraints() { constrain(profilePictureImageView, userEmailAddressLabel, contactByPhoneButton, contactByEmailButton, logoutButton) { pic, email, contactPhone, contactEmail, logout in pic.centerX == pic.superview!.centerX pic.top == pic.superview!.topMargin + 50 pic.width == 100 pic.height == 100 email.top == pic.bottom + 30 email.left == email.superview!.leftMargin email.right == email.superview!.rightMargin contactPhone.top == email.bottom + 50 contactPhone.left == contactPhone.superview!.leftMargin contactPhone.right == contactPhone.superview!.rightMargin contactEmail.top == contactPhone.bottom + 20 contactEmail.left == contactEmail.superview!.leftMargin contactEmail.right == contactEmail.superview!.rightMargin logout.bottom == logout.superview!.bottomMargin - 30 logout.left == logout.superview!.leftMargin + 30 logout.right == logout.superview!.rightMargin - 30 } } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() profilePictureImageView.layer.cornerRadius = min(profilePictureImageView.bounds.width, profilePictureImageView.bounds.height) / 2 } // MARK: - Private methods private func loadUserInfos() { guard let currentUser = CurrentUser.get() as? CurrentUser else { print("No current logged in user. This should never happen") return } userEmailAddressLabel.text = currentUser.email } @objc private func handleBackToCameraButtonTapped() { pn_swipeToControllerIdentifier(controllerIdentifier: .CaptureController, animated: true) } @objc private func handleLogoutButtonTapped() { CurrentUser.delete() if let appDelegate = UIApplication.shared.delegate as? AppDelegate { appDelegate.presentLoginScreen() } } @objc private func handleContactByPhoneButtonTapped() { UIApplication.shared.open(URL(string: "tel://+33672482741")!, options: [:], completionHandler: nil) } @objc private func handleContactByEmailButtonTapped() { guard MFMailComposeViewController.canSendMail() else { HUD.flash(.labeledError(title: NSLocalizedString("Failed", comment: ""), subtitle: NSLocalizedString("No mail account configured", comment: "")), delay: 3.0) return } let controller = MFMailComposeViewController() controller.mailComposeDelegate = self controller.setToRecipients(["[email protected]"]) controller.setSubject("Retours sur l'application alpha") present(controller, animated: true, completion: nil) } } extension AccountViewController : MFMailComposeViewControllerDelegate { func mailComposeController(_ controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?) { controller.dismiss(animated: true, completion: nil) } }
gpl-3.0
b7da25237043583a2c7100a3784100b0
40.344444
175
0.691078
5.512593
false
false
false
false
Shashi717/ImmiGuide
ImmiGuide/ImmiGuide/ProfileViewController.swift
1
5593
// // ProfileViewController.swift // ImmiGuide // // Created by Annie Tung on 2/19/17. // Copyright © 2017 Madushani Lekam Wasam Liyanage. All rights reserved. // import UIKit class ProfileViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout, UITableViewDelegate, UITableViewDataSource,UITabBarControllerDelegate { @IBOutlet weak var tableView: UITableView! @IBOutlet weak var collectionView: UICollectionView! let imageNames = ["Spain", "china", "united-states"] var currentLanguage: String! required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) let userDefaults = UserDefaults.standard let appLanguage = userDefaults.object(forKey: TranslationLanguage.appLanguage.rawValue) if let language = appLanguage as? String, let languageDict = Translation.tabBarTranslation[language], let firstTab = languageDict["Settings"] { self.navigationController?.tabBarItem.title = firstTab } } override func viewDidLoad() { super.viewDidLoad() self.navigationController?.navigationBar.titleTextAttributes = ([NSForegroundColorAttributeName: UIColor.white]) self.navigationItem.titleView = UIImageView(image: UIImage(named: "Settings-64")) self.navigationController?.navigationBar.barTintColor = UIColor(red:1.00, green:0.36, blue:0.36, alpha:1.0) collectionView.delegate = self collectionView.dataSource = self tableView.delegate = self tableView.dataSource = self self.collectionView.register(SettingCollectionViewCell.self, forCellWithReuseIdentifier: SettingCollectionViewCell.identifier) tableView.rowHeight = 75 tableView.preservesSuperviewLayoutMargins = false tableView.separatorInset = UIEdgeInsets.init(top: 0, left: 15, bottom: 0, right: 15) tableView.layoutMargins = UIEdgeInsets.zero tableView.separatorColor = UIColor.darkGray } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) currentLanguage = Translation.getLanguageFromDefauls() collectionView.reloadData() } // MARK: - Collection View func numberOfSections(in collectionView: UICollectionView) -> Int { return 1 } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return imageNames.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: SettingCollectionViewCell.identifier, for: indexPath) as! SettingCollectionViewCell let imageName = imageNames[indexPath.item] let language = Translation.languageFrom(imageName: imageName) currentLanguage = Translation.getLanguageFromDefauls() if language == currentLanguage { cell.flagImage.image = UIImage(named: imageName) cell.alpha = 1.0 cell.layoutIfNeeded() } else { cell.flagImage.image = UIImage(named: imageName) cell.alpha = 0.40 cell.layoutIfNeeded() } return cell } func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { let imageName = imageNames[indexPath.item] let language = Translation.languageFrom(imageName: imageName) let defaults = UserDefaults() defaults.setValue(language, forKey: TranslationLanguage.appLanguage.rawValue) collectionView.reloadData() } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { let width = view.frame.width * 0.25 return CGSize(width: width, height: width) } // MARK: - Table View func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 2 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { switch indexPath.row { case 0: let cell = tableView.dequeueReusableCell(withIdentifier: "MeetTheTeam", for: indexPath) as! MeetTheTeamTableViewCell cell.teamLabel?.text = " Meet The Team" return cell case 1: let cell = tableView.dequeueReusableCell(withIdentifier: "Feedback", for: indexPath) as! MeetTheTeamTableViewCell cell.feedbackLabel?.text = " Send Us Feedback" return cell default: let cell = tableView.dequeueReusableCell(withIdentifier: "MeetTheTeam", for: indexPath) as! MeetTheTeamTableViewCell return cell } } // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "GoogleFormSegue" { if let cuvc = segue.destination as? ContactUsViewController { cuvc.url = "https://docs.google.com/forms/d/e/1FAIpQLSc4fVNv7jHBJemmRgPOvdavjWsAZf3gZ221U6aR6BjLHK5llA/viewform" } } } }
mit
3ed175659353040037b562a55ea6c052
40.422222
208
0.677933
5.285444
false
false
false
false
SpriteKitAlliance/SKATiledMap
SKATiledMapExample/GameScene.swift
1
3028
// // GameScene.swift // SKATiledMapExample // // Created by Skyler Lauren on 10/5/15. // Copyright (c) 2015 Sprite Kit Alliance. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. import SpriteKit class GameScene: SKScene { let player = SKATestPlayer(color: UIColor.blueColor(), size: CGSizeMake(40, 80)) let map = SKATiledMap(mapName: "SampleMapKenney") override func didMoveToView(view: SKView) { addChild(map) //showing ease of adding actions to a layer let fadeOut = SKAction.fadeAlphaTo(0, duration: 2) let fadeIn = SKAction.fadeAlphaTo(1, duration: 2) let sequence = SKAction.sequence([fadeOut, fadeIn]) let repeatAction = SKAction.repeatActionForever(sequence) let backgroundLayer = map.spriteLayers[0] backgroundLayer .runAction(repeatAction) //showing ease of adding action to a specific sprite let rotate = SKAction.rotateByAngle(2, duration: 1) let repeatRotation = SKAction.repeatActionForever(rotate) let sprite = map.spriteFor(2, x: 5, y: 4) sprite.runAction(repeatRotation) //adding test player player.zPosition = 20 player.position = CGPointMake(400, 400); map.autoFollowNode = player; map.addChild(player) //adding test hud let hud = SKATestHud(scene: self, player: player) addChild(hud) } override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) { /* Called when a touch begins */ } override func update(currentTime: CFTimeInterval) { //updates map.update() player.update() //culling feature update let playerIndex = map.index(player.position) map.cullAround(Int(playerIndex.x), y: Int(playerIndex.y), width: 5, height: 5) } }
mit
5aa9967106d1a0939619f6cc0aadfbfd
35.047619
86
0.662814
4.459499
false
false
false
false
mypalal84/GoGoGithub
GoGoGithub/GoGoGithub/RepoDetailViewController.swift
1
2578
// // RepoDetailViewController.swift // GoGoGithub // // Created by A Cahn on 4/5/17. // Copyright © 2017 A Cahn. All rights reserved. // import UIKit import SafariServices class RepoDetailViewController: UIViewController { @IBOutlet weak var repoNameLabel: UILabel! @IBOutlet weak var repoDescriptionLabel: UILabel! @IBOutlet weak var languageLabel: UILabel! @IBOutlet weak var starsLabel: UILabel! @IBOutlet weak var forkLabel: UILabel! @IBOutlet weak var dateLabel: UILabel! var repo: Repository? // { // didSet { // if let repo = repo { // self.repoNameLabel.text = repo.name // self.repoDescriptionLabel.text = repo.description // self.languageLabel.text = repo.language // self.starsLabel.text = "Stars: \(repo.numberOfStars)" // self.forkLabel.text = repo.isFork ? "Forked" : "Not forked" // self.dateLabel.text = repo.createdAt // } // } // } override func viewDidLoad() { super.viewDidLoad() if let repo = repo { self.repoNameLabel.text = repo.name self.repoDescriptionLabel.text = repo.description self.languageLabel.text = repo.language self.starsLabel.text = "Stars: \(repo.numberOfStars)" self.forkLabel.text = repo.isFork ? "Forked" : "Not forked" self.dateLabel.text = "Date Created: \(repo.createdAt)" } } @IBAction func backButtonPressed(_ sender: Any) { self.dismiss(animated: true, completion: nil) } @IBAction func moreDetailsPressed(_ sender: Any) { guard let repo = repo else { return } presentSafariViewControllerWith(urlString: repo.repoURLString) // presentWebViewControllerWith(urlString: repo.repoURLString) } func presentSafariViewControllerWith(urlString: String) { guard let url = URL(string: urlString) else { return } let safariController = SFSafariViewController(url: url) self.present(safariController, animated: true, completion: nil) } func presentWebViewControllerWith(urlString: String) { let webController = WebViewController() webController.url = urlString self.present(webController, animated: true, completion: nil) } }
mit
1dbfd6893e529d5497ea8e8e4bc0548a
28.62069
81
0.58246
4.807836
false
false
false
false
quadro5/swift3_L
Swift_api.playground/Pages/Primitive Types.xcplaygroundpage/Contents.swift
1
254
//: [Previous](@previous) import Foundation var str = "Hello, playground" //: [Next](@next) //UInt(bitPattern: Int) let num0 = UInt(bitPattern: -1) let num1 = UInt(bitPattern: 0) let num2 = UInt(bitPattern: 1) let num3 = Int(bitPattern: UInt(1))
unlicense
eb8e4f3793ea7740692ecbb7ab19c893
13.166667
35
0.665354
2.988235
false
false
false
false
vl4298/mah-income
Mah Income/Mah Income/Scenes/Analyze/Option/Chart/BarChart.swift
1
2379
// // BarChart.swift // Mah Income // // Created by Van Luu on 5/9/17. // Copyright © 2017 Van Luu. All rights reserved. // import UIKit import Charts class BarChart: UIScrollView { fileprivate var barChartView: BarChartView! var data: [String: Double]! { didSet { setupDataAndAnimate() } } override var contentSize: CGSize { didSet { barChartView.frame.size = contentSize } } var animateDuration: TimeInterval = 1.4 weak var vcdelegate: ChartDelegate! var kind: String = "" var extraData: String = "" override init(frame: CGRect) { super.init(frame: frame) setupbarChartView() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func setupbarChartView() { barChartView = BarChartView(frame: self.bounds) barChartView.drawGridBackgroundEnabled = false barChartView.highlightPerDragEnabled = false let leftAxis = barChartView.leftAxis leftAxis.enabled = false let rightAxis = barChartView.rightAxis rightAxis.enabled = false self.addSubview(barChartView) barChartView.chartDescription?.text = "" let legend = barChartView.legend legend.form = .circle legend.horizontalAlignment = .left legend.verticalAlignment = .bottom legend.orientation = .horizontal legend.formSize = 10.0 legend.xEntrySpace = 100.0 legend.yEntrySpace = 10.0 legend.font = UIFont(name: "Avenir Next", size: 13.0)! barChartView.delegate = self } func setupDataAndAnimate() { var i: Double = 0 var dataSets: [BarChartDataSet] = [] for (field, value) in data { let entry = BarChartDataEntry(x: i, y: value) entry.data = [field: value] as AnyObject let dataSet = BarChartDataSet(values: [entry], label: field) dataSet.colors = [.random()] dataSets.append(dataSet) i += 1 } let chartData = BarChartData(dataSets: dataSets) barChartView.data = chartData barChartView.animate(xAxisDuration: animateDuration, yAxisDuration: animateDuration, easingOption: .easeInCubic) } } extension BarChart: ChartViewDelegate { func chartValueSelected(_ chartView: ChartViewBase, entry: ChartDataEntry, highlight: Highlight) { vcdelegate.barChartSelected(barChart: self, value: entry) } }
mit
e7ed7839edd339dae9b954c297185267
24.297872
116
0.675778
4.469925
false
false
false
false
darkzero/DZPopupMessageView
Example/DZPopupMessageSample/HomeViewController.swift
1
2316
// // ViewController.swift // DZPopupMessageSample // // Created by Yuhua Hu on 2019/01/23. // Copyright © 2019 CocoaPods. All rights reserved. // import UIKit import DZPopupMessageView class HomeViewController: UIViewController { @IBOutlet var messageField: UITextField! @IBOutlet var themeSegment: UISegmentedControl! @IBOutlet var typeSegment: UISegmentedControl! @IBOutlet var displaySegment: UISegmentedControl! @IBOutlet var imageView: UIImageView! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. //let image = UIImage(named: "dz_icon_info", in: Bundle(for: DZPopupMessageView.self), compatibleWith: nil)?.withRenderingMode(.alwaysTemplate) //self.imageView.image = image } } extension HomeViewController { @IBAction func onButtonClicked(_ sender: UIButton) { self.view.endEditing(true) var msg = self.messageField.text ?? "" if msg.count <= 0 { msg = "Test Message" } // theme let theme: DZPopupMessage.Theme = { switch self.themeSegment.selectedSegmentIndex { case 0: return .light case 1: return .dark default: return .light } }() // type let type: DZPopupMessage.MessageType = { switch self.typeSegment.selectedSegmentIndex { case 0: return .info case 1: return .warning case 2: return .error default: return .info } }() // display let display: DZPopupMessage.DisplayType = { switch self.displaySegment.selectedSegmentIndex { case 0: return .rise case 1: return .drop case 2: return .bubbleTop case 3: return .bubbleBottom default: return .bubbleBottom } }() DZPopupMessage.show(msg, theme: theme, type: type, display: display, callback: { // print("aaaaaa") }) } }
mit
a79d29cc88a995b42ca2eec5b1dacb2b
27.231707
151
0.543844
5.155902
false
false
false
false
pennlabs/penn-mobile-ios
PennMobile/Setup + Navigation/TabBarController.swift
1
4149
// // NavigationTabBarController.swift // PennMobile // // Created by Josh Doman on 2/16/18. // Copyright © 2018 PennLabs. All rights reserved. // import Foundation import UIKit final class TabBarController: UITabBarController { override func viewDidLoad() { super.viewDidLoad() let appearance = UITabBarAppearance() appearance.configureWithOpaqueBackground() tabBar.standardAppearance = appearance // Required to prevent tab bar's appearance from switching between light and dark mode if #available(iOS 15.0, *) { tabBar.scrollEdgeAppearance = appearance } loadTabs() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) } func loadTabs() { ControllerModel.shared.viewControllers.forEach { (vc) in if vc is TabBarShowable { vc.tabBarItem = (vc as! TabBarShowable).getTabBarItem() } } self.viewControllers = ControllerModel.shared.viewControllers self.delegate = self } } // MARK: - Delegate extension TabBarController: UITabBarControllerDelegate { func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool { return true } } protocol TabBarShowable { func getTabBarItem() -> UITabBarItem } extension HomeViewController: TabBarShowable { func getTabBarItem() -> UITabBarItem { let normalImage = UIImage(named: "Home_Grey") let selectedImage = UIImage(named: "Home_Blue") return UITabBarItem(title: "Home", image: normalImage, selectedImage: selectedImage) } } /*extension FlingViewController: TabBarShowable { func getTabBarItem() -> UITabBarItem { let normalImage = UIImage(named: "Fling_Grey") let selectedImage = UIImage(named: "Fling_Blue") return UITabBarItem(title: "Fling", image: normalImage, selectedImage: selectedImage) } }*/ extension DiningViewControllerSwiftUI: TabBarShowable { func getTabBarItem() -> UITabBarItem { let normalImage = UIImage(named: "Dining_Grey") let selectedImage = UIImage(named: "Dining_Blue") return UITabBarItem(title: "Dining", image: normalImage, selectedImage: selectedImage) } } extension GSRController: TabBarShowable { func getTabBarItem() -> UITabBarItem { let normalImage = UIImage(named: "GSR_Grey") let selectedImage = UIImage(named: "GSR_Blue") return UITabBarItem(title: "GSR", image: normalImage, selectedImage: selectedImage) } } extension GSRLocationsController: TabBarShowable { func getTabBarItem() -> UITabBarItem { let normalImage = UIImage(named: "GSR_Grey") let selectedImage = UIImage(named: "GSR_Blue") return UITabBarItem(title: "GSR", image: normalImage, selectedImage: selectedImage) } } extension GSRTabController: TabBarShowable { func getTabBarItem() -> UITabBarItem { let normalImage = UIImage(named: "GSR_Grey") let selectedImage = UIImage(named: "GSR_Blue") return UITabBarItem(title: "GSR", image: normalImage, selectedImage: selectedImage) } } extension LaundryTableViewController: TabBarShowable { func getTabBarItem() -> UITabBarItem { let normalImage = UIImage(named: "Laundry_Grey") let selectedImage = UIImage(named: "Laundry_Blue") return UITabBarItem(title: "Laundry", image: normalImage, selectedImage: selectedImage) } } extension FitnessViewController: TabBarShowable { func getTabBarItem() -> UITabBarItem { let normalImage = UIImage(named: "Fitness_Grey") let selectedImage = UIImage(named: "Fitness_Blue") return UITabBarItem(title: "Fitness", image: normalImage, selectedImage: selectedImage) } } extension MoreViewController: TabBarShowable { func getTabBarItem() -> UITabBarItem { let normalImage = UIImage(named: "More_Grey") let selectedImage = UIImage(named: "More_Blue") return UITabBarItem(title: "More", image: normalImage, selectedImage: selectedImage) } }
mit
306a3ab45c8f89ea80d205593b85eaef
32.723577
122
0.686596
4.756881
false
false
false
false
adamnemecek/AudioKit
Tests/AudioKitTests/Node Tests/Player Tests/AudioPlayerFileTests+RealtimeContent.swift
1
11794
import AudioKit import AVFoundation import XCTest extension AudioPlayerFileTests { func realtimeTestReversed(from startTime: TimeInterval = 0, to endTime: TimeInterval = 0) { guard let countingURL = countingURL else { XCTFail("Didn't find the 12345.wav") return } guard let player = AudioPlayer(url: countingURL) else { XCTFail("Failed to create AudioPlayer") return } let engine = AudioEngine() engine.output = player try? engine.start() player.completionHandler = { Log("🏁 Completion Handler") } player.isReversed = true player.play(from: startTime, to: endTime) wait(for: endTime - startTime) } // Walks through the chromatic scale playing each note twice with // two different editing methods. Note this test will take some time // so be prepared to cancel it func realtimeTestEdited(buffered: Bool = false, reversed: Bool = false) { let duration = TimeInterval(chromaticScale.count) guard let player = createPlayer(duration: duration, buffered: buffered) else { XCTFail("Failed to create AudioPlayer") return } if buffered { guard player.isBuffered else { XCTFail("Should be buffered") return } } player.isReversed = reversed let engine = AudioEngine() engine.output = player try? engine.start() player.completionHandler = { Log("🏁 Completion Handler") } // test out of bounds edits player.editStartTime = duration + 1 XCTAssertTrue(player.editStartTime == player.duration) player.editStartTime = -1 XCTAssertTrue(player.editStartTime == 0) player.editEndTime = -1 XCTAssertTrue(player.editEndTime == 0) player.editEndTime = duration + 1 XCTAssertTrue(player.editEndTime == player.duration) for i in 0 ..< chromaticScale.count { let startTime = TimeInterval(i) let endTime = TimeInterval(i + 1) Log(startTime, "to", endTime, "duration", duration) player.play(from: startTime, to: endTime, at: nil) wait(for: 2) // Alternate syntax which should be the same as above player.editStartTime = startTime player.editEndTime = endTime Log(startTime, "to", endTime, "duration", duration) player.play() wait(for: 2) } Log("Done") } func realtimeTestPause() { guard let player = createPlayer(duration: 5) else { XCTFail("Failed to create AudioPlayer") return } let engine = AudioEngine() engine.output = player try? engine.start() player.completionHandler = { Log("🏁 Completion Handler") } var duration = player.duration Log("▶️") player.play() wait(for: 2) duration -= 2 Log("⏸") player.pause() wait(for: 1) duration -= 1 Log("▶️") player.play() wait(for: duration) Log("⏹") } func realtimeScheduleFile() { guard let player = createPlayer(duration: 2) else { XCTFail("Failed to create AudioPlayer") return } let engine = AudioEngine() engine.output = player try? engine.start() var completionCounter = 0 player.completionHandler = { completionCounter += 1 Log("🏁 Completion Handler", completionCounter) } // test schedule with play player.play(at: AVAudioTime.now().offset(seconds: 3)) wait(for: player.duration + 4) // test schedule separated from play player.schedule(at: AVAudioTime.now().offset(seconds: 3)) player.play() wait(for: player.duration + 4) XCTAssertEqual(completionCounter, 2, "Completion handler wasn't called on both completions") } func realtimeLoop(buffered: Bool, duration: TimeInterval) { guard let player = createPlayer(duration: duration, buffered: buffered) else { XCTFail("Failed to create AudioPlayer") return } let engine = AudioEngine() engine.output = player try? engine.start() var completionCounter = 0 player.completionHandler = { if buffered { XCTFail("For buffer looping the completion handler isn't called. The loop is infinite") return } completionCounter += 1 Log("🏁 Completion Handler", completionCounter) } player.isLooping = true player.play() wait(for: 5) player.stop() } func realtimeInterrupts() { guard let player = createPlayer(duration: 5, buffered: false) else { XCTFail("Failed to create AudioPlayer") return } let engine = AudioEngine() engine.output = player try? engine.start() player.isLooping = true player.play() wait(for: 2) guard let url2 = Bundle.module.url(forResource: "twoNotes-2", withExtension: "aiff", subdirectory: "TestResources") else { XCTFail("Failed to create file") return } do { let file = try AVAudioFile(forReading: url2) try player.load(file: file) XCTAssertNotNil(player.file, "File is nil") } catch let error as NSError { Log(error, type: .error) XCTFail("Failed loading AVAudioFile") } wait(for: 1.5) guard let url3 = Bundle.module.url(forResource: "twoNotes-3", withExtension: "aiff", subdirectory: "TestResources") else { XCTFail("Failed to create file") return } // load a file do { let file = try AVAudioFile(forReading: url3) try player.load(file: file, buffered: true) XCTAssertNotNil(player.buffer, "Buffer is nil") } catch let error as NSError { Log(error, type: .error) XCTFail("Failed loading AVAudioFile") } wait(for: 2) // load a buffer guard let url4 = Bundle.module.url(forResource: "chromaticScale-2", withExtension: "aiff", subdirectory: "TestResources"), let buffer = try? AVAudioPCMBuffer(url: url4) else { XCTFail("Failed to create file or buffer") return } // will set isBuffered to true player.buffer = buffer XCTAssertTrue(player.isBuffered, "isBuffered isn't correct") wait(for: 1.5) // load a file after a buffer guard let url5 = Bundle.module.url(forResource: "chromaticScale-1", withExtension: "aiff", subdirectory: "TestResources"), let file = try? AVAudioFile(forReading: url5) else { XCTFail("Failed to create file or buffer") return } player.buffer = nil player.file = file XCTAssertFalse(player.isBuffered, "isBuffered isn't correct") wait(for: 2) } func realtimeTestSeek(buffered: Bool = false) { guard let countingURL = countingURL else { XCTFail("Didn't find the 12345.wav") return } guard let player = AudioPlayer(url: countingURL) else { XCTFail("Failed to create AudioPlayer") return } let engine = AudioEngine() engine.output = player try? engine.start() player.completionHandler = { Log("🏁 Completion Handler", Thread.current) } player.isBuffered = buffered // 2 3 4 player.seek(time: 1) player.play() XCTAssertTrue(player.isPlaying) wait(for: 1) player.stop() wait(for: 1) // 4 player.seek(time: 3) player.play() XCTAssertTrue(player.isPlaying) wait(for: 1) // NOTE: the completionHandler will set isPlaying to false. This happens in a different // thread and subsequently makes the below isPlaying checks fail. This only seems // to happen in the buffered test, but bypassing those checks for now // rewind to 4 while playing player.seek(time: 3) // XCTAssertTrue(player.isPlaying) wait(for: 1) player.seek(time: 2) // XCTAssertTrue(player.isPlaying) wait(for: 1) player.seek(time: 1) // XCTAssertTrue(player.isPlaying) wait(for: 1) var time = player.duration // make him count backwards for fun: 5 4 3 2 1 // Currently only works correctly in the non buffered version: while time > 0 { time -= 1 player.seek(time: time) // XCTAssertTrue(player.isPlaying) wait(for: 1) } player.stop() } } extension AudioPlayerFileTests { /// Files should play back at normal pitch for both buffered and streamed func realtimeTestMixedSampleRates(buffered: Bool = false) { // this file is 44.1k guard let countingURL = countingURL else { XCTFail("Didn't find the 12345.wav") return } guard let audioFormat = AVAudioFormat(standardFormatWithSampleRate: 48000, channels: 2) else { XCTFail("Failed to create 48k format") return } let countingURL48k = countingURL.deletingLastPathComponent() .appendingPathComponent("_io_audiokit_AudioPlayerFileTests_realtimeTestMixedSampleRates.wav") Self.tempFiles.append(countingURL48k) let wav48k = FormatConverter.Options(pcmFormat: "wav", sampleRate: 48000, bitDepth: 16, channels: 1) let converter = FormatConverter(inputURL: countingURL, outputURL: countingURL48k, options: wav48k) converter.start { error in if let error = error { XCTFail(error.localizedDescription) return } self.processMixedSampleRates(urls: [countingURL, countingURL48k], audioFormat: audioFormat, buffered: buffered) } } private func processMixedSampleRates(urls: [URL], audioFormat: AVAudioFormat, buffered: Bool = false) { Settings.audioFormat = audioFormat let engine = AudioEngine() let player = AudioPlayer() player.isBuffered = buffered player.completionHandler = { Log("🏁 Completion Handler", Thread.current) } engine.output = player try? engine.start() for url in urls { do { try player.load(url: url) } catch { Log(error) XCTFail(error.localizedDescription) } Log("ENGINE", engine.avEngine.description, "PLAYER fileFormat", player.file?.fileFormat, "PLAYER buffer format", player.buffer?.format) player.play() wait(for: player.duration + 1) player.stop() } } }
mit
5262cf852ea334c398af04667b5be17b
29.627604
131
0.553949
4.954086
false
false
false
false
ObjectAlchemist/OOUIKit
Sources/_UIKitDelegate/UITextFieldDelegate/ManagingEditing/UITextFieldDelegateManage.swift
1
2183
// // UITextFieldDelegateManage.swift // OOUIKit // // Created by Karsten Litsche on 05.11.17. // import UIKit import OOBase public final class UITextFieldDelegateManage: NSObject, UITextFieldDelegate { // MARK: - init public init( shouldBeginEditing: @escaping (UITextField) -> OOBool = { _ in BoolConst(true) }, didBeginEditing: @escaping (UITextField) -> OOExecutable = { _ in DoNothing() }, shouldEndEditing: @escaping (UITextField) -> OOBool = { _ in BoolConst(true) }, didEndEditingReason: @escaping (UITextField, UITextField.DidEndEditingReason) -> OOExecutable = { _,_ in DoNothing() }, didEndEditing: @escaping (UITextField) -> OOExecutable = { _ in DoNothing() } ) { self.shouldBeginEditing = shouldBeginEditing self.didBeginEditing = didBeginEditing self.shouldEndEditing = shouldEndEditing self.didEndEditingReason = didEndEditingReason self.didEndEditing = didEndEditing super.init() } // MARK: - protocol: UITextFieldDelegate public final func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool { return shouldBeginEditing(textField).value } public final func textFieldDidBeginEditing(_ textField: UITextField) { didBeginEditing(textField).execute() } public final func textFieldShouldEndEditing(_ textField: UITextField) -> Bool { return shouldEndEditing(textField).value } public final func textFieldDidEndEditing(_ textField: UITextField, reason: UITextField.DidEndEditingReason) { didEndEditingReason(textField, reason).execute() } public final func textFieldDidEndEditing(_ textField: UITextField) { didEndEditing(textField).execute() } // MARK: - private private let shouldBeginEditing: (UITextField) -> OOBool private let didBeginEditing: (UITextField) -> OOExecutable private let shouldEndEditing: (UITextField) -> OOBool private let didEndEditingReason: (UITextField, UITextField.DidEndEditingReason) -> OOExecutable private let didEndEditing: (UITextField) -> OOExecutable }
mit
fb38a82df9d69e24d8e0a089091aaa4b
34.786885
127
0.689418
5.376847
false
false
false
false
WE-St0r/SwiftyVK
Library/Sources/Utils/Reachability.swift
2
10041
/* Copyright (c) 2014, Ashley Mills All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ // Reachability.swift version 2.2beta2 import SystemConfiguration import Foundation public enum ReachabilityError: Error { case FailedToCreateWithAddress(sockaddr_in) case FailedToCreateWithHostname(String) case UnableToSetCallback case UnableToSetDispatchQueue } public let ReachabilityChangedNotification = NSNotification.Name("ReachabilityChangedNotification") func callback(reachability: SCNetworkReachability, flags: SCNetworkReachabilityFlags, info: UnsafeMutableRawPointer?) { guard let info = info else { return } let reachability = Unmanaged<Reachability>.fromOpaque(info).takeUnretainedValue() DispatchQueue.main.async { reachability.reachabilityChanged() } } public class Reachability { public typealias NetworkReachable = (Reachability) -> () public typealias NetworkUnreachable = (Reachability) -> () public enum NetworkStatus: CustomStringConvertible { case notReachable, reachableViaWiFi, reachableViaWWAN public var description: String { switch self { case .reachableViaWWAN: return "Cellular" case .reachableViaWiFi: return "WiFi" case .notReachable: return "No Connection" } } } var semaphore = DispatchSemaphore(value: 0) public var whenReachable: NetworkReachable? public var whenUnreachable: NetworkUnreachable? public var reachableOnWWAN: Bool public var currentReachabilityString: String { return "\(currentReachabilityStatus)" } public var currentReachabilityStatus: NetworkStatus { guard isReachable else { return .notReachable } if isReachableViaWiFi { return .reachableViaWiFi } if isRunningOnDevice { return .reachableViaWWAN } return .notReachable } fileprivate var previousFlags: SCNetworkReachabilityFlags? fileprivate var isRunningOnDevice: Bool = { #if targetEnvironment(simulator) return false #else return true #endif }() fileprivate var notifierRunning = false fileprivate var reachabilityRef: SCNetworkReachability? fileprivate let reachabilitySerialQueue = DispatchQueue(label: "uk.co.ashleymills.reachability") required public init(reachabilityRef: SCNetworkReachability) { reachableOnWWAN = true self.reachabilityRef = reachabilityRef } public convenience init?(hostname: String) { guard let ref = SCNetworkReachabilityCreateWithName(nil, hostname) else { return nil } self.init(reachabilityRef: ref) } public convenience init?() { var zeroAddress = sockaddr() zeroAddress.sa_len = UInt8(MemoryLayout<sockaddr>.size) zeroAddress.sa_family = sa_family_t(AF_INET) guard let ref: SCNetworkReachability = withUnsafePointer(to: &zeroAddress, { SCNetworkReachabilityCreateWithAddress(nil, UnsafePointer($0)) }) else { return nil } self.init(reachabilityRef: ref) } deinit { stopNotifier() semaphore.signal() reachabilityRef = nil whenReachable = nil whenUnreachable = nil } } extension Reachability { // MARK: - *** Notifier methods *** func startNotifier() throws { guard let reachabilityRef = reachabilityRef, !notifierRunning else { return } var context = SCNetworkReachabilityContext(version: 0, info: nil, retain: nil, release: nil, copyDescription: nil) context.info = UnsafeMutableRawPointer(Unmanaged<Reachability>.passUnretained(self).toOpaque()) if !SCNetworkReachabilitySetCallback(reachabilityRef, callback, &context) { stopNotifier() throw ReachabilityError.UnableToSetCallback } if !SCNetworkReachabilitySetDispatchQueue(reachabilityRef, reachabilitySerialQueue) { stopNotifier() throw ReachabilityError.UnableToSetDispatchQueue } // Perform an intial check reachabilitySerialQueue.async { self.reachabilityChanged() } notifierRunning = true } func stopNotifier() { defer { notifierRunning = false } guard let reachabilityRef = reachabilityRef else { return } SCNetworkReachabilitySetCallback(reachabilityRef, nil, nil) SCNetworkReachabilitySetDispatchQueue(reachabilityRef, nil) } // MARK: - *** Connection test methods *** var isReachable: Bool { guard isReachableFlagSet else { return false } if isConnectionRequiredAndTransientFlagSet { return false } if isRunningOnDevice { if isOnWWANFlagSet && !reachableOnWWAN { // We don't want to connect when on 3G. return false } } return true } var isReachableViaWWAN: Bool { // Check we're not on the simulator, we're REACHABLE and check we're on WWAN return isRunningOnDevice && isReachableFlagSet && isOnWWANFlagSet } var isReachableViaWiFi: Bool { // Check we're reachable guard isReachableFlagSet else { return false } // If reachable we're reachable, but not on an iOS device (i.e. simulator), we must be on WiFi guard isRunningOnDevice else { return true } // Check we're NOT on WWAN return !isOnWWANFlagSet } var description: String { let W = isRunningOnDevice ? (isOnWWANFlagSet ? "W" : "-") : "X" let R = isReachableFlagSet ? "R" : "-" let c = isConnectionRequiredFlagSet ? "c" : "-" let t = isTransientConnectionFlagSet ? "t" : "-" let i = isInterventionRequiredFlagSet ? "i" : "-" let C = isConnectionOnTrafficFlagSet ? "C" : "-" let D = isConnectionOnDemandFlagSet ? "D" : "-" let l = isLocalAddressFlagSet ? "l" : "-" let d = isDirectFlagSet ? "d" : "-" return "\(W)\(R) \(c)\(t)\(i)\(C)\(D)\(l)\(d)" } } fileprivate extension Reachability { func reachabilityChanged() { let flags = reachabilityFlags guard previousFlags != flags else { return } let block = isReachable ? whenReachable : whenUnreachable block?(self) NotificationCenter.default.post(name: ReachabilityChangedNotification, object:self) previousFlags = flags } var isOnWWANFlagSet: Bool { #if os(iOS) return reachabilityFlags.contains(.isWWAN) #else return false #endif } var isReachableFlagSet: Bool { return reachabilityFlags.contains(.reachable) } var isConnectionRequiredFlagSet: Bool { return reachabilityFlags.contains(.connectionRequired) } var isInterventionRequiredFlagSet: Bool { return reachabilityFlags.contains(.interventionRequired) } var isConnectionOnTrafficFlagSet: Bool { return reachabilityFlags.contains(.connectionOnTraffic) } var isConnectionOnDemandFlagSet: Bool { return reachabilityFlags.contains(.connectionOnDemand) } var isConnectionOnTrafficOrDemandFlagSet: Bool { return !reachabilityFlags.intersection([.connectionOnTraffic, .connectionOnDemand]).isEmpty } var isTransientConnectionFlagSet: Bool { return reachabilityFlags.contains(.transientConnection) } var isLocalAddressFlagSet: Bool { return reachabilityFlags.contains(.isLocalAddress) } var isDirectFlagSet: Bool { return reachabilityFlags.contains(.isDirect) } var isConnectionRequiredAndTransientFlagSet: Bool { return reachabilityFlags.intersection([.connectionRequired, .transientConnection]) == [.connectionRequired, .transientConnection] } var reachabilityFlags: SCNetworkReachabilityFlags { guard let reachabilityRef = reachabilityRef else { return SCNetworkReachabilityFlags() } var flags = SCNetworkReachabilityFlags() let gotFlags = withUnsafeMutablePointer(to: &flags) { SCNetworkReachabilityGetFlags(reachabilityRef, UnsafeMutablePointer($0)) } if gotFlags { return flags } else { return SCNetworkReachabilityFlags() } } }
mit
248ffbe83b3fc08eaebee1191498d786
32.694631
137
0.654915
6.115104
false
false
false
false
kostiakoval/Seru
Seru/Classes/Seru.swift
1
3511
// // Actions.swift // Seru // // Created by Konstantin Koval on 28/02/15. // Copyright (c) 2015 Konstantin Koval. All rights reserved. // import Foundation import CoreData import Sweet protocol StorageAtions { var errorHandler: ErrorHandling {get} var mainMOC: NSManagedObjectContext {get} func persist(moc: NSManagedObjectContext) } public class Seru { public let stack: CoreDataStack let errorHandler: ErrorHandling public init (stack: CoreDataStack) { self.stack = stack errorHandler = ErrorHandler() } public convenience init(name:String = AppInfo.productName, bundle: NSBundle = NSBundle.mainBundle(), type: StoreType = .SQLite, location: StoreLocation = .PrivateFolder) { self.init(stack: BaseStack(name: name, bundle: bundle, type: type, location: location)) } //MARK: - Functionalioty public func persist() { return persist(stack.mainMOC) } public func persist(moc: NSManagedObjectContext) { saveContext(moc) } //MARK: - Perform public func performInBackgroundContext(block: (context: NSManagedObjectContext) -> Void) { let context = Seru.backgroundContext(stack.mainMOC) performWorkInContext(context, block: block) } public func performInMainContext(block: (context: NSManagedObjectContext) -> Void) { performWorkInContext(stack.mainMOC, block: block) } func performWorkInContext(context: NSManagedObjectContext, block: (context: NSManagedObjectContext) -> Void) { context.performBlock { block(context: context) } } public func performBackgroundSave(block: (context: NSManagedObjectContext) -> Void) { performBackgroundSave(block, completion: nil) } public func performBackgroundSave(block: (context: NSManagedObjectContext) -> Void, completion: (Bool -> Void)? = nil) { let context = Seru.backgroundContext(stack.mainMOC) context.performBlock { block(context: context) self.saveContext(context, completion: {result in if let parentContex = context.parentContext { self.saveContextsChain(parentContex, completion: completion); } else { call_if(completion, param: result) } }); } } //MARKL:- Context public class func backgroundContext(parent: NSManagedObjectContext? = nil) -> NSManagedObjectContext { let context = NSManagedObjectContext(concurrencyType: .PrivateQueueConcurrencyType) context.name = "Background" context.parentContext = parent return context } //MARK: - Private //MARK: - Save public func saveContext(moc: NSManagedObjectContext, completion: (Bool -> Void)? = nil) { var result: Bool = true if moc.hasChanges { do { try moc.save() } catch let error as NSError { self.errorHandler.handle(error) result = false } } main_queue_call_if(completion, param: result) } func saveContextsChain(moc: NSManagedObjectContext, completion: (Bool -> Void)? = nil) { moc.performBlock { self.saveContext(moc) { [unowned self] result in if result && moc.parentContext != nil { self.saveContextsChain(moc.parentContext!, completion: completion) } else { call_if(completion, param: result) } } } } } //MARK - Helpers func call_if<P>(f: (P -> Void)?, param: P) { if let f = f { f(param) } } func main_queue_call_if<P>(f: (P -> Void)?, param: P) { if let f = f { dispatch_async(dispatch_get_main_queue(), { f(param) }) } }
mit
41b43bb066de3fedf06083fde7083246
24.816176
173
0.675021
4.159953
false
false
false
false
CNKCQ/oschina
OSCHINA/ViewModels/Discover/ArticlesViewModel.swift
1
3161
// // Copyright © 2016年 Jack. All rights reserved. // import Foundation import RxSwift import ObjectMapper class ArticlesViewModel: BaseViewModel { var articleEntities: [ArticleEntity] = [] override init() { super.init() } func refresh() -> Observable<[ArticleEntity]> { page = 1 return getArticleInfoByPage(page: page) } /* 分页获取更多 */ func loadMore() -> Observable<[ArticleEntity]> { return getArticleInfoByPage(page: page + 1) } /// 测试 zip 合并操作 private func getArticleInfoByPage(page: Int) -> Observable<[ArticleEntity]> { return Observable .zip( provider.request(GankIOService.byPageAndKind(kind: "福利", page: page, count: offset)).filter(statusCodes: 200 ... 201).observeOn(backgroundWorkScheduler).map({ response -> [ArticleEntity] in if let result = Mapper<BaseModel<ArticleEntity>>().map(JSONString: String(data: response.data, encoding: String.Encoding.utf8)!) { return result.results! } else { throw response as! Error } }), provider .request(GankIOService.byPageAndKind(kind: "休息视频", page: page, count: offset)) .filter(statusCodes: 200 ... 201) .observeOn(backgroundWorkScheduler) .map({ response -> [ArticleEntity] in if let result = Mapper<BaseModel<ArticleEntity>>().map(JSONString: String(data: response.data, encoding: String.Encoding.utf8)!) { return result.results! } else { throw response as! Error } }), resultSelector: { (girls, videos) -> [ArticleEntity] in for item in girls { item.desc = item.desc! + " " + self.getFirstVideoDescByPublishTime(videos: videos, publishedAt: item.publishedAt!) } return girls } ) .do(onNext: { entities in if !entities.isEmpty { if page == 1 { // new or refresh data self.articleEntities = entities } else { self.articleEntities += entities self.page = page } } }) .observeOn(MainScheduler.instance) } private func getFirstVideoDescByPublishTime(videos: [ArticleEntity], publishedAt: Date) -> String { var videoDesc = "" for item in videos { if item.publishedAt == nil { item.publishedAt = item.createdAt } let videoPublishedAt = item.publishedAt if DateUtil.areDatesSameDay(dateOne: videoPublishedAt!, dateTwo: publishedAt) { videoDesc = item.desc! break } } return videoDesc } }
mit
8e4b6111bb6071c941c8cab227fe2f9e
36.166667
205
0.51025
5.177446
false
false
false
false
CNKCQ/oschina
Pods/SnapKit/Source/Constraint.swift
1
11694
// // SnapKit // // Copyright (c) 2011-Present SnapKit Team - https://github.com/SnapKit // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. #if os(iOS) || os(tvOS) import UIKit #else import AppKit #endif public final class Constraint { internal let sourceLocation: (String, UInt) internal let label: String? private let from: ConstraintItem private let to: ConstraintItem private let relation: ConstraintRelation private let multiplier: ConstraintMultiplierTarget private var constant: ConstraintConstantTarget { didSet { updateConstantAndPriorityIfNeeded() } } private var priority: ConstraintPriorityTarget { didSet { updateConstantAndPriorityIfNeeded() } } public var layoutConstraints: [LayoutConstraint] public var isActive: Bool { for layoutConstraint in self.layoutConstraints { if layoutConstraint.isActive { return true } } return false } // MARK: Initialization internal init(from: ConstraintItem, to: ConstraintItem, relation: ConstraintRelation, sourceLocation: (String, UInt), label: String?, multiplier: ConstraintMultiplierTarget, constant: ConstraintConstantTarget, priority: ConstraintPriorityTarget) { self.from = from self.to = to self.relation = relation self.sourceLocation = sourceLocation self.label = label self.multiplier = multiplier self.constant = constant self.priority = priority self.layoutConstraints = [] // get attributes let layoutFromAttributes = self.from.attributes.layoutAttributes let layoutToAttributes = self.to.attributes.layoutAttributes // get layout from let layoutFrom = self.from.layoutConstraintItem! // get relation let layoutRelation = self.relation.layoutRelation for layoutFromAttribute in layoutFromAttributes { // get layout to attribute let layoutToAttribute: NSLayoutAttribute #if os(iOS) || os(tvOS) if layoutToAttributes.count > 0 { if self.from.attributes == .edges && self.to.attributes == .margins { switch layoutFromAttribute { case .left: layoutToAttribute = .leftMargin case .right: layoutToAttribute = .rightMargin case .top: layoutToAttribute = .topMargin case .bottom: layoutToAttribute = .bottomMargin default: fatalError() } } else if self.from.attributes == .margins && self.to.attributes == .edges { switch layoutFromAttribute { case .leftMargin: layoutToAttribute = .left case .rightMargin: layoutToAttribute = .right case .topMargin: layoutToAttribute = .top case .bottomMargin: layoutToAttribute = .bottom default: fatalError() } } else if self.from.attributes == self.to.attributes { layoutToAttribute = layoutFromAttribute } else { layoutToAttribute = layoutToAttributes[0] } } else { if self.to.target == nil && (layoutFromAttribute == .centerX || layoutFromAttribute == .centerY) { layoutToAttribute = layoutFromAttribute == .centerX ? .left : .top } else { layoutToAttribute = layoutFromAttribute } } #else if self.from.attributes == self.to.attributes { layoutToAttribute = layoutFromAttribute } else if layoutToAttributes.count > 0 { layoutToAttribute = layoutToAttributes[0] } else { layoutToAttribute = layoutFromAttribute } #endif // get layout constant let layoutConstant: CGFloat = self.constant.constraintConstantTargetValueFor(layoutAttribute: layoutToAttribute) // get layout to var layoutTo: AnyObject? = self.to.target // use superview if possible if layoutTo == nil && layoutToAttribute != .width && layoutToAttribute != .height { layoutTo = layoutFrom.superview } // create layout constraint let layoutConstraint = LayoutConstraint( item: layoutFrom, attribute: layoutFromAttribute, relatedBy: layoutRelation, toItem: layoutTo, attribute: layoutToAttribute, multiplier: self.multiplier.constraintMultiplierTargetValue, constant: layoutConstant ) // set label layoutConstraint.label = self.label // set priority layoutConstraint.priority = self.priority.constraintPriorityTargetValue // set constraint layoutConstraint.constraint = self // append self.layoutConstraints.append(layoutConstraint) } } // MARK: Public @available(*, deprecated: 3.0, message: "Use activate().") public func install() { self.activate() } @available(*, deprecated: 3.0, message: "Use deactivate().") public func uninstall() { self.deactivate() } public func activate() { self.activateIfNeeded() } public func deactivate() { self.deactivateIfNeeded() } @discardableResult public func update(offset: ConstraintOffsetTarget) -> Constraint { self.constant = offset.constraintOffsetTargetValue return self } @discardableResult public func update(inset: ConstraintInsetTarget) -> Constraint { self.constant = inset.constraintInsetTargetValue return self } @discardableResult public func update(priority: ConstraintPriorityTarget) -> Constraint { self.priority = priority.constraintPriorityTargetValue return self } @available(*, deprecated: 3.0, message: "Use update(offset: ConstraintOffsetTarget) instead.") public func updateOffset(amount: ConstraintOffsetTarget) { self.update(offset: amount) } @available(*, deprecated: 3.0, message: "Use update(inset: ConstraintInsetTarget) instead.") public func updateInsets(amount: ConstraintInsetTarget) { self.update(inset: amount) } @available(*, deprecated: 3.0, message: "Use update(priority: ConstraintPriorityTarget) instead.") public func updatePriority(amount: ConstraintPriorityTarget) { self.update(priority: amount) } @available(*, obsoleted: 3.0, message: "Use update(priority: ConstraintPriorityTarget) instead.") public func updatePriorityRequired() {} @available(*, obsoleted: 3.0, message: "Use update(priority: ConstraintPriorityTarget) instead.") public func updatePriorityHigh() { fatalError("Must be implemented by Concrete subclass.") } @available(*, obsoleted: 3.0, message: "Use update(priority: ConstraintPriorityTarget) instead.") public func updatePriorityMedium() { fatalError("Must be implemented by Concrete subclass.") } @available(*, obsoleted: 3.0, message: "Use update(priority: ConstraintPriorityTarget) instead.") public func updatePriorityLow() { fatalError("Must be implemented by Concrete subclass.") } // MARK: Internal internal func updateConstantAndPriorityIfNeeded() { for layoutConstraint in self.layoutConstraints { let attribute = (layoutConstraint.secondAttribute == .notAnAttribute) ? layoutConstraint.firstAttribute : layoutConstraint.secondAttribute layoutConstraint.constant = self.constant.constraintConstantTargetValueFor(layoutAttribute: attribute) let requiredPriority = ConstraintPriority.required.value if layoutConstraint.priority < requiredPriority, (self.priority.constraintPriorityTargetValue != requiredPriority) { layoutConstraint.priority = self.priority.constraintPriorityTargetValue } } } internal func activateIfNeeded(updatingExisting: Bool = false) { guard let item = self.from.layoutConstraintItem else { print("WARNING: SnapKit failed to get from item from constraint. Activate will be a no-op.") return } let layoutConstraints = self.layoutConstraints if updatingExisting { var existingLayoutConstraints: [LayoutConstraint] = [] for constraint in item.constraints { existingLayoutConstraints += constraint.layoutConstraints } for layoutConstraint in layoutConstraints { let existingLayoutConstraint = existingLayoutConstraints.first { $0 == layoutConstraint } guard let updateLayoutConstraint = existingLayoutConstraint else { fatalError("Updated constraint could not find existing matching constraint to update: \(layoutConstraint)") } let updateLayoutAttribute = (updateLayoutConstraint.secondAttribute == .notAnAttribute) ? updateLayoutConstraint.firstAttribute : updateLayoutConstraint.secondAttribute updateLayoutConstraint.constant = self.constant.constraintConstantTargetValueFor(layoutAttribute: updateLayoutAttribute) } } else { NSLayoutConstraint.activate(layoutConstraints) item.add(constraints: [self]) } } internal func deactivateIfNeeded() { guard let item = self.from.layoutConstraintItem else { print("WARNING: SnapKit failed to get from item from constraint. Deactivate will be a no-op.") return } let layoutConstraints = self.layoutConstraints NSLayoutConstraint.deactivate(layoutConstraints) item.remove(constraints: [self]) } }
mit
7432d39edd4aef63c0eeb4a3939d3f9a
39.185567
184
0.617154
6
false
false
false
false
devxoul/Drrrible
DrrribleTests/Sources/Views/ShotViewImageCellSpec.swift
1
610
// // ShotViewImageCellSpec.swift // Drrrible // // Created by Suyeol Jeon on 10/09/2017. // Copyright © 2017 Suyeol Jeon. All rights reserved. // import Quick import Nimble @testable import Drrrible final class ShotViewImageCellSpec: QuickSpec { override func spec() { var reactor: ShotViewImageCellReactor! var cell: ShotViewImageCell! beforeEach { reactor = ShotViewImageCellReactor(shot: ShotFixture.shot1) reactor.isStubEnabled = true cell = ShotViewImageCell() } it("has subviews") { expect(cell.imageView.superview) == cell.contentView } } }
mit
e6a31c119c44c95c26b7431b2b215672
20.75
65
0.696223
3.903846
false
false
false
false
Tj3n/TVNExtensions
UIKit/UIViewController+KeyboardHandling.swift
1
6229
// // UIViewController+KeyboardHandling.swift // TVNExtensions // // Created by Tien Nhat Vu on 7/23/18. // import Foundation import UIKit extension UIViewController { private struct AssociatedKeys { static var _keyboardHeightKey = "com.tvn.keyboardHeightKey" static var _isKeyboardShowKey = "com.tvn.isKeyboardShowKey" static var _keyboardAddedHeightKey = "com.tvn.keyboardAddedHeightKey" static var _keyboardHandleKey = "com.tvn.keyboardHandleKey" static var _keyboardDurationKey = "com.tvn.keyboardDurationKey" static var _keyboardKeyframeAnimationOptionKey = "com.tvn.keyboardKeyframeAnimationOptionKey" } /// Full size of keyboard height public private(set) var _keyboardHeight: CGFloat { get { return getAssociatedObject(key: &AssociatedKeys._keyboardHeightKey, type: CGFloat.self) ?? 0 } set(newValue) { setAssociatedObject(key: &AssociatedKeys._keyboardHeightKey, value: newValue) } } /// Check if keyboard is showing public private(set) var _isKeyboardShow: Bool { get { return getAssociatedObject(key: &AssociatedKeys._isKeyboardShowKey, type: Bool.self) ?? false } set(newValue) { setAssociatedObject(key: &AssociatedKeys._isKeyboardShowKey, value: newValue) } } /// Changed keyboard height from the last handler call public private(set) var _keyboardAddedHeight: CGFloat { get { return getAssociatedObject(key: &AssociatedKeys._keyboardAddedHeightKey, type: CGFloat.self) ?? 0 } set(newValue) { setAssociatedObject(key: &AssociatedKeys._keyboardAddedHeightKey, value: newValue) } } /// Duration of the animation public private(set) var _keyboardDuration: Double { get { return getAssociatedObject(key: &AssociatedKeys._keyboardDurationKey, type: Double.self) ?? 0 } set(newValue) { setAssociatedObject(key: &AssociatedKeys._keyboardDurationKey, value: newValue) } } /// Use with `UIView.animateKeyframes` for smoother animation public private(set) var _keyboardKeyframeAnimationOption: UIView.KeyframeAnimationOptions { get { guard let rawValue = getAssociatedObject(key: &AssociatedKeys._keyboardKeyframeAnimationOptionKey, type: UInt.self) else { return UIView.KeyframeAnimationOptions.calculationModeLinear } return UIView.KeyframeAnimationOptions(rawValue: rawValue) } set(newValue) { setAssociatedObject(key: &AssociatedKeys._keyboardKeyframeAnimationOptionKey, value: newValue.rawValue) } } private var _handleAction: HandlingClosure? { get { guard let store = getAssociatedObject(key: &AssociatedKeys._keyboardHandleKey, type: ActionStore.self) else { return nil } return store.action } set(newValue) { guard let newValue = newValue else { return } setAssociatedObject(key: &AssociatedKeys._keyboardHandleKey, value: ActionStore(newValue)) } } private class ActionStore: NSObject { let action: HandlingClosure init(_ action: @escaping HandlingClosure) { self.action = action } } /// Self handle keyboard event, from iOS 9 there's no need of remove observer manually in dealloc/deinit /// /// - Parameter handler: Must use [unowned self], Closure parametters: /// ``` /// (_ up: Bool, _ height: CGFloat, _ duration: Double) -> () /// ``` public func observeKeyboardEvent(handler: @escaping HandlingClosure) { _keyboardHeight = 0 _isKeyboardShow = false _keyboardAddedHeight = 0 _handleAction = handler NotificationCenter.default.addObserver(self, selector: #selector(keyboardOnScreen(_:)), name: UIResponder.keyboardWillShowNotification, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(keyboardOnScreen(_:)), name: UIResponder.keyboardDidShowNotification, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(keyboardOffScreen(_:)), name: UIResponder.keyboardWillHideNotification, object: nil) } /// Before iOS 9 have to remove observer during dealloc/deinit public func removeKeyboardEventObserver() { NotificationCenter.default.removeObserver(self, name: UIResponder.keyboardWillShowNotification, object: nil) NotificationCenter.default.removeObserver(self, name: UIResponder.keyboardDidShowNotification, object: nil) NotificationCenter.default.removeObserver(self, name: UIResponder.keyboardWillHideNotification, object: nil) } @objc private func keyboardOnScreen(_ notification: Notification) { _keyboardHeight = (notification.userInfo![UIResponder.keyboardFrameEndUserInfoKey]! as AnyObject).cgRectValue.size.height _keyboardDuration = (notification.userInfo![UIResponder.keyboardAnimationDurationUserInfoKey]! as! NSNumber).doubleValue let curve = notification.userInfo![UIResponder.keyboardAnimationCurveUserInfoKey] as! UInt _keyboardKeyframeAnimationOption = UIView.KeyframeAnimationOptions(rawValue: curve) if _keyboardHeight == _keyboardAddedHeight || _keyboardHeight <= 0 { return } _keyboardAddedHeight = _keyboardHeight - _keyboardAddedHeight _handleAction?(true, _keyboardAddedHeight, _keyboardDuration) _keyboardAddedHeight = _keyboardHeight _isKeyboardShow = true } @objc private func keyboardOffScreen(_ notification: Notification) { _keyboardDuration = (notification.userInfo![UIResponder.keyboardAnimationDurationUserInfoKey]! as! NSNumber).doubleValue let curve = notification.userInfo![UIResponder.keyboardAnimationCurveUserInfoKey] as! UInt _keyboardKeyframeAnimationOption = UIView.KeyframeAnimationOptions(rawValue: curve) guard _isKeyboardShow else { return } _handleAction?(false, _keyboardHeight, _keyboardDuration) _keyboardHeight = 0 _keyboardAddedHeight = 0 _isKeyboardShow = false } }
mit
f7aad31963e273ac8eb30a65b1791124
46.915385
157
0.697062
5.278814
false
false
false
false
RoverPlatform/rover-ios
Sources/Data/EventQueue/EventQueue.swift
1
11598
// // EventQueue.swift // RoverData // // Created by Sean Rucker on 2017-09-01. // Copyright © 2017 Rover Labs Inc. All rights reserved. // import os.log import UIKit public class EventQueue { let client: EventsClient let flushAt: Int let flushInterval: Double let maxBatchSize: Int let maxQueueSize: Int // swiftlint:disable:next implicitly_unwrapped_optional // Use an implicitly unwrapped optional to allow circular dependency injection var contextProvider: ContextProvider! let serialQueue: Foundation.OperationQueue = { let q = Foundation.OperationQueue() q.maxConcurrentOperationCount = 1 return q }() struct WeakObserver { private(set) weak var value: EventQueueObserver? init(_ value: EventQueueObserver) { self.value = value } } var observers = [WeakObserver]() // The following variables comprise the state of the EventQueueService and should only be modified from within an operation on the serial queue var eventQueue = [Event]() var uploadTask: URLSessionTask? var timer: Timer? var backgroundTask = UIBackgroundTaskIdentifier.invalid var cache: URL? { return FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask).first?.appendingPathComponent("events").appendingPathExtension("plist") } var didBecomeActiveObserver: NSObjectProtocol? var willResignActiveObserver: NSObjectProtocol? var didEnterBackgroundObserver: NSObjectProtocol? init(client: EventsClient, flushAt: Int, flushInterval: Double, maxBatchSize: Int, maxQueueSize: Int) { self.client = client self.flushAt = flushAt self.flushInterval = flushInterval self.maxBatchSize = maxBatchSize self.maxQueueSize = maxQueueSize } public func restore() { restoreEvents() self.didBecomeActiveObserver = NotificationCenter.default.addObserver(forName: UIApplication.didBecomeActiveNotification, object: nil, queue: OperationQueue.main) { [weak self] _ in self?.startTimer() } self.willResignActiveObserver = NotificationCenter.default.addObserver(forName: UIApplication.willResignActiveNotification, object: nil, queue: OperationQueue.main) { [weak self] _ in self?.stopTimer() } self.didEnterBackgroundObserver = NotificationCenter.default.addObserver(forName: UIApplication.didEnterBackgroundNotification, object: nil, queue: OperationQueue.main) { [weak self] _ in self?.beginBackgroundTask() self?.flushEvents() } if UIApplication.shared.applicationState == .active { self.startTimer() } } deinit { self.stopTimer() if let didBecomeActiveObserver = self.didBecomeActiveObserver { NotificationCenter.default.removeObserver(didBecomeActiveObserver) } if let willResignActiveObserver = self.willResignActiveObserver { NotificationCenter.default.removeObserver(willResignActiveObserver) } if let didEnterBackgroundObserver = self.didEnterBackgroundObserver { NotificationCenter.default.removeObserver(didEnterBackgroundObserver) } } func restoreEvents() { serialQueue.addOperation { os_log("Restoring events from cache...", log: .events, type: .debug) guard let cache = self.cache else { os_log("Cache not found", log: .events, type: .error) return } if !FileManager.default.fileExists(atPath: cache.path) { os_log("Cache is empty, no events to restore", log: .events, type: .debug) return } do { let data = try Data(contentsOf: cache) self.eventQueue = try PropertyListDecoder().decode([Event].self, from: data) os_log("%d event(s) restored from cache", log: .events, type: .debug, self.eventQueue.count) } catch { os_log("Failed to restore events from cache: %@", log: .events, type: .error, error.logDescription) } } } public func addEvent(_ info: EventInfo) { let context = self.contextProvider.context serialQueue.addOperation { if self.eventQueue.count == self.maxQueueSize { os_log("Event queue is at capacity (%d) – removing oldest event", log: .events, type: .debug, self.maxQueueSize) self.eventQueue.remove(at: 0) } let event = Event( name: info.name, context: context, namespace: info.namespace, attributes: info.attributes, timestamp: info.timestamp ?? Date() ) self.eventQueue.append(event) os_log("Added event to queue: %@", log: .events, type: .debug, event.name) os_log("Queue now contains %d event(s)", log: .events, type: .debug, self.eventQueue.count) } persistEvents() let onMainThread: (() -> Void) -> Void = { block in if Thread.isMainThread { block() } else { DispatchQueue.main.sync { block() } } } onMainThread { if UIApplication.shared.applicationState == .active { flushEvents(minBatchSize: flushAt) } else { flushEvents() } } observers.compactMap { $0.value }.forEach { $0.eventQueue(self, didAddEvent: info) } } func persistEvents() { serialQueue.addOperation { os_log("Persisting events to cache...", log: .events, type: .debug) guard let cache = self.cache else { os_log("Cache not found", log: .events, type: .error) return } do { let encoder = PropertyListEncoder() encoder.outputFormat = .xml let data = try encoder.encode(self.eventQueue) try data.write(to: cache, options: [.atomic]) os_log("Cache now contains %d event(s)", log: .events, type: .debug, self.eventQueue.count) } catch { os_log("Failed to persist events to cache: %@", log: .events, type: .error, error.logDescription) } } } public func flush() { flushEvents() } struct FlushReponse: Decodable { struct Data: Decodable { var trackEvents: String } var data: Data } func flushEvents(minBatchSize: Int = 1) { // swiftlint:disable:next closure_body_length // TODO consider refactoring. serialQueue.addOperation { if self.uploadTask != nil { os_log("Skipping flush – already in progress", log: .events, type: .debug) return } if self.eventQueue.count < 1 { os_log("Skipping flush – no events in the queue", log: .events, type: .debug) return } if self.eventQueue.count < minBatchSize { os_log("Skipping flush – less than %d events in the queue", log: .events, type: .debug, minBatchSize) return } let events = Array(self.eventQueue.prefix(self.maxBatchSize)) os_log("Uploading %d event(s) to server", log: .events, type: .debug, events.count) let uploadTask = self.client.task(with: events) { result in switch result { case let .error(error, isRetryable): if let error = error { os_log("Failed to upload events: %@", log: .events, type: .error, error.logDescription) } if isRetryable { os_log("Will retry failed events", log: .events, type: .info) } else { os_log("Discarding failed events", log: .events, type: .info) self.removeEvents(events) } case .success(let data): do { _ = try JSONDecoder.default.decode(FlushReponse.self, from: data) os_log("Successfully uploaded %d event(s)", log: .events, type: .debug, events.count) self.removeEvents(events) } catch { os_log("Failed to upload events: %@", log: .events, type: .error, error.logDescription) os_log("Will retry failed events", log: .events, type: .info) } } self.uploadTask = nil self.endBackgroundTask() } uploadTask.resume() self.uploadTask = uploadTask } } func removeEvents(_ eventsToRemove: [Event]) { serialQueue.addOperation { self.eventQueue = self.eventQueue.filter { event in !eventsToRemove.contains { $0.id == event.id } } os_log("Removed %d event(s) from queue – queue now contains %d event(s)", log: .events, type: .debug, eventsToRemove.count, self.eventQueue.count) } persistEvents() } public func addObserver(_ observer: EventQueueObserver) { let weakRef = WeakObserver(observer) observers.append(weakRef) } } // MARK: Timer extension EventQueue { func startTimer() { self.stopTimer() guard self.flushInterval > 0.0 else { return } self.timer = Timer.scheduledTimer(withTimeInterval: self.flushInterval, repeats: true) { [weak self] _ in self?.flushEvents() } } func stopTimer() { guard let timer = self.timer else { return } timer.invalidate() self.timer = nil } } // MARK: Background task extension EventQueue { func beginBackgroundTask() { endBackgroundTask() serialQueue.addOperation { self.backgroundTask = UIApplication.shared.beginBackgroundTask { self.serialQueue.cancelAllOperations() self.endBackgroundTask() } } } func endBackgroundTask() { serialQueue.addOperation { if self.backgroundTask != UIBackgroundTaskIdentifier.invalid { let taskIdentifier = UIBackgroundTaskIdentifier(rawValue: self.backgroundTask.rawValue) UIApplication.shared.endBackgroundTask(taskIdentifier) self.backgroundTask = UIBackgroundTaskIdentifier.invalid } } } } // MARK: Screen Tracking public extension EventQueue { func trackScreenViewed(screenName: String, contentID: String? = nil, contentName: String? = nil) { self.addEvent( EventInfo(screenViewedWithName: screenName, contentID: contentID, contentName: contentName) ) } }
apache-2.0
8a82e6c80aa6090a33e9be08070c8af1
34.006042
195
0.558212
5.168153
false
false
false
false
laurentVeliscek/AudioKit
AudioKit/Common/MIDI/Sequencer/AKSequencer.swift
1
18120
// // AKSequencer.swift // AudioKit // // Created by Jeff Cooper, revision history on Github. // Copyright © 2016 AudioKit. All rights reserved. // import Foundation import AVFoundation /// Basic sequencer /// /// This is currently in transistion from old c core audio apis, to the more /// modern avaudiosequencer setup. However, the new system is not as advanced as the /// old, so we will keep both and have them interact. In addition, some of the features /// of the new AVAudioSequencer don't even work yet (midi sequencing). /// Still, both have their strengths and weaknesses so I am keeping them both. /// As such, there is some code hanging around while we iron it out. /// public class AKSequencer { /// Music sequence public var sequence: MusicSequence = nil /// Pointer to Music Sequence public var sequencePointer: UnsafeMutablePointer<MusicSequence> /// AVAudioSequencer - on hold while technology is still unstable public var avSequencer = AVAudioSequencer() /// Array of AudioKit Music Tracks public var tracks = [AKMusicTrack]() /// Array of AVMusicTracks public var avTracks: [AVMusicTrack] { if isAVSequencer { return avSequencer.tracks } else { //this won't do anything if not using an AVSeq print("AKSequencer ERROR ! avTracks only work if isAVSequencer ") let tracks = [AVMusicTrack]() return tracks } } /// Music Player var musicPlayer: MusicPlayer = nil /// Loop control public var loopEnabled: Bool = false /// Are we using the AVAudioEngineSequencer? public var isAVSequencer: Bool = false /// Sequencer Initialization public init() { NewMusicSequence(&sequence) sequencePointer = UnsafeMutablePointer<MusicSequence>(sequence) //setup and attach to musicplayer NewMusicPlayer(&musicPlayer) MusicPlayerSetSequence(musicPlayer, sequence) } /// Initialize the sequence with a MIDI file /// /// - parameter filename: Location of the MIDI File /// public convenience init(filename: String) { self.init() loadMIDIFile(filename) } /// Initialize the sequence with a midi file and audioengine - on hold while technology is still unstable /// /// - Parameters: /// - filename: Location of the MIDI File /// - engine: reference to the AV Audio Engine /// public convenience init(filename: String, engine: AVAudioEngine) { self.init() isAVSequencer = true avSequencer = AVAudioSequencer(audioEngine: engine) loadMIDIFile(filename) } /// Initialize the sequence with an empty sequence and audioengine /// (on hold while technology is still unstable) /// /// - parameter engine: reference to the AV Audio Engine /// public convenience init(engine: AVAudioEngine) { self.init() isAVSequencer = true avSequencer = AVAudioSequencer(audioEngine: engine) } /// Load a sequence from data /// /// - parameter data: data to create sequence from /// public func sequenceFromData(data: NSData) { let options = AVMusicSequenceLoadOptions.SMF_PreserveTracks do { try avSequencer.loadFromData(data, options: options) print("should have loaded new sequence data") } catch { print("cannot load from data \(error)") return } } /// Preroll for the music player public func preroll() { MusicPlayerPreroll(musicPlayer) } /// Set loop functionality of entire sequence public func toggleLoop() { (loopEnabled ? disableLooping() : enableLooping()) } /// Enable looping for all tracks - loops entire sequence public func enableLooping() { if isAVSequencer { for track in avSequencer.tracks { track.loopingEnabled = true track.loopRange = AVMakeBeatRange(0, self.length.beats) } } else { setLoopInfo(length, numberOfLoops: 0) } loopEnabled = true } /// Enable looping for all tracks with specified length /// /// - parameter loopLength: Loop length in beats /// public func enableLooping(loopLength: AKDuration) { if isAVSequencer { for track in avSequencer.tracks { track.loopingEnabled = true track.loopRange = AVMakeBeatRange(0, self.length.beats) } } else { setLoopInfo(loopLength, numberOfLoops: 0) } loopEnabled = true } /// Disable looping for all tracks public func disableLooping() { if isAVSequencer { for track in avSequencer.tracks { track.loopingEnabled = false } } else { setLoopInfo(AKDuration(beats: 0), numberOfLoops: 0) } loopEnabled = false } /// Set looping duration and count for all tracks /// /// - Parameters: /// - duration: Duration of the loop in beats /// - numberOfLoops: The number of time to repeat /// public func setLoopInfo(duration: AKDuration, numberOfLoops: Int) { if isAVSequencer { print("AKSequencer ERROR ! setLoopInfo only work if not isAVSequencer ") //nothing yet } else { for track in tracks { track.setLoopInfo(duration, numberOfLoops: numberOfLoops) } } loopEnabled = true } /// Set length of all tracks /// /// - parameter length: Length of tracks in beats /// public func setLength(length: AKDuration) { if isAVSequencer { for track in avSequencer.tracks { track.lengthInBeats = length.beats track.loopRange = AVMakeBeatRange(0, length.beats) } } else { for track in tracks { track.setLength(length) } let size: UInt32 = 0 var len = length.musicTimeStamp var tempoTrack: MusicTrack = nil MusicSequenceGetTempoTrack(sequence, &tempoTrack) MusicTrackSetProperty(tempoTrack, kSequenceTrackProperty_TrackLength, &len, size) } } /// Length of longest track in the sequence public var length: AKDuration { var length: MusicTimeStamp = 0 var tmpLength: MusicTimeStamp = 0 for track in tracks { tmpLength = track.length if tmpLength >= length { length = tmpLength } } if isAVSequencer { for track in avSequencer.tracks { tmpLength = track.lengthInBeats if tmpLength >= length { length = tmpLength } } } return AKDuration(beats: length, tempo: tempo) } /// Rate relative to the default tempo (BPM) of the track public var rate: Double? { get { if isAVSequencer { return Double(avSequencer.rate) } else { print("AKSequencer ERROR ! rate only work if isAVSequencer ") return nil } } set { if isAVSequencer { avSequencer.rate = Float(newValue!) } else { print("AKSequencer ERROR ! rate only work if isAVSequencer ") } } } /// Set the tempo of the sequencer public func setTempo(bpm: Double) { if isAVSequencer { return } let constrainedTempo = min(max(bpm, 10.0), 280.0) var tempoTrack: MusicTrack = nil MusicSequenceGetTempoTrack(sequence, &tempoTrack) if isPlaying { var currTime: MusicTimeStamp = 0 MusicPlayerGetTime(musicPlayer, &currTime) currTime = fmod(currTime, length.beats) MusicTrackNewExtendedTempoEvent(tempoTrack, currTime, constrainedTempo) } // Had to comment out this line and two below to make the synth arpeggiator work. Doing so brings back the "Invalid beat range or track is empty" error // if !isTempoTrackEmpty { MusicTrackClear(tempoTrack, 0, length.beats) // } MusicTrackNewExtendedTempoEvent(tempoTrack, 0, constrainedTempo) } /// Add a tempo change to the score /// /// - Parameters: /// - bpm: Tempo in beats per minute /// - position: Point in time in beats /// public func addTempoEventAt(tempo bpm: Double, position: AKDuration) { if isAVSequencer { print("AKSequencer ERROR ! addTempoEventAt only work if not isAVSequencer ") return } let constrainedTempo = min(max(bpm, 10.0), 280.0) var tempoTrack: MusicTrack = nil MusicSequenceGetTempoTrack(sequence, &tempoTrack) MusicTrackNewExtendedTempoEvent(tempoTrack, position.beats, constrainedTempo) } /// Tempo retrieved from the sequencer public var tempo: Double { var tempoOut: Double = 120.0 var tempoTrack: MusicTrack = nil MusicSequenceGetTempoTrack(sequence, &tempoTrack) var iterator: MusicEventIterator = nil NewMusicEventIterator(tempoTrack, &iterator) var eventTime: MusicTimeStamp = 0 var eventType: MusicEventType = kMusicEventType_ExtendedTempo var eventData: UnsafePointer<Void> = nil var eventDataSize: UInt32 = 0 var hasPreviousEvent: DarwinBoolean = false MusicEventIteratorSeek(iterator, currentPosition.beats) MusicEventIteratorHasPreviousEvent(iterator, &hasPreviousEvent) if hasPreviousEvent { MusicEventIteratorPreviousEvent(iterator) MusicEventIteratorGetEventInfo(iterator, &eventTime, &eventType, &eventData, &eventDataSize) if eventType == kMusicEventType_ExtendedTempo { let tempoEventPointer: UnsafePointer<ExtendedTempoEvent> = UnsafePointer(eventData) tempoOut = tempoEventPointer.memory.bpm } } return tempoOut } var isTempoTrackEmpty: Bool { var outBool = true var iterator: MusicEventIterator = nil var tempoTrack: MusicTrack = nil MusicSequenceGetTempoTrack(sequence, &tempoTrack) NewMusicEventIterator(tempoTrack, &iterator) var eventTime = MusicTimeStamp(0) var eventType = MusicEventType() var eventData: UnsafePointer<Void> = nil var eventDataSize: UInt32 = 0 var hasNextEvent: DarwinBoolean = false MusicEventIteratorHasCurrentEvent(iterator, &hasNextEvent) while(hasNextEvent) { MusicEventIteratorGetEventInfo(iterator, &eventTime, &eventType, &eventData, &eventDataSize) if eventType != 5 { outBool = true } MusicEventIteratorNextEvent(iterator) MusicEventIteratorHasCurrentEvent(iterator, &hasNextEvent) } return outBool } /// Convert seconds into AKDuration /// /// - parameter seconds: time in seconds /// public func duration(seconds seconds: Double) -> AKDuration { let sign = seconds > 0 ? 1.0 : -1.0 let absoluteValueSeconds = fabs(seconds) var outBeats = AKDuration(beats: MusicTimeStamp()) MusicSequenceGetBeatsForSeconds(sequence, Float64(absoluteValueSeconds), &(outBeats.beats)) outBeats.beats = outBeats.beats * sign return outBeats } /// Convert beats into seconds /// /// - parameter duration: AKDuration /// public func seconds(duration duration: AKDuration) -> Double { let sign = duration.beats > 0 ? 1.0 : -1.0 let absoluteValueBeats = fabs(duration.beats) var outSecs: Double = MusicTimeStamp() MusicSequenceGetSecondsForBeats(sequence, absoluteValueBeats, &outSecs) outSecs = outSecs * sign return outSecs } /// Play the sequence public func play() { if isAVSequencer { do { try avSequencer.start() } catch _ { print("could not start avSeq") } } else { MusicPlayerStart(musicPlayer) } } /// Stop the sequence public func stop() { if isAVSequencer { avSequencer.stop() } else { MusicPlayerStop(musicPlayer) } } /// Rewind the sequence public func rewind() { if isAVSequencer { avSequencer.currentPositionInBeats = 0 } else { MusicPlayerSetTime(musicPlayer, 0) } } /// Set the Audio Unit output for all tracks - on hold while technology is still unstable public func setGlobalAVAudioUnitOutput(audioUnit: AVAudioUnit) { if isAVSequencer { for track in avSequencer.tracks { track.destinationAudioUnit = audioUnit } } else { //do nothing - doesn't apply. In the old C-api, MusicTracks could point at AUNodes, but we don't use those print("AKSequencer ERROR ! setGlobalAVAudioUnitOutput only work if isAVSequencer ") } } /// Wheter or not the sequencer is currently playing public var isPlaying: Bool { if isAVSequencer { return avSequencer.playing } else { var isPlayingBool: DarwinBoolean = false MusicPlayerIsPlaying(musicPlayer, &isPlayingBool) return isPlayingBool.boolValue } } /// Current Time public var currentPosition: AKDuration { if isAVSequencer { return AKDuration(beats: avSequencer.currentPositionInBeats) } else { var currentTime = MusicTimeStamp() MusicPlayerGetTime(musicPlayer, &currentTime) let duration = AKDuration(beats: currentTime) return duration } } /// Track count public var trackCount: Int { if isAVSequencer { return avSequencer.tracks.count } else { var count: UInt32 = 0 MusicSequenceGetTrackCount(sequence, &count) return Int(count) } } /// Load a MIDI file public func loadMIDIFile(filename: String) { let bundle = NSBundle.mainBundle() let file = bundle.pathForResource(filename, ofType: "mid") let fileURL = NSURL.fileURLWithPath(file!) MusicSequenceFileLoad(sequence, fileURL, MusicSequenceFileTypeID.MIDIType, MusicSequenceLoadFlags.SMF_PreserveTracks) if isAVSequencer { do { try avSequencer.loadFromURL(fileURL, options: AVMusicSequenceLoadOptions.SMF_PreserveTracks) } catch _ { print("failed to load midi into avseq") } } initTracks() } /// Initialize all tracks /// /// Clears the AKMusicTrack array, and rebuilds it based on actual contents of music sequence /// func initTracks() { tracks.removeAll() var count: UInt32 = 0 MusicSequenceGetTrackCount(sequence, &count) for i in 0 ..< count { var musicTrack: MusicTrack = nil MusicSequenceGetIndTrack(sequence, UInt32(i), &musicTrack) tracks.append(AKMusicTrack(musicTrack: musicTrack, name: "InitializedTrack")) } } /// Get a new track public func newTrack(name: String = "Unnamed") -> AKMusicTrack? { if isAVSequencer { print("AKSequencer ERROR ! newTrack only work if not isAVSequencer ") return nil } var newMusicTrack: MusicTrack = nil MusicSequenceNewTrack(sequence, &newMusicTrack) var count: UInt32 = 0 MusicSequenceGetTrackCount(sequence, &count) tracks.append(AKMusicTrack(musicTrack: newMusicTrack, name: name)) //print("Calling initTracks() from newTrack") //initTracks() return tracks.last! } /// Clear some events from the track // /// - Parameters: /// - start: Starting position of clearing /// - duration: Length of time after the start position to clear /// public func clearRange(start start: AKDuration, duration: AKDuration) { if isAVSequencer { print("AKSequencer ERROR ! clearRange only work if not isAVSequencer ") return } for track in tracks { track.clearRange(start: start, duration: duration) } } /// Set the music player time directly /// /// - parameter time: Music time stamp to set /// public func setTime(time: MusicTimeStamp) { MusicPlayerSetTime(musicPlayer, time) } /// Generate NSData from the sequence public func genData() -> NSData? { var status = noErr var data: Unmanaged<CFData>? status = MusicSequenceFileCreateData(sequence, MusicSequenceFileTypeID.MIDIType, MusicSequenceFileFlags.EraseFile, 480, &data) if status != noErr { print("error creating MusicSequence Data") return nil } let ns: NSData = data!.takeUnretainedValue() data?.release() return ns } /// Print sequence to console public func debug() { if isAVSequencer { print("No debug information available for AVAudioEngine's sequencer.") } else { CAShow(sequencePointer) } } /// Set the midi output for all tracks public func setGlobalMIDIOutput(midiEndpoint: MIDIEndpointRef) { if isAVSequencer { for track in avSequencer.tracks { track.destinationMIDIEndpoint = midiEndpoint } } else { for track in tracks { track.setMIDIOutput(midiEndpoint) } } } }
mit
da4f68687a418f4a9e7a9caf0664df9c
31.125887
152
0.604338
4.783263
false
false
false
false
siutsin/STLLapTimer-Swift
LapTimer-Swift/Utility.swift
1
1862
// // Utility.swift // LapTimer-Swift // // Created by Simon Li on 4/9/14. // Copyright (c) 2014 Simon Li. All rights reserved. // import UIKit class Utility: NSObject { /*! * http://stackoverflow.com/a/24318861/837059 */ class func delay(delay:NSTimeInterval, closure:()->()) { dispatch_after( dispatch_time( DISPATCH_TIME_NOW, Int64(delay * Double(NSEC_PER_SEC)) ), dispatch_get_main_queue(), closure) } /*! * http://stackoverflow.com/a/25120393/837059 */ typealias dispatch_cancelable_closure = (cancel : Bool) -> () class func cancelableDelay(time:NSTimeInterval, closure:()->()) -> dispatch_cancelable_closure? { func dispatch_later(clsr:()->()) { dispatch_after( dispatch_time( DISPATCH_TIME_NOW, Int64(time * Double(NSEC_PER_SEC)) ), dispatch_get_main_queue(), clsr) } var closure:dispatch_block_t? = closure var cancelableClosure:dispatch_cancelable_closure? let delayedClosure:dispatch_cancelable_closure = { cancel in if let clsr = closure { if (cancel == false) { dispatch_async(dispatch_get_main_queue(), clsr); } } closure = nil cancelableClosure = nil } cancelableClosure = delayedClosure dispatch_later { if let delayedClosure = cancelableClosure { delayedClosure(cancel: false) } } return cancelableClosure; } class func cancelDelay(closure:dispatch_cancelable_closure?) { if closure != nil { closure!(cancel: true) } } }
mit
339aa736a48a77c165410885bf37a07a
26.382353
102
0.525242
4.586207
false
false
false
false
rnystrom/OneNews-Swift
OneNews/OneNews/Classes/View Controllers/HackerNewsController.swift
1
3789
// // HackerNewsController.swift // OneNews // // Created by Ryan Nystrom on 8/9/14. // Copyright (c) 2014 Ryan Nystrom. All rights reserved. // import UIKit let HackerNewsCellIdentifier = "HackerNewsCellIdentifier" class HackerNewsController: UITableViewController { override func viewDidLoad() { super.viewDidLoad() tableView.rowHeight = UITableViewAutomaticDimension; tableView.estimatedRowHeight = 100 tableView.contentInset = UIEdgeInsetsMake(0, 0, 50, 0) refreshControl = UIRefreshControl() refreshControl.addTarget(self, action: Selector("onRefresh:"), forControlEvents: .ValueChanged) onRefresh(self) } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) tabBarController.title = "Hacker News" } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) tableView.reloadData() } override func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator!) { super.viewWillTransitionToSize(size, withTransitionCoordinator: coordinator) tableView.reloadData() } // MARK: Custom Actionss func onRefresh(sender: AnyObject!) { DataStore.sharedStore.fetchHackerNewsFrontPage { self.refreshControl.endRefreshing() self.tableView.reloadData() } } func onCustomAccessoryTapped(sender: UIButton) { let indexPath = NSIndexPath(forRow: sender.tag, inSection: 0) let item = itemForIndexPath(indexPath) let comments = storyboard.instantiateViewControllerWithIdentifier("Comments") as CommentsController comments.item = item showDetailViewController(comments, sender: self) } func itemForIndexPath(indexPath: NSIndexPath) -> Post { return DataStore.sharedStore.hackerNewsItems![indexPath.row] } // MARK: UITableViewDataSource override func numberOfSectionsInTableView(tableView: UITableView!) -> Int { return 1 } override func tableView(tableView: UITableView!, numberOfRowsInSection section: Int) -> Int { if let items = DataStore.sharedStore.hackerNewsItems { return items.count } return 0 } override func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell! { let cell = tableView.dequeueReusableCellWithIdentifier(HackerNewsCellIdentifier, forIndexPath: indexPath) as HackerNewsCell configureCell(cell, indexPath: indexPath) return cell } func configureCell(cell: HackerNewsCell, indexPath: NSIndexPath) { let item = itemForIndexPath(indexPath) cell.titleLabel.text = item.title cell.authorLabel.text = item.author // ryan hacks code, and i dont care cell.commentButton.tag = indexPath.row cell.commentButton.addTarget(self, action: Selector("onCustomAccessoryTapped:"), forControlEvents: .TouchUpInside) let points = item.points as Int? cell.pointsLabel.text = "\(points!)" cell.commentsLabel.text = "\(item.totalComments)" } // MARK: UITableViewDelegate override func tableView(tableView: UITableView!, didSelectRowAtIndexPath indexPath: NSIndexPath!) { let item = itemForIndexPath(indexPath) let detail = storyboard.instantiateViewControllerWithIdentifier("Webview") as WebviewController detail.item = item showDetailViewController(detail, sender: self) } }
mit
d8aee6dc1606a9b665dac698e10b312f
31.663793
137
0.667458
5.697744
false
false
false
false
Erin-Mounts/BridgeAppSDK
BridgeAppSDK/SBASurveyFactory.swift
1
8155
// // SBASurveyFactory.swift // BridgeAppSDK // // Copyright © 2016 Sage Bionetworks. All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation and/or // other materials provided with the distribution. // // 3. Neither the name of the copyright holder(s) nor the names of any contributors // may be used to endorse or promote products derived from this software without // specific prior written permission. No license is granted to the trademarks of // the copyright holders even if such marks are included in this software. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // import ResearchKit /** * The purpose of the Survey Factory is to allow subclassing for custom types of steps * that are not recognized by this factory and to allow usage by Obj-c classes that * do not recognize protocol extensions. */ public class SBASurveyFactory : NSObject { public var steps: [ORKStep]? public override init() { super.init() } public convenience init?(jsonNamed: String) { guard let json = SBAResourceFinder().jsonNamed(jsonNamed) else { return nil } self.init(dictionary: json) } public convenience init(dictionary: NSDictionary) { self.init() self.mapSteps(dictionary) } func mapSteps(dictionary: NSDictionary) { if let steps = dictionary["steps"] as? [NSDictionary] { self.steps = steps.map({ self.createSurveyStepWithDictionary($0) }) } } /** * Factory method for creating a survey step with a dictionary */ public func createSurveyStepWithDictionary(dictionary: NSDictionary) -> ORKStep { return self.createSurveyStep(dictionary, isSubtaskStep: false) } /** * Factory method for creating a custom type of survey question that is not * defined by this class. Note: Only swift can subclass this method directly */ public func createSurveyStepWithCustomType(inputItem: SBASurveyItem) -> ORKStep { return inputItem.createCustomStep() } func createSurveyStep(inputItem: SBASurveyItem, isSubtaskStep: Bool) -> ORKStep { switch (inputItem.surveyItemType) { case .Instruction, .Completion: return inputItem.createInstructionStep() case .Subtask: return inputItem.createSubtaskStep(self) case .Form(_): return inputItem.createFormStep(isSubtaskStep) default: return self.createSurveyStepWithCustomType(inputItem) } } } extension SBASurveyItem { func createInstructionStep() -> ORKInstructionStep { var instructionStep: ORKInstructionStep! let learnMoreHTMLContent = self.learnMoreHTMLContent let nextIdentifier = self.nextIdentifier if case .Completion = self.surveyItemType { instructionStep = ORKInstructionStep.completionStep().copyWithIdentifier(self.identifier) } else if (nextIdentifier != nil) || (learnMoreHTMLContent != nil) { let step = SBADirectNavigationStep(identifier: self.identifier, nextStepIdentifier: nextIdentifier) step.learnMoreHTMLContent = learnMoreHTMLContent; instructionStep = step } else { instructionStep = ORKInstructionStep(identifier: self.identifier) } instructionStep.title = self.stepTitle instructionStep.text = self.prompt instructionStep.detailText = self.detailText instructionStep.image = self.image return instructionStep } func createSubtaskStep(factory:SBASurveyFactory) -> SBASubtaskStep { assert(self.items?.count > 0, "A subtask step requires items") let steps = self.items?.map({ factory.createSurveyStep($0 as! SBASurveyItem, isSubtaskStep: true) }) let step = self.usesNavigation() ? SBASurveySubtaskStep(surveyItem: self, steps: steps) : SBASubtaskStep(identifier: self.identifier, steps: steps) return step } func createFormStep(isSubtaskStep: Bool) -> ORKFormStep { let step = (!isSubtaskStep && self.usesNavigation()) ? SBASurveyFormStep(surveyItem: self) : ORKFormStep(identifier: self.identifier) if case SBASurveyItemType.Form(.Compound) = self.surveyItemType { step.formItems = self.items?.map({ ($0 as! SBASurveyItem).createFormItem($0.prompt) }) } else { step.formItems = [self.createFormItem(nil)] } step.title = self.stepTitle step.text = self.prompt step.optional = self.optional return step } func createFormItem(text: String?) -> ORKFormItem { let answerFormat = self.createAnswerFormat() if let rulePredicate = self.rulePredicate { // If there is a rule predicate then return a survey form item let formItem = SBASurveyFormItem(identifier: self.identifier, text: text, answerFormat: answerFormat, optional: self.optional) formItem.rulePredicate = rulePredicate return formItem } else { // Otherwise, return a form item return ORKFormItem(identifier: self.identifier, text: text, answerFormat: answerFormat, optional: self.optional) } } func createAnswerFormat() -> ORKAnswerFormat? { guard let subtype = self.surveyItemType.formSubtype() else { return nil } switch(subtype) { case .Boolean: return ORKBooleanAnswerFormat() case .SingleChoiceText, .MultipleChoiceText: guard let textChoices = self.items?.map({createTextChoice($0)}) else { return nil } let style: ORKChoiceAnswerStyle = (subtype == .SingleChoiceText) ? .SingleChoice : .MultipleChoice return ORKTextChoiceAnswerFormat(style: style, textChoices: textChoices) default: assertionFailure("Form item question type \(subtype) not implemented") return nil } } func createTextChoice(obj: AnyObject) -> ORKTextChoice { guard let textChoice = obj as? SBATextChoice else { assertionFailure("Passing object \(obj) does not match expected protocol SBATextChoice") return ORKTextChoice(text: "", detailText: nil, value: NSNull(), exclusive: false) } let text = textChoice.prompt ?? "\(textChoice.value)" return ORKTextChoice(text: text, detailText: textChoice.detailText, value: textChoice.value, exclusive: textChoice.exclusive) } func usesNavigation() -> Bool { if (self.skipIdentifier != nil) || (self.rulePredicate != nil) { return true } guard let items = self.items else { return false } for item in items { if let item = item as? SBASurveyItem, let _ = item.rulePredicate { return true } } return false } }
bsd-3-clause
b5dfafdcb4ae14240c8d4f2c1bc4c978
40.181818
138
0.66961
5.005525
false
false
false
false
kaojohnny/CoreStore
Sources/Observing/ListMonitor.swift
1
53536
// // ListMonitor.swift // CoreStore // // Copyright © 2015 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 #if USE_FRAMEWORKS import GCDKit #endif #if os(iOS) || os(watchOS) || os(tvOS) // MARK: - ListMonitor /** The `ListMonitor` monitors changes to a list of `NSManagedObject` instances. Observers that implement the `ListObserver` protocol may then register themselves to the `ListMonitor`'s `addObserver(_:)` method: ``` let monitor = CoreStore.monitorList( From(MyPersonEntity), Where("title", isEqualTo: "Engineer"), OrderBy(.Ascending("lastName")) ) monitor.addObserver(self) ``` The `ListMonitor` instance needs to be held on (retained) for as long as the list needs to be observed. Observers registered via `addObserver(_:)` are not retained. `ListMonitor` only keeps a `weak` reference to all observers, thus keeping itself free from retain-cycles. Lists created with `monitorList(...)` keep a single-section list of objects, where each object can be accessed by index: ``` let firstPerson: MyPersonEntity = monitor[0] ``` Accessing the list with an index above the valid range will raise an exception. Creating a sectioned-list is also possible with the `monitorSectionedList(...)` method: ``` let monitor = CoreStore.monitorSectionedList( From(MyPersonEntity), SectionBy("age") { "Age \($0)" }, Where("title", isEqualTo: "Engineer"), OrderBy(.Ascending("lastName")) ) monitor.addObserver(self) ``` Objects from `ListMonitor`s created this way can be accessed either by an `NSIndexPath` or a tuple: ``` let indexPath = NSIndexPath(forItem: 3, inSection: 2) let person1 = monitor[indexPath] let person2 = monitor[2, 3] ``` In the example above, both `person1` and `person2` will contain the object at section=2, index=3. */ public final class ListMonitor<T: NSManagedObject>: Hashable { // MARK: Public (Accessors) /** Returns the object at the given index within the first section. This subscript indexer is typically used for `ListMonitor`s created with `monitorList(_:)`. - parameter index: the index of the object. Using an index above the valid range will raise an exception. - returns: the `NSManagedObject` at the specified index */ public subscript(index: Int) -> T { return self.objectsInAllSections()[index] } /** Returns the object at the given index, or `nil` if out of bounds. This subscript indexer is typically used for `ListMonitor`s created with `monitorList(_:)`. - parameter index: the index for the object. Using an index above the valid range will return `nil`. - returns: the `NSManagedObject` at the specified index, or `nil` if out of bounds */ public subscript(safeIndex index: Int) -> T? { let objects = self.objectsInAllSections() guard objects.indices.contains(index) else { return nil } return objects[index] } /** Returns the object at the given `sectionIndex` and `itemIndex`. This subscript indexer is typically used for `ListMonitor`s created with `monitorSectionedList(_:)`. - parameter sectionIndex: the section index for the object. Using a `sectionIndex` with an invalid range will raise an exception. - parameter itemIndex: the index for the object within the section. Using an `itemIndex` with an invalid range will raise an exception. - returns: the `NSManagedObject` at the specified section and item index */ public subscript(sectionIndex: Int, itemIndex: Int) -> T { return self[NSIndexPath(indexes: [sectionIndex, itemIndex], length: 2)] } /** Returns the object at the given section and item index, or `nil` if out of bounds. This subscript indexer is typically used for `ListMonitor`s created with `monitorSectionedList(_:)`. - parameter sectionIndex: the section index for the object. Using a `sectionIndex` with an invalid range will return `nil`. - parameter itemIndex: the index for the object within the section. Using an `itemIndex` with an invalid range will return `nil`. - returns: the `NSManagedObject` at the specified section and item index, or `nil` if out of bounds */ public subscript(safeSectionIndex sectionIndex: Int, safeItemIndex itemIndex: Int) -> T? { guard let section = self.sectionInfoAtIndex(safeSectionIndex: sectionIndex) else { return nil } guard itemIndex >= 0 && itemIndex < section.numberOfObjects else { return nil } return section.objects?[itemIndex] as? T } /** Returns the object at the given `NSIndexPath`. This subscript indexer is typically used for `ListMonitor`s created with `monitorSectionedList(_:)`. - parameter indexPath: the `NSIndexPath` for the object. Using an `indexPath` with an invalid range will raise an exception. - returns: the `NSManagedObject` at the specified index path */ public subscript(indexPath: NSIndexPath) -> T { CoreStore.assert( !self.isPendingRefetch || NSThread.isMainThread(), "Attempted to access a \(cs_typeName(self)) outside the main thread while a refetch is in progress." ) return self.fetchedResultsController.objectAtIndexPath(indexPath) as! T } /** Returns the object at the given `NSIndexPath`, or `nil` if out of bounds. This subscript indexer is typically used for `ListMonitor`s created with `monitorSectionedList(_:)`. - parameter indexPath: the `NSIndexPath` for the object. Using an `indexPath` with an invalid range will return `nil`. - returns: the `NSManagedObject` at the specified index path, or `nil` if out of bounds */ public subscript(safeIndexPath indexPath: NSIndexPath) -> T? { return self[ safeSectionIndex: indexPath.indexAtPosition(0), safeItemIndex: indexPath.indexAtPosition(1) ] } /** Checks if the `ListMonitor` has at least one section - returns: `true` if at least one section exists, `false` otherwise */ @warn_unused_result public func hasSections() -> Bool { return self.sections().count > 0 } /** Checks if the `ListMonitor` has at least one object in any section. - returns: `true` if at least one object in any section exists, `false` otherwise */ @warn_unused_result public func hasObjects() -> Bool { return self.numberOfObjects() > 0 } /** Checks if the `ListMonitor` has at least one object the specified section. - parameter section: the section index. Using an index outside the valid range will return `false`. - returns: `true` if at least one object in the specified section exists, `false` otherwise */ @warn_unused_result public func hasObjectsInSection(section: Int) -> Bool { return self.numberOfObjectsInSection(safeSectionIndex: section) > 0 } /** Returns all objects in all sections - returns: all objects in all sections */ @warn_unused_result public func objectsInAllSections() -> [T] { CoreStore.assert( !self.isPendingRefetch || NSThread.isMainThread(), "Attempted to access a \(cs_typeName(self)) outside the main thread while a refetch is in progress." ) return (self.fetchedResultsController.fetchedObjects as? [T]) ?? [] } /** Returns all objects in the specified section - parameter section: the section index. Using an index outside the valid range will raise an exception. - returns: all objects in the specified section */ @warn_unused_result public func objectsInSection(section: Int) -> [T] { return (self.sectionInfoAtIndex(section).objects as? [T]) ?? [] } /** Returns all objects in the specified section, or `nil` if out of bounds. - parameter section: the section index. Using an index outside the valid range will return `nil`. - returns: all objects in the specified section */ @warn_unused_result public func objectsInSection(safeSectionIndex section: Int) -> [T]? { return (self.sectionInfoAtIndex(safeSectionIndex: section)?.objects as? [T]) ?? [] } /** Returns the number of sections - returns: the number of sections */ @warn_unused_result public func numberOfSections() -> Int { CoreStore.assert( !self.isPendingRefetch || NSThread.isMainThread(), "Attempted to access a \(cs_typeName(self)) outside the main thread while a refetch is in progress." ) return self.fetchedResultsController.sections?.count ?? 0 } /** Returns the number of objects in all sections - returns: the number of objects in all sections */ @warn_unused_result public func numberOfObjects() -> Int { CoreStore.assert( !self.isPendingRefetch || NSThread.isMainThread(), "Attempted to access a \(cs_typeName(self)) outside the main thread while a refetch is in progress." ) return self.fetchedResultsController.fetchedObjects?.count ?? 0 } /** Returns the number of objects in the specified section - parameter section: the section index. Using an index outside the valid range will raise an exception. - returns: the number of objects in the specified section */ @warn_unused_result public func numberOfObjectsInSection(section: Int) -> Int { return self.sectionInfoAtIndex(section).numberOfObjects } /** Returns the number of objects in the specified section, or `nil` if out of bounds. - parameter section: the section index. Using an index outside the valid range will return `nil`. - returns: the number of objects in the specified section */ @warn_unused_result public func numberOfObjectsInSection(safeSectionIndex section: Int) -> Int? { return self.sectionInfoAtIndex(safeSectionIndex: section)?.numberOfObjects } /** Returns the `NSFetchedResultsSectionInfo` for the specified section - parameter section: the section index. Using an index outside the valid range will raise an exception. - returns: the `NSFetchedResultsSectionInfo` for the specified section */ @warn_unused_result public func sectionInfoAtIndex(section: Int) -> NSFetchedResultsSectionInfo { CoreStore.assert( !self.isPendingRefetch || NSThread.isMainThread(), "Attempted to access a \(cs_typeName(self)) outside the main thread while a refetch is in progress." ) return self.fetchedResultsController.sections![section] } /** Returns the `NSFetchedResultsSectionInfo` for the specified section, or `nil` if out of bounds. - parameter section: the section index. Using an index outside the valid range will return `nil`. - returns: the `NSFetchedResultsSectionInfo` for the specified section, or `nil` if the section index is out of bounds. */ @warn_unused_result public func sectionInfoAtIndex(safeSectionIndex section: Int) -> NSFetchedResultsSectionInfo? { CoreStore.assert( !self.isPendingRefetch || NSThread.isMainThread(), "Attempted to access a \(cs_typeName(self)) outside the main thread while a refetch is in progress." ) guard section >= 0 else { return nil } guard let sections = self.fetchedResultsController.sections where section < sections.count else { return nil } return sections[section] } /** Returns the `NSFetchedResultsSectionInfo`s for all sections - returns: the `NSFetchedResultsSectionInfo`s for all sections */ @warn_unused_result public func sections() -> [NSFetchedResultsSectionInfo] { CoreStore.assert( !self.isPendingRefetch || NSThread.isMainThread(), "Attempted to access a \(cs_typeName(self)) outside the main thread while a refetch is in progress." ) return self.fetchedResultsController.sections ?? [] } /** Returns the target section for a specified "Section Index" title and index. - parameter title: the title of the Section Index - parameter index: the index of the Section Index - returns: the target section for the specified "Section Index" title and index. */ @warn_unused_result public func targetSectionForSectionIndex(title title: String, index: Int) -> Int { CoreStore.assert( !self.isPendingRefetch || NSThread.isMainThread(), "Attempted to access a \(cs_typeName(self)) outside the main thread while a refetch is in progress." ) return self.fetchedResultsController.sectionForSectionIndexTitle(title, atIndex: index) } /** Returns the section index titles for all sections - returns: the section index titles for all sections */ @warn_unused_result public func sectionIndexTitles() -> [String] { CoreStore.assert( !self.isPendingRefetch || NSThread.isMainThread(), "Attempted to access a \(cs_typeName(self)) outside the main thread while a refetch is in progress." ) return self.fetchedResultsController.sectionIndexTitles } /** Returns the index of the `NSManagedObject` if it exists in the `ListMonitor`'s fetched objects, or `nil` if not found. - parameter object: the `NSManagedObject` to search the index of - returns: the index of the `NSManagedObject` if it exists in the `ListMonitor`'s fetched objects, or `nil` if not found. */ @warn_unused_result public func indexOf(object: T) -> Int? { CoreStore.assert( !self.isPendingRefetch || NSThread.isMainThread(), "Attempted to access a \(cs_typeName(self)) outside the main thread while a refetch is in progress." ) return (self.fetchedResultsController.fetchedObjects as? [T] ?? []).indexOf(object) } /** Returns the `NSIndexPath` of the `NSManagedObject` if it exists in the `ListMonitor`'s fetched objects, or `nil` if not found. - parameter object: the `NSManagedObject` to search the index of - returns: the `NSIndexPath` of the `NSManagedObject` if it exists in the `ListMonitor`'s fetched objects, or `nil` if not found. */ @warn_unused_result public func indexPathOf(object: T) -> NSIndexPath? { CoreStore.assert( !self.isPendingRefetch || NSThread.isMainThread(), "Attempted to access a \(cs_typeName(self)) outside the main thread while a refetch is in progress." ) return self.fetchedResultsController.indexPathForObject(object) } // MARK: Public (Observers) /** Registers a `ListObserver` to be notified when changes to the receiver's list occur. To prevent retain-cycles, `ListMonitor` only keeps `weak` references to its observers. For thread safety, this method needs to be called from the main thread. An assertion failure will occur (on debug builds only) if called from any thread other than the main thread. Calling `addObserver(_:)` multiple times on the same observer is safe, as `ListMonitor` unregisters previous notifications to the observer before re-registering them. - parameter observer: a `ListObserver` to send change notifications to */ public func addObserver<U: ListObserver where U.ListEntityType == T>(observer: U) { self.unregisterObserver(observer) self.registerObserver( observer, willChange: { (observer, monitor) in observer.listMonitorWillChange(monitor) }, didChange: { (observer, monitor) in observer.listMonitorDidChange(monitor) }, willRefetch: { (observer, monitor) in observer.listMonitorWillRefetch(monitor) }, didRefetch: { (observer, monitor) in observer.listMonitorDidRefetch(monitor) } ) } /** Registers a `ListObjectObserver` to be notified when changes to the receiver's list occur. To prevent retain-cycles, `ListMonitor` only keeps `weak` references to its observers. For thread safety, this method needs to be called from the main thread. An assertion failure will occur (on debug builds only) if called from any thread other than the main thread. Calling `addObserver(_:)` multiple times on the same observer is safe, as `ListMonitor` unregisters previous notifications to the observer before re-registering them. - parameter observer: a `ListObjectObserver` to send change notifications to */ public func addObserver<U: ListObjectObserver where U.ListEntityType == T>(observer: U) { self.unregisterObserver(observer) self.registerObserver( observer, willChange: { (observer, monitor) in observer.listMonitorWillChange(monitor) }, didChange: { (observer, monitor) in observer.listMonitorDidChange(monitor) }, willRefetch: { (observer, monitor) in observer.listMonitorWillRefetch(monitor) }, didRefetch: { (observer, monitor) in observer.listMonitorDidRefetch(monitor) } ) self.registerObserver( observer, didInsertObject: { (observer, monitor, object, toIndexPath) in observer.listMonitor(monitor, didInsertObject: object, toIndexPath: toIndexPath) }, didDeleteObject: { (observer, monitor, object, fromIndexPath) in observer.listMonitor(monitor, didDeleteObject: object, fromIndexPath: fromIndexPath) }, didUpdateObject: { (observer, monitor, object, atIndexPath) in observer.listMonitor(monitor, didUpdateObject: object, atIndexPath: atIndexPath) }, didMoveObject: { (observer, monitor, object, fromIndexPath, toIndexPath) in observer.listMonitor(monitor, didMoveObject: object, fromIndexPath: fromIndexPath, toIndexPath: toIndexPath) } ) } /** Registers a `ListSectionObserver` to be notified when changes to the receiver's list occur. To prevent retain-cycles, `ListMonitor` only keeps `weak` references to its observers. For thread safety, this method needs to be called from the main thread. An assertion failure will occur (on debug builds only) if called from any thread other than the main thread. Calling `addObserver(_:)` multiple times on the same observer is safe, as `ListMonitor` unregisters previous notifications to the observer before re-registering them. - parameter observer: a `ListSectionObserver` to send change notifications to */ public func addObserver<U: ListSectionObserver where U.ListEntityType == T>(observer: U) { self.unregisterObserver(observer) self.registerObserver( observer, willChange: { (observer, monitor) in observer.listMonitorWillChange(monitor) }, didChange: { (observer, monitor) in observer.listMonitorDidChange(monitor) }, willRefetch: { (observer, monitor) in observer.listMonitorWillRefetch(monitor) }, didRefetch: { (observer, monitor) in observer.listMonitorDidRefetch(monitor) } ) self.registerObserver( observer, didInsertObject: { (observer, monitor, object, toIndexPath) in observer.listMonitor(monitor, didInsertObject: object, toIndexPath: toIndexPath) }, didDeleteObject: { (observer, monitor, object, fromIndexPath) in observer.listMonitor(monitor, didDeleteObject: object, fromIndexPath: fromIndexPath) }, didUpdateObject: { (observer, monitor, object, atIndexPath) in observer.listMonitor(monitor, didUpdateObject: object, atIndexPath: atIndexPath) }, didMoveObject: { (observer, monitor, object, fromIndexPath, toIndexPath) in observer.listMonitor(monitor, didMoveObject: object, fromIndexPath: fromIndexPath, toIndexPath: toIndexPath) } ) self.registerObserver( observer, didInsertSection: { (observer, monitor, sectionInfo, toIndex) in observer.listMonitor(monitor, didInsertSection: sectionInfo, toSectionIndex: toIndex) }, didDeleteSection: { (observer, monitor, sectionInfo, fromIndex) in observer.listMonitor(monitor, didDeleteSection: sectionInfo, fromSectionIndex: fromIndex) } ) } /** Unregisters a `ListObserver` from receiving notifications for changes to the receiver's list. For thread safety, this method needs to be called from the main thread. An assertion failure will occur (on debug builds only) if called from any thread other than the main thread. - parameter observer: a `ListObserver` to unregister notifications to */ public func removeObserver<U: ListObserver where U.ListEntityType == T>(observer: U) { self.unregisterObserver(observer) } // MARK: Public (Refetching) /** Returns `true` if a call to `refetch(...)` was made to the `ListMonitor` and is currently waiting for the fetching to complete. Returns `false` otherwise. */ public private(set) var isPendingRefetch = false /** Asks the `ListMonitor` to refetch its objects using the specified series of `FetchClause`s. Note that this method does not execute the fetch immediately; the actual fetching will happen after the `NSFetchedResultsController`'s last `controllerDidChangeContent(_:)` notification completes. `refetch(...)` broadcasts `listMonitorWillRefetch(...)` to its observers immediately, and then `listMonitorDidRefetch(...)` after the new fetch request completes. - parameter fetchClauses: a series of `FetchClause` instances for fetching the object list. Accepts `Where`, `OrderBy`, and `Tweak` clauses. Note that only specified clauses will be changed; unspecified clauses will use previous values. */ public func refetch(fetchClauses: FetchClause...) { self.refetch(fetchClauses) } /** Asks the `ListMonitor` to refetch its objects using the specified series of `FetchClause`s. Note that this method does not execute the fetch immediately; the actual fetching will happen after the `NSFetchedResultsController`'s last `controllerDidChangeContent(_:)` notification completes. `refetch(...)` broadcasts `listMonitorWillRefetch(...)` to its observers immediately, and then `listMonitorDidRefetch(...)` after the new fetch request completes. - parameter fetchClauses: a series of `FetchClause` instances for fetching the object list. Accepts `Where`, `OrderBy`, and `Tweak` clauses. Note that only specified clauses will be changed; unspecified clauses will use previous values. */ public func refetch(fetchClauses: [FetchClause]) { self.refetch { (fetchRequest) in fetchClauses.forEach { $0.applyToFetchRequest(fetchRequest) } } } // MARK: Hashable public var hashValue: Int { return ObjectIdentifier(self).hashValue } // MARK: Internal internal convenience init(dataStack: DataStack, from: From<T>, sectionBy: SectionBy?, applyFetchClauses: (fetchRequest: NSFetchRequest) -> Void) { self.init( context: dataStack.mainContext, transactionQueue: dataStack.childTransactionQueue, from: from, sectionBy: sectionBy, applyFetchClauses: applyFetchClauses, createAsynchronously: nil ) } internal convenience init(dataStack: DataStack, from: From<T>, sectionBy: SectionBy?, applyFetchClauses: (fetchRequest: NSFetchRequest) -> Void, createAsynchronously: (ListMonitor<T>) -> Void) { self.init( context: dataStack.mainContext, transactionQueue: dataStack.childTransactionQueue, from: from, sectionBy: sectionBy, applyFetchClauses: applyFetchClauses, createAsynchronously: createAsynchronously ) } internal convenience init(unsafeTransaction: UnsafeDataTransaction, from: From<T>, sectionBy: SectionBy?, applyFetchClauses: (fetchRequest: NSFetchRequest) -> Void) { self.init( context: unsafeTransaction.context, transactionQueue: unsafeTransaction.transactionQueue, from: from, sectionBy: sectionBy, applyFetchClauses: applyFetchClauses, createAsynchronously: nil ) } internal convenience init(unsafeTransaction: UnsafeDataTransaction, from: From<T>, sectionBy: SectionBy?, applyFetchClauses: (fetchRequest: NSFetchRequest) -> Void, createAsynchronously: (ListMonitor<T>) -> Void) { self.init( context: unsafeTransaction.context, transactionQueue: unsafeTransaction.transactionQueue, from: from, sectionBy: sectionBy, applyFetchClauses: applyFetchClauses, createAsynchronously: createAsynchronously ) } internal func upcast() -> ListMonitor<NSManagedObject> { return unsafeBitCast(self, ListMonitor<NSManagedObject>.self) } internal func registerChangeNotification(notificationKey: UnsafePointer<Void>, name: String, toObserver observer: AnyObject, callback: (monitor: ListMonitor<T>) -> Void) { cs_setAssociatedRetainedObject( NotificationObserver( notificationName: name, object: self, closure: { [weak self] (note) -> Void in guard let `self` = self else { return } callback(monitor: self) } ), forKey: notificationKey, inObject: observer ) } internal func registerObjectNotification(notificationKey: UnsafePointer<Void>, name: String, toObserver observer: AnyObject, callback: (monitor: ListMonitor<T>, object: T, indexPath: NSIndexPath?, newIndexPath: NSIndexPath?) -> Void) { cs_setAssociatedRetainedObject( NotificationObserver( notificationName: name, object: self, closure: { [weak self] (note) -> Void in guard let `self` = self, let userInfo = note.userInfo, let object = userInfo[UserInfoKeyObject] as? T else { return } callback( monitor: self, object: object, indexPath: userInfo[UserInfoKeyIndexPath] as? NSIndexPath, newIndexPath: userInfo[UserInfoKeyNewIndexPath] as? NSIndexPath ) } ), forKey: notificationKey, inObject: observer ) } internal func registerSectionNotification(notificationKey: UnsafePointer<Void>, name: String, toObserver observer: AnyObject, callback: (monitor: ListMonitor<T>, sectionInfo: NSFetchedResultsSectionInfo, sectionIndex: Int) -> Void) { cs_setAssociatedRetainedObject( NotificationObserver( notificationName: name, object: self, closure: { [weak self] (note) -> Void in guard let `self` = self, let userInfo = note.userInfo, let sectionInfo = userInfo[UserInfoKeySectionInfo] as? NSFetchedResultsSectionInfo, let sectionIndex = (userInfo[UserInfoKeySectionIndex] as? NSNumber)?.integerValue else { return } callback( monitor: self, sectionInfo: sectionInfo, sectionIndex: sectionIndex ) } ), forKey: notificationKey, inObject: observer ) } internal func registerObserver<U: AnyObject>(observer: U, willChange: (observer: U, monitor: ListMonitor<T>) -> Void, didChange: (observer: U, monitor: ListMonitor<T>) -> Void, willRefetch: (observer: U, monitor: ListMonitor<T>) -> Void, didRefetch: (observer: U, monitor: ListMonitor<T>) -> Void) { CoreStore.assert( NSThread.isMainThread(), "Attempted to add an observer of type \(cs_typeName(observer)) outside the main thread." ) self.registerChangeNotification( &self.willChangeListKey, name: ListMonitorWillChangeListNotification, toObserver: observer, callback: { [weak observer] (monitor) -> Void in guard let observer = observer else { return } willChange(observer: observer, monitor: monitor) } ) self.registerChangeNotification( &self.didChangeListKey, name: ListMonitorDidChangeListNotification, toObserver: observer, callback: { [weak observer] (monitor) -> Void in guard let observer = observer else { return } didChange(observer: observer, monitor: monitor) } ) self.registerChangeNotification( &self.willRefetchListKey, name: ListMonitorWillRefetchListNotification, toObserver: observer, callback: { [weak observer] (monitor) -> Void in guard let observer = observer else { return } willRefetch(observer: observer, monitor: monitor) } ) self.registerChangeNotification( &self.didRefetchListKey, name: ListMonitorDidRefetchListNotification, toObserver: observer, callback: { [weak observer] (monitor) -> Void in guard let observer = observer else { return } didRefetch(observer: observer, monitor: monitor) } ) } internal func registerObserver<U: AnyObject>(observer: U, didInsertObject: (observer: U, monitor: ListMonitor<T>, object: T, toIndexPath: NSIndexPath) -> Void, didDeleteObject: (observer: U, monitor: ListMonitor<T>, object: T, fromIndexPath: NSIndexPath) -> Void, didUpdateObject: (observer: U, monitor: ListMonitor<T>, object: T, atIndexPath: NSIndexPath) -> Void, didMoveObject: (observer: U, monitor: ListMonitor<T>, object: T, fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) -> Void) { CoreStore.assert( NSThread.isMainThread(), "Attempted to add an observer of type \(cs_typeName(observer)) outside the main thread." ) self.registerObjectNotification( &self.didInsertObjectKey, name: ListMonitorDidInsertObjectNotification, toObserver: observer, callback: { [weak observer] (monitor, object, indexPath, newIndexPath) -> Void in guard let observer = observer else { return } didInsertObject( observer: observer, monitor: monitor, object: object, toIndexPath: newIndexPath! ) } ) self.registerObjectNotification( &self.didDeleteObjectKey, name: ListMonitorDidDeleteObjectNotification, toObserver: observer, callback: { [weak observer] (monitor, object, indexPath, newIndexPath) -> Void in guard let observer = observer else { return } didDeleteObject( observer: observer, monitor: monitor, object: object, fromIndexPath: indexPath! ) } ) self.registerObjectNotification( &self.didUpdateObjectKey, name: ListMonitorDidUpdateObjectNotification, toObserver: observer, callback: { [weak observer] (monitor, object, indexPath, newIndexPath) -> Void in guard let observer = observer else { return } didUpdateObject( observer: observer, monitor: monitor, object: object, atIndexPath: indexPath! ) } ) self.registerObjectNotification( &self.didMoveObjectKey, name: ListMonitorDidMoveObjectNotification, toObserver: observer, callback: { [weak observer] (monitor, object, indexPath, newIndexPath) -> Void in guard let observer = observer else { return } didMoveObject( observer: observer, monitor: monitor, object: object, fromIndexPath: indexPath!, toIndexPath: newIndexPath! ) } ) } internal func registerObserver<U: AnyObject>(observer: U, didInsertSection: (observer: U, monitor: ListMonitor<T>, sectionInfo: NSFetchedResultsSectionInfo, toIndex: Int) -> Void, didDeleteSection: (observer: U, monitor: ListMonitor<T>, sectionInfo: NSFetchedResultsSectionInfo, fromIndex: Int) -> Void) { CoreStore.assert( NSThread.isMainThread(), "Attempted to add an observer of type \(cs_typeName(observer)) outside the main thread." ) self.registerSectionNotification( &self.didInsertSectionKey, name: ListMonitorDidInsertSectionNotification, toObserver: observer, callback: { [weak observer] (monitor, sectionInfo, sectionIndex) -> Void in guard let observer = observer else { return } didInsertSection( observer: observer, monitor: monitor, sectionInfo: sectionInfo, toIndex: sectionIndex ) } ) self.registerSectionNotification( &self.didDeleteSectionKey, name: ListMonitorDidDeleteSectionNotification, toObserver: observer, callback: { [weak observer] (monitor, sectionInfo, sectionIndex) -> Void in guard let observer = observer else { return } didDeleteSection( observer: observer, monitor: monitor, sectionInfo: sectionInfo, fromIndex: sectionIndex ) } ) } internal func unregisterObserver(observer: AnyObject) { CoreStore.assert( NSThread.isMainThread(), "Attempted to remove an observer of type \(cs_typeName(observer)) outside the main thread." ) let nilValue: AnyObject? = nil cs_setAssociatedRetainedObject(nilValue, forKey: &self.willChangeListKey, inObject: observer) cs_setAssociatedRetainedObject(nilValue, forKey: &self.didChangeListKey, inObject: observer) cs_setAssociatedRetainedObject(nilValue, forKey: &self.willRefetchListKey, inObject: observer) cs_setAssociatedRetainedObject(nilValue, forKey: &self.didRefetchListKey, inObject: observer) cs_setAssociatedRetainedObject(nilValue, forKey: &self.didInsertObjectKey, inObject: observer) cs_setAssociatedRetainedObject(nilValue, forKey: &self.didDeleteObjectKey, inObject: observer) cs_setAssociatedRetainedObject(nilValue, forKey: &self.didUpdateObjectKey, inObject: observer) cs_setAssociatedRetainedObject(nilValue, forKey: &self.didMoveObjectKey, inObject: observer) cs_setAssociatedRetainedObject(nilValue, forKey: &self.didInsertSectionKey, inObject: observer) cs_setAssociatedRetainedObject(nilValue, forKey: &self.didDeleteSectionKey, inObject: observer) } internal func refetch(applyFetchClauses: (fetchRequest: NSFetchRequest) -> Void) { CoreStore.assert( NSThread.isMainThread(), "Attempted to refetch a \(cs_typeName(self)) outside the main thread." ) if !self.isPendingRefetch { self.isPendingRefetch = true NSNotificationCenter.defaultCenter().postNotificationName( ListMonitorWillRefetchListNotification, object: self ) } self.applyFetchClauses = applyFetchClauses self.taskGroup.notify(.Main) { [weak self] () -> Void in guard let `self` = self else { return } self.fetchedResultsControllerDelegate.enabled = false self.applyFetchClauses(fetchRequest: self.fetchedResultsController.fetchRequest) self.transactionQueue.async { [weak self] in guard let `self` = self else { return } try! self.fetchedResultsController.performFetchFromSpecifiedStores() GCDQueue.Main.async { [weak self] () -> Void in guard let `self` = self else { return } self.fetchedResultsControllerDelegate.enabled = true self.isPendingRefetch = false NSNotificationCenter.defaultCenter().postNotificationName( ListMonitorDidRefetchListNotification, object: self ) } } } } deinit { self.fetchedResultsControllerDelegate.fetchedResultsController = nil self.isPersistentStoreChanging = false } // MARK: Private private var willChangeListKey: Void? private var didChangeListKey: Void? private var willRefetchListKey: Void? private var didRefetchListKey: Void? private var didInsertObjectKey: Void? private var didDeleteObjectKey: Void? private var didUpdateObjectKey: Void? private var didMoveObjectKey: Void? private var didInsertSectionKey: Void? private var didDeleteSectionKey: Void? private let fetchedResultsController: CoreStoreFetchedResultsController private let fetchedResultsControllerDelegate: FetchedResultsControllerDelegate private let sectionIndexTransformer: (sectionName: KeyPath?) -> String? private var observerForWillChangePersistentStore: NotificationObserver! private var observerForDidChangePersistentStore: NotificationObserver! private let taskGroup = GCDGroup() private let transactionQueue: GCDQueue private var applyFetchClauses: (fetchRequest: NSFetchRequest) -> Void private var isPersistentStoreChanging: Bool = false { didSet { let newValue = self.isPersistentStoreChanging guard newValue != oldValue else { return } if newValue { self.taskGroup.enter() } else { self.taskGroup.leave() } } } private init(context: NSManagedObjectContext, transactionQueue: GCDQueue, from: From<T>, sectionBy: SectionBy?, applyFetchClauses: (fetchRequest: NSFetchRequest) -> Void, createAsynchronously: ((ListMonitor<T>) -> Void)?) { let fetchRequest = CoreStoreFetchRequest() fetchRequest.fetchLimit = 0 fetchRequest.resultType = .ManagedObjectResultType fetchRequest.fetchBatchSize = 20 fetchRequest.includesPendingChanges = false fetchRequest.shouldRefreshRefetchedObjects = true let fetchedResultsController = CoreStoreFetchedResultsController( context: context, fetchRequest: fetchRequest, from: from, sectionBy: sectionBy, applyFetchClauses: applyFetchClauses ) let fetchedResultsControllerDelegate = FetchedResultsControllerDelegate() self.fetchedResultsController = fetchedResultsController self.fetchedResultsControllerDelegate = fetchedResultsControllerDelegate if let sectionIndexTransformer = sectionBy?.sectionIndexTransformer { self.sectionIndexTransformer = sectionIndexTransformer } else { self.sectionIndexTransformer = { $0 } } self.transactionQueue = transactionQueue self.applyFetchClauses = applyFetchClauses fetchedResultsControllerDelegate.handler = self fetchedResultsControllerDelegate.fetchedResultsController = fetchedResultsController guard let coordinator = context.parentStack?.coordinator else { return } self.observerForWillChangePersistentStore = NotificationObserver( notificationName: NSPersistentStoreCoordinatorStoresWillChangeNotification, object: coordinator, queue: NSOperationQueue.mainQueue(), closure: { [weak self] (note) -> Void in guard let `self` = self else { return } self.isPersistentStoreChanging = true guard let removedStores = (note.userInfo?[NSRemovedPersistentStoresKey] as? [NSPersistentStore]).flatMap(Set.init) where !Set(self.fetchedResultsController.fetchRequest.affectedStores ?? []).intersect(removedStores).isEmpty else { return } self.refetch(self.applyFetchClauses) } ) self.observerForDidChangePersistentStore = NotificationObserver( notificationName: NSPersistentStoreCoordinatorStoresDidChangeNotification, object: coordinator, queue: NSOperationQueue.mainQueue(), closure: { [weak self] (note) -> Void in guard let `self` = self else { return } if !self.isPendingRefetch { let previousStores = Set(self.fetchedResultsController.fetchRequest.affectedStores ?? []) let currentStores = previousStores .subtract(note.userInfo?[NSRemovedPersistentStoresKey] as? [NSPersistentStore] ?? []) .union(note.userInfo?[NSAddedPersistentStoresKey] as? [NSPersistentStore] ?? []) if previousStores != currentStores { self.refetch(self.applyFetchClauses) } } self.isPersistentStoreChanging = false } ) if let createAsynchronously = createAsynchronously { transactionQueue.async { try! fetchedResultsController.performFetchFromSpecifiedStores() self.taskGroup.notify(.Main) { createAsynchronously(self) } } } else { try! fetchedResultsController.performFetchFromSpecifiedStores() } } } // MARK: - ListMonitor: Equatable @warn_unused_result public func == <T: NSManagedObject>(lhs: ListMonitor<T>, rhs: ListMonitor<T>) -> Bool { return lhs === rhs } @warn_unused_result public func == <T: NSManagedObject, U: NSManagedObject>(lhs: ListMonitor<T>, rhs: ListMonitor<U>) -> Bool { return lhs.fetchedResultsController === rhs.fetchedResultsController } @warn_unused_result public func ~= <T: NSManagedObject>(lhs: ListMonitor<T>, rhs: ListMonitor<T>) -> Bool { return lhs === rhs } @warn_unused_result public func ~= <T: NSManagedObject, U: NSManagedObject>(lhs: ListMonitor<T>, rhs: ListMonitor<U>) -> Bool { return lhs.fetchedResultsController === rhs.fetchedResultsController } extension ListMonitor: Equatable { } // MARK: - ListMonitor: FetchedResultsControllerHandler extension ListMonitor: FetchedResultsControllerHandler { // MARK: FetchedResultsControllerHandler internal func controller(controller: NSFetchedResultsController, didChangeObject anObject: AnyObject, atIndexPath indexPath: NSIndexPath?, forChangeType type: NSFetchedResultsChangeType, newIndexPath: NSIndexPath?) { switch type { case .Insert: NSNotificationCenter.defaultCenter().postNotificationName( ListMonitorDidInsertObjectNotification, object: self, userInfo: [ UserInfoKeyObject: anObject, UserInfoKeyNewIndexPath: newIndexPath! ] ) case .Delete: NSNotificationCenter.defaultCenter().postNotificationName( ListMonitorDidDeleteObjectNotification, object: self, userInfo: [ UserInfoKeyObject: anObject, UserInfoKeyIndexPath: indexPath! ] ) case .Update: NSNotificationCenter.defaultCenter().postNotificationName( ListMonitorDidUpdateObjectNotification, object: self, userInfo: [ UserInfoKeyObject: anObject, UserInfoKeyIndexPath: indexPath! ] ) case .Move: NSNotificationCenter.defaultCenter().postNotificationName( ListMonitorDidMoveObjectNotification, object: self, userInfo: [ UserInfoKeyObject: anObject, UserInfoKeyIndexPath: indexPath!, UserInfoKeyNewIndexPath: newIndexPath! ] ) } } internal func controller(controller: NSFetchedResultsController, didChangeSection sectionInfo: NSFetchedResultsSectionInfo, atIndex sectionIndex: Int, forChangeType type: NSFetchedResultsChangeType) { switch type { case .Insert: NSNotificationCenter.defaultCenter().postNotificationName( ListMonitorDidInsertSectionNotification, object: self, userInfo: [ UserInfoKeySectionInfo: sectionInfo, UserInfoKeySectionIndex: NSNumber(integer: sectionIndex) ] ) case .Delete: NSNotificationCenter.defaultCenter().postNotificationName( ListMonitorDidDeleteSectionNotification, object: self, userInfo: [ UserInfoKeySectionInfo: sectionInfo, UserInfoKeySectionIndex: NSNumber(integer: sectionIndex) ] ) default: break } } internal func controllerWillChangeContent(controller: NSFetchedResultsController) { self.taskGroup.enter() NSNotificationCenter.defaultCenter().postNotificationName( ListMonitorWillChangeListNotification, object: self ) } internal func controllerDidChangeContent(controller: NSFetchedResultsController) { NSNotificationCenter.defaultCenter().postNotificationName( ListMonitorDidChangeListNotification, object: self ) self.taskGroup.leave() } internal func controller(controller: NSFetchedResultsController, sectionIndexTitleForSectionName sectionName: String?) -> String? { return self.sectionIndexTransformer(sectionName: sectionName) } } // MARK: - Notification Keys private let ListMonitorWillChangeListNotification = "ListMonitorWillChangeListNotification" private let ListMonitorDidChangeListNotification = "ListMonitorDidChangeListNotification" private let ListMonitorWillRefetchListNotification = "ListMonitorWillRefetchListNotification" private let ListMonitorDidRefetchListNotification = "ListMonitorDidRefetchListNotification" private let ListMonitorDidInsertObjectNotification = "ListMonitorDidInsertObjectNotification" private let ListMonitorDidDeleteObjectNotification = "ListMonitorDidDeleteObjectNotification" private let ListMonitorDidUpdateObjectNotification = "ListMonitorDidUpdateObjectNotification" private let ListMonitorDidMoveObjectNotification = "ListMonitorDidMoveObjectNotification" private let ListMonitorDidInsertSectionNotification = "ListMonitorDidInsertSectionNotification" private let ListMonitorDidDeleteSectionNotification = "ListMonitorDidDeleteSectionNotification" private let UserInfoKeyObject = "UserInfoKeyObject" private let UserInfoKeyIndexPath = "UserInfoKeyIndexPath" private let UserInfoKeyNewIndexPath = "UserInfoKeyNewIndexPath" private let UserInfoKeySectionInfo = "UserInfoKeySectionInfo" private let UserInfoKeySectionIndex = "UserInfoKeySectionIndex" #endif
mit
8253c8106f5a50ac77ddcd9360c735fc
38.981329
499
0.608331
5.758309
false
false
false
false
fgulan/letter-ml
project/LetterML/Frameworks/framework/Source/Operations/CannyEdgeDetection.swift
9
2260
/** This applies the edge detection process described by John Canny in Canny, J., A Computational Approach To Edge Detection, IEEE Trans. Pattern Analysis and Machine Intelligence, 8(6):679–698, 1986. and implemented in OpenGL ES by A. Ensor, S. Hall. GPU-based Image Analysis on Mobile Devices. Proceedings of Image and Vision Computing New Zealand 2011. It starts with a conversion to luminance, followed by an accelerated 9-hit Gaussian blur. A Sobel operator is applied to obtain the overall gradient strength in the blurred image, as well as the direction (in texture sampling steps) of the gradient. A non-maximum suppression filter acts along the direction of the gradient, highlighting strong edges that pass the threshold and completely removing those that fail the lower threshold. Finally, pixels from in-between these thresholds are either included in edges or rejected based on neighboring pixels. */ public class CannyEdgeDetection: OperationGroup { public var blurRadiusInPixels:Float = 2.0 { didSet { gaussianBlur.blurRadiusInPixels = blurRadiusInPixels } } public var upperThreshold:Float = 0.4 { didSet { directionalNonMaximumSuppression.uniformSettings["upperThreshold"] = upperThreshold } } public var lowerThreshold:Float = 0.1 { didSet { directionalNonMaximumSuppression.uniformSettings["lowerThreshold"] = lowerThreshold } } let luminance = Luminance() let gaussianBlur = SingleComponentGaussianBlur() let directionalSobel = TextureSamplingOperation(fragmentShader:DirectionalSobelEdgeDetectionFragmentShader) let directionalNonMaximumSuppression = TextureSamplingOperation(vertexShader:OneInputVertexShader, fragmentShader:DirectionalNonMaximumSuppressionFragmentShader) let weakPixelInclusion = TextureSamplingOperation(fragmentShader:WeakPixelInclusionFragmentShader) public override init() { super.init() ({blurRadiusInPixels = 2.0})() ({upperThreshold = 0.4})() ({lowerThreshold = 0.1})() self.configureGroup{input, output in input --> self.luminance --> self.gaussianBlur --> self.directionalSobel --> self.directionalNonMaximumSuppression --> self.weakPixelInclusion --> output } } }
mit
4119aa0ca13cc1fea9352223e9266f70
60.054054
165
0.763065
4.87689
false
false
false
false
tuanan94/FRadio-ios
Pods/NotificationBannerSwift/NotificationBanner/Classes/NotificationBanner.swift
1
7263
/* The MIT License (MIT) Copyright (c) 2017 Dalton Hinterscher 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 SnapKit #if CARTHAGE_CONFIG import MarqueeLabelSwift #else import MarqueeLabel #endif public class NotificationBanner: BaseNotificationBanner { /// Notification that will be posted when a notification banner will appear public static let BannerWillAppear: Notification.Name = Notification.Name(rawValue: "NotificationBannerWillAppear") /// Notification that will be posted when a notification banner did appear public static let BannerDidAppear: Notification.Name = Notification.Name(rawValue: "NotificationBannerDidAppear") /// Notification that will be posted when a notification banner will appear public static let BannerWillDisappear: Notification.Name = Notification.Name(rawValue: "NotificationBannerWillDisappear") /// Notification that will be posted when a notification banner did appear public static let BannerDidDisappear: Notification.Name = Notification.Name(rawValue: "NotificationBannerDidDisappear") /// Notification banner object key that is included with each Notification public static let BannerObjectKey: String = "NotificationBannerObjectKey" /// The bottom most label of the notification if a subtitle is provided public private(set) var subtitleLabel: MarqueeLabel? /// The view that is presented on the left side of the notification private var leftView: UIView? /// The view that is presented on the right side of the notification private var rightView: UIView? public init(title: String, subtitle: String? = nil, leftView: UIView? = nil, rightView: UIView? = nil, style: BannerStyle = .info, colors: BannerColorsProtocol? = nil) { super.init(style: style, colors: colors) if let leftView = leftView { contentView.addSubview(leftView) leftView.snp.makeConstraints({ (make) in make.top.equalToSuperview().offset(10) make.left.equalToSuperview().offset(10) make.bottom.equalToSuperview().offset(-10) make.width.equalTo(leftView.snp.height) }) } if let rightView = rightView { contentView.addSubview(rightView) rightView.snp.makeConstraints({ (make) in make.top.equalToSuperview().offset(10) make.right.equalToSuperview().offset(-10) make.bottom.equalToSuperview().offset(-10) make.width.equalTo(rightView.snp.height) }) } let labelsView = UIView() contentView.addSubview(labelsView) titleLabel = MarqueeLabel() titleLabel!.type = .left titleLabel!.font = UIFont.systemFont(ofSize: 17.5, weight: UIFont.Weight.bold) titleLabel!.textColor = .white titleLabel!.text = title labelsView.addSubview(titleLabel!) titleLabel!.snp.makeConstraints { (make) in make.top.equalToSuperview() make.left.equalToSuperview() make.right.equalToSuperview() if let _ = subtitle { titleLabel!.numberOfLines = 1 } else { titleLabel!.numberOfLines = 2 } } if let subtitle = subtitle { subtitleLabel = MarqueeLabel() subtitleLabel!.type = .left subtitleLabel!.font = UIFont.systemFont(ofSize: 15.0) subtitleLabel!.numberOfLines = 1 subtitleLabel!.textColor = .white subtitleLabel!.text = subtitle labelsView.addSubview(subtitleLabel!) subtitleLabel!.snp.makeConstraints { (make) in make.top.equalTo(titleLabel!.snp.bottom).offset(2.5) make.left.equalTo(titleLabel!) make.right.equalTo(titleLabel!) } } labelsView.snp.makeConstraints { (make) in make.centerY.equalToSuperview() if let leftView = leftView { make.left.equalTo(leftView.snp.right).offset(padding) } else { make.left.equalToSuperview().offset(padding) } if let rightView = rightView { make.right.equalTo(rightView.snp.left).offset(-padding) } else { make.right.equalToSuperview().offset(-padding) } if let subtitleLabel = subtitleLabel { make.bottom.equalTo(subtitleLabel) } else { make.bottom.equalTo(titleLabel!) } } updateMarqueeLabelsDurations() } public convenience init(attributedTitle: NSAttributedString, attributedSubtitle: NSAttributedString? = nil, leftView: UIView? = nil, rightView: UIView? = nil, style: BannerStyle = .info, colors: BannerColorsProtocol? = nil) { let subtitle: String? = (attributedSubtitle != nil) ? "" : nil self.init(title: "", subtitle: subtitle, leftView: leftView, rightView: rightView, style: style, colors: colors) titleLabel!.attributedText = attributedTitle subtitleLabel?.attributedText = attributedSubtitle } public init(customView: UIView) { super.init(style: .none) contentView.addSubview(customView) customView.snp.makeConstraints { (make) in make.edges.equalTo(contentView) } spacerView.backgroundColor = customView.backgroundColor } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } internal override func updateMarqueeLabelsDurations() { super.updateMarqueeLabelsDurations() subtitleLabel?.speed = .duration(CGFloat(duration - 3)) } }
mit
b3b232ff10187037e8f4c9928252792d
39.35
147
0.624673
5.514806
false
false
false
false
TG908/iOS
Pods/Sweeft/Sources/Sweeft/Promises/PromiseHandler.swift
1
2943
// // PromiseHandler.swift // Pods // // Created by Mathias Quintero on 12/11/16. // // import Foundation /// Enum For Representing an Empty Error Domain public enum NoError: Error {} public enum AnyError: Error { case error(Error) } /// Structure that allows us to nest callbacks more nicely public struct PromiseSuccessHandler<R, T, E: Error> { typealias Handler = (T) -> R private weak var promise: Promise<T, E>! private var handler: Handler init(promise: Promise<T, E>, handler: @escaping Handler) { self.promise = promise self.handler = handler promise.successHandlers.append(handler**) promise.state.result | handler** } /// Add an action after the current item @discardableResult public func then<O>(_ handler: @escaping (R) -> (O)) -> PromiseSuccessHandler<O, T, E> { _ = promise.successHandlers.popLast() return PromiseSuccessHandler<O, T, E>(promise: promise, handler: self.handler >>> handler) } /// Add a success Handler @discardableResult public func and<O>(call handler: @escaping (T) -> (O)) -> PromiseSuccessHandler<O, T, E> { return promise.onSuccess(call: handler) } /// Add an error Handler @discardableResult public func onError<O>(call handler: @escaping (E) -> (O)) -> PromiseErrorHandler<O, T, E> { return promise.onError(call: handler) } } public extension PromiseSuccessHandler where R: PromiseBody, R.ErrorType == E { /// Promise returned by the handler public var future: Promise<R.Result, R.ErrorType> { return .new { promise in self.then { $0.nest(to: promise, using: id) } self.onError(call: promise.error) } } } /// Structure that allows us to nest callbacks more nicely public struct PromiseErrorHandler<R, T, E: Error> { typealias Handler = (E) -> R private var promise: Promise<T, E> private var handler: Handler init(promise: Promise<T, E>, handler: @escaping Handler) { self.promise = promise self.handler = handler promise.errorHandlers.append(handler**) promise.state.error | handler** } /// Add an action to be done afterwards @discardableResult public func then<O>(_ handler: @escaping (R) -> (O)) -> PromiseErrorHandler<O, T, E> { _ = promise.errorHandlers.popLast() return PromiseErrorHandler<O, T, E>(promise: promise, handler: self.handler >>> handler) } /// Add a success Handler @discardableResult public func onSuccess<O>(call handler: @escaping (T) -> (O)) -> PromiseSuccessHandler<O, T, E> { return promise.onSuccess(call: handler) } /// Add an error Handler @discardableResult public func and<O>(call handler: @escaping (E) -> (O)) -> PromiseErrorHandler<O, T, E> { return promise.onError(call: handler) } }
gpl-3.0
4a0714f83b0928b8d5c5e9d27365fe20
30.645161
119
0.631668
4.104603
false
false
false
false
cdmx/MiniMancera
miniMancera/Model/Option/WhistlesVsZombies/Abstract/MOptionWhistlesVsZombiesLoader.swift
1
1151
import UIKit extension MOptionWhistlesVsZombies { private static let kResourceName:String = "ResourceWhistlesVsZombiesArea" private static let kResourceExtension:String = "plist" private static let kKeyBase:String = "base" private static let kKeyLane:String = "lane" class func loadArea() -> MOptionWhistlesVsZombiesArea { let area:MOptionWhistlesVsZombiesArea guard let resourceBase:URL = Bundle.main.url( forResource:kResourceName, withExtension:kResourceExtension), let areaDictionary:NSDictionary = NSDictionary( contentsOf:resourceBase), let map:[String:AnyObject] = areaDictionary as? [String:AnyObject], let mapLane:[CGFloat] = map[kKeyLane] as? [CGFloat], let mapBase:[CGFloat] = map[kKeyBase] as? [CGFloat] else { area = MOptionWhistlesVsZombiesArea(lane:[], base:[]) return area } area = MOptionWhistlesVsZombiesArea(lane:mapLane, base:mapBase) return area } }
mit
c3fcb45f51651b7c2369e92a97013567
30.972222
79
0.607298
5.208145
false
false
false
false
jadevance/fuzz-therapy-iOS
Fuzz Therapy/GetSearchResults.swift
1
2316
// // SearchResultsViewController.swift // Fuzz Therapy // // Created by Jade Vance on 8/13/16. // Copyright © 2016 Jade Vance. All rights reserved. // import Foundation import Alamofire import SwiftyJSON import RealmSwift // opening the database connection let realm = try! Realm() // instantiating variable up so it can be an instance of realm db var realm_dogUsers: Results<SearchResults>! func getSearchResults(completionHandler:(Array<Array<String>>)->()) { // gets the dog users(doguser.all) realm_dogUsers = realm.objects(SearchResults) var resultsArray = Array<Array<String>>() let enteredLocation = CurrentUser.sharedInstance.user?.location let parameters = ["location" : "\(enteredLocation!)"] Alamofire.request(.POST, "https://www.fuzztherapy.com/api/search", parameters: parameters) .responseJSON { response in if JSON(response.result.value!)[0] != "No Matches" { let resultsData = JSON(response.result.value!) for i in 0...14 { let name = resultsData[i]["name"].string! let dogName = resultsData[i]["dog_name"].string! let location = resultsData[i]["location"].string! let availability = resultsData[i]["availability"].string! let dogPicture = resultsData[i]["dog_picture_url"].string! let email = resultsData[i]["email"].string! resultsArray.append([name, dogName, location, availability, dogPicture, email]) // dogUser.New let dogUser = SearchResults() dogUser.name = name dogUser.dogName = dogName dogUser.location = location dogUser.availability = availability dogUser.dogPicture = dogPicture dogUser.email = email // dogUser.save try! realm.write { realm.add(dogUser) } completionHandler(resultsArray) } } else { let noMatches = "No Matches" resultsArray.append([noMatches]) completionHandler(resultsArray) } } }
apache-2.0
fd7e968fdcccc7053659b074f4b61da1
33.567164
95
0.567603
4.946581
false
false
false
false
hooman/swift
validation-test/stdlib/HashingRandomization.swift
3
2031
// RUN: %empty-directory(%t) // RUN: %target-build-swift -Xfrontend -disable-access-control -module-name main %s -o %t/hash // RUN: %target-codesign %t/hash // RUN: env %env-SWIFT_DETERMINISTIC_HASHING='' %target-run %t/hash > %t/nondeterministic.log // RUN: env %env-SWIFT_DETERMINISTIC_HASHING='' %target-run %t/hash >> %t/nondeterministic.log // RUN: %FileCheck --check-prefixes=RANDOM %s < %t/nondeterministic.log // RUN: env %env-SWIFT_DETERMINISTIC_HASHING=1 %target-run %t/hash > %t/deterministic.log // RUN: env %env-SWIFT_DETERMINISTIC_HASHING=1 %target-run %t/hash >> %t/deterministic.log // RUN: %FileCheck --check-prefixes=STABLE %s < %t/deterministic.log // REQUIRES: executable_test // This check verifies that the hash seed is randomly generated on every // execution of a Swift program unless the SWIFT_DETERMINISTIC_HASHING // environment variable is set. print("Deterministic: \(Hasher._isDeterministic)") print("Seed: \(Hasher._executionSeed)") print("Hash values: <\(0.hashValue), \(1.hashValue)>") // With randomized hashing, we get a new seed and a new set of hash values on // each run. There is a minuscule chance that the same seed is generated on two // separate executions; however, a test failure here is more likely to indicate // an issue with the random number generator or the testing environment. // RANDOM: Deterministic: false // RANDOM-NEXT: Seed: [[SEED0:\([0-9]+, [0-9]+\)]] // RANDOM-NEXT: Hash values: [[HASH0:<-?[0-9]+, -?[0-9]+>]] // RANDOM-NEXT: Deterministic: false // RANDOM-NEXT: Seed: // RANDOM-NOT: [[SEED0]] // RANDOM-NEXT: Hash values: // RANDOM-NOT: [[HASH0]] // Stable runs have known seeds, and generate the same hash values. A test // failure here indicates that the seed override mechanism isn't working // correctly. // STABLE: Deterministic: true // STABLE-NEXT: Seed: (0, 0) // STABLE-NEXT: Hash values: [[HASH1:<-?[0-9]+, -?[0-9]+>]] // STABLE-NEXT: Deterministic: true // STABLE-NEXT: Seed: (0, 0) // STABLE-NEXT: Hash values: [[HASH1]]
apache-2.0
9e8d78def99c15c9c00e0b529ff4d1db
47.357143
94
0.693747
3.067976
false
true
true
false
TruckMuncher/TruckMuncher-iOS
TruckMuncher/Constants.swift
1
980
// // Constants.swift // TruckMuncher // // Created by Josh Ault on 9/22/14. // Copyright (c) 2014 TruckMuncher. All rights reserved. // import Foundation /* * Non-value constants (such as keys into a dictionary) start with a k and are camel case */ let kTwitterOauthVerifier = "oauth_verifier" let kTwitterOauthToken = "oauth_token" let kTwitterOauthSecret = "oauth_secret" let kTwitterCallback = "twitter_callback" let kTwitterName = "twitter_name" let kTwitterKey = "twitter_key" let kTwitterSecretKey = "twitter_secret_key" let kCrashlyticsKey = "crashlytics_key" let kFinishedTutorial = "finished_tutorial" /* * Constants holding real values used directly should take on the typical syntax that #define used in obj-c */ let MENU_CATEGORY_HEIGHT:CGFloat = 66.0 #if RELEASE let PROPERTIES_FILE = "Properties" let BASE_URL = "https://api.truckmuncher.com:8443" #elseif DEBUG let PROPERTIES_FILE = "Properties-dev" let BASE_URL = "http://truckmuncher:8443" #endif
gpl-2.0
85dc67a124f9a4aff92df4071c10efd0
24.789474
107
0.746939
3.356164
false
false
false
false
mhmiles/PodcastFeedFinder
Source/PodcastFeedFinder.swift
1
5421
// // PodcastFeedFinder.swift // PodcastFeedFinder // // Created by Miles Hollingsworth on 6/2/16. // Copyright © 2016 Miles Hollingsworth. All rights reserved. // import Foundation import Alamofire import Fuzi typealias FeedFinderCompletion = ((URL) -> ()) public struct PodcastFeedFinderResult { public let mediaURL: URL public let artworkURL: URL public let duration: TimeInterval public let artist: String public let title: String } public enum FeedFinderError: Error { case podcastNotFoundByName case podcastNotFoundByID case podcastIDNotFound case episodeGUIDNotFound case alamofireError(NSError) } open class PodcastFeedFinder { open static let sharedFinder = PodcastFeedFinder() func getFeedURLForPodcastLink(_ link: URL, completion: @escaping ((URL) -> ())) { if let podcastID = try? getPodcastIDFromURL(link) { getFeedURLForID(podcastID, completion: completion) } else { let podcastName = link.deletingLastPathComponent().lastPathComponent getFeedURLForPodcastName(podcastName, completion: completion) } } open func getMediaURLForPodcastLink(_ link: URL, completion: @escaping ((PodcastFeedFinderResult) -> ())) throws { let components = URLComponents(url: link, resolvingAgainstBaseURL: false) guard let fragment = components?.fragment , fragment.hasPrefix("episodeGuid") else { print("No episode guid in link") return } let episodeGuid = fragment[fragment.index(fragment.startIndex, offsetBy: "episodeGuid=".characters.count)...] getFeedURLForPodcastLink(link) { (feedURL) in Alamofire.request(feedURL, method: .get).responseData(completionHandler: { (response) in guard let data = response.data else { print("Feed fetching error") return } let feed = try! XMLDocument(data: data) if let itemNode = feed.firstChild(xpath: "*/item[guid = '\(episodeGuid)']"), let mediaURLString = itemNode.firstChild(xpath: "enclosure")?.attr("url"), let mediaURL = URL(string: mediaURLString), let artworkURLString = (itemNode.firstChild(css: "itunes:image") ?? feed.firstChild(css: "itunes:image")!).attr("href"), let artworkURL = URL(string: artworkURLString), let durationString = itemNode.firstChild(xpath: "itunes:duration")?.stringValue, let artist = feed.firstChild(xpath: "channel/title")?.stringValue, let title = itemNode.firstChild(xpath: "title")?.stringValue { let durationComponents = durationString.components(separatedBy: ":") let duration = durationComponents.enumerated().reduce(TimeInterval(0), { (acc, value) -> TimeInterval in return acc + TimeInterval(value.element)!*pow(60, Double(durationComponents.count-value.offset-1)) }) completion(PodcastFeedFinderResult(mediaURL: mediaURL, artworkURL: artworkURL, duration: duration, artist: artist, title: title)) } }) } } internal func getPodcastIDFromURL(_ url: URL) throws -> String { let lastComponent = url.lastPathComponent if lastComponent.hasPrefix("id") { return String(lastComponent[lastComponent.index(lastComponent.startIndex, offsetBy: 2)...]) } throw FeedFinderError.podcastIDNotFound } internal func getFeedURLForID(_ podcastID: String, completion: @escaping FeedFinderCompletion) { Alamofire.request("https://itunes.apple.com/lookup", method: .get, parameters: ["id": podcastID]).responseJSON { (response) in switch response.result { case .success(let JSON as [String: Any]): if let result = (JSON["results"] as? NSArray)?.firstObject as? NSDictionary, let feedURLString = result["feedUrl"] as? String, let feedURL = URL(string: feedURLString) { completion(feedURL) } case .failure: print("ERROR") default: abort() } } } internal func getFeedURLForPodcastName(_ name: String, completion: @escaping FeedFinderCompletion) { let parameters = [ "term": name, "media": "podcast" ] Alamofire.request("https://itunes.apple.com/search", method: .get, parameters: parameters).responseJSON { (response) in switch response.result { case .success(let JSON as [String: Any]): if let results = JSON["results"] as? [NSDictionary], let result = results.filter({ $0["kind"] as? String == "podcast" }).first, let feedURLString = result["feedUrl"] as? String, let feedURL = URL(string: feedURLString) { completion(feedURL) } else { } case .failure: print("ERROR") default: abort() } } } }
mit
93befc270a8b2ec01d968e366cb88f89
40.060606
236
0.585609
5.084428
false
false
false
false
gregomni/swift
stdlib/public/Concurrency/AsyncDropWhileSequence.swift
3
4992
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2021 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// import Swift @available(SwiftStdlib 5.1, *) extension AsyncSequence { /// Omits elements from the base asynchronous sequence until a given closure /// returns false, after which it passes through all remaining elements. /// /// Use `drop(while:)` to omit elements from an asynchronous sequence until /// the element received meets a condition you specify. /// /// In this example, an asynchronous sequence called `Counter` produces `Int` /// values from `1` to `10`. The `drop(while:)` method causes the modified /// sequence to ignore received values until it encounters one that is /// divisible by `3`: /// /// let stream = Counter(howHigh: 10) /// .drop { $0 % 3 != 0 } /// for await number in stream { /// print("\(number) ", terminator: " ") /// } /// // prints "3 4 5 6 7 8 9 10" /// /// After the predicate returns `false`, the sequence never executes it again, /// and from then on the sequence passes through elements from its underlying /// sequence as-is. /// /// - Parameter predicate: A closure that takes an element as a parameter and /// returns a Boolean value indicating whether to drop the element from the /// modified sequence. /// - Returns: An asynchronous sequence that skips over values from the /// base sequence until the provided closure returns `false`. @preconcurrency @inlinable public __consuming func drop( while predicate: @Sendable @escaping (Element) async -> Bool ) -> AsyncDropWhileSequence<Self> { AsyncDropWhileSequence(self, predicate: predicate) } } /// An asynchronous sequence which omits elements from the base sequence until a /// given closure returns false, after which it passes through all remaining /// elements. @available(SwiftStdlib 5.1, *) public struct AsyncDropWhileSequence<Base: AsyncSequence> { @usableFromInline let base: Base @usableFromInline let predicate: (Base.Element) async -> Bool @usableFromInline init( _ base: Base, predicate: @escaping (Base.Element) async -> Bool ) { self.base = base self.predicate = predicate } } @available(SwiftStdlib 5.1, *) extension AsyncDropWhileSequence: AsyncSequence { /// The type of element produced by this asynchronous sequence. /// /// The drop-while sequence produces whatever type of element its base /// sequence produces. public typealias Element = Base.Element /// The type of iterator that produces elements of the sequence. public typealias AsyncIterator = Iterator /// The iterator that produces elements of the drop-while sequence. public struct Iterator: AsyncIteratorProtocol { @usableFromInline var baseIterator: Base.AsyncIterator @usableFromInline var predicate: ((Base.Element) async -> Bool)? @usableFromInline init( _ baseIterator: Base.AsyncIterator, predicate: @escaping (Base.Element) async -> Bool ) { self.baseIterator = baseIterator self.predicate = predicate } /// Produces the next element in the drop-while sequence. /// /// This iterator calls `next()` on its base iterator and evaluates the /// result with the `predicate` closure. As long as the predicate returns /// `true`, this method returns `nil`. After the predicate returns `false`, /// for a value received from the base iterator, this method returns that /// value. After that, the iterator returns values received from its /// base iterator as-is, and never executes the predicate closure again. @inlinable public mutating func next() async rethrows -> Base.Element? { while let predicate = self.predicate { guard let element = try await baseIterator.next() else { return nil } if await predicate(element) == false { self.predicate = nil return element } } return try await baseIterator.next() } } /// Creates an instance of the drop-while sequence iterator. @inlinable public __consuming func makeAsyncIterator() -> Iterator { return Iterator(base.makeAsyncIterator(), predicate: predicate) } } @available(SwiftStdlib 5.1, *) extension AsyncDropWhileSequence: @unchecked Sendable where Base: Sendable, Base.Element: Sendable { } @available(SwiftStdlib 5.1, *) extension AsyncDropWhileSequence.Iterator: @unchecked Sendable where Base.AsyncIterator: Sendable, Base.Element: Sendable { }
apache-2.0
3a1af17d84a3a96486f84edb095859d6
34.657143
80
0.667468
4.80462
false
false
false
false
khizkhiz/swift
test/SILGen/protocol_extensions.swift
2
34052
// RUN: %target-swift-frontend -disable-objc-attr-requires-foundation-module -emit-silgen %s | FileCheck %s public protocol P1 { func reqP1a() subscript(i: Int) -> Int { get set } } struct Box { var number: Int } extension P1 { // CHECK-LABEL: sil hidden @_TFE19protocol_extensionsPS_2P16extP1a{{.*}} : $@convention(method) <Self where Self : P1> (@in_guaranteed Self) -> () { // CHECK: bb0([[SELF:%[0-9]+]] : $*Self): final func extP1a() { // CHECK: [[WITNESS:%[0-9]+]] = witness_method $Self, #P1.reqP1a!1 : $@convention(witness_method) <τ_0_0 where τ_0_0 : P1> (@in_guaranteed τ_0_0) -> () // CHECK-NEXT: apply [[WITNESS]]<Self>([[SELF]]) : $@convention(witness_method) <τ_0_0 where τ_0_0 : P1> (@in_guaranteed τ_0_0) -> () reqP1a() // CHECK: return } // CHECK-LABEL: sil @_TFE19protocol_extensionsPS_2P16extP1b{{.*}} : $@convention(method) <Self where Self : P1> (@in_guaranteed Self) -> () { // CHECK: bb0([[SELF:%[0-9]+]] : $*Self): public final func extP1b() { // CHECK: [[FN:%[0-9]+]] = function_ref @_TFE19protocol_extensionsPS_2P16extP1a{{.*}} : $@convention(method) <τ_0_0 where τ_0_0 : P1> (@in_guaranteed τ_0_0) -> () // CHECK-NEXT: apply [[FN]]<Self>([[SELF]]) : $@convention(method) <τ_0_0 where τ_0_0 : P1> (@in_guaranteed τ_0_0) -> () extP1a() // CHECK: return } subscript(i: Int) -> Int { // materializeForSet can do static dispatch to peer accessors (tested later, in the emission of the concrete conformance) get { return 0 } set {} } final func callSubscript() -> Int { // But here we have to do a witness method call: // CHECK-LABEL: sil hidden @_TFE19protocol_extensionsPS_2P113callSubscript{{.*}} // CHECK: bb0(%0 : $*Self): // CHECK: witness_method $Self, #P1.subscript!getter.1 // CHECK: return return self[0] } static var staticReadOnlyProperty: Int { return 0 } static var staticReadWrite1: Int { get { return 0 } set { } } static var staticReadWrite2: Box { get { return Box(number: 0) } set { } } } // ---------------------------------------------------------------------------- // Using protocol extension members with concrete types // ---------------------------------------------------------------------------- class C : P1 { func reqP1a() { } } // (materializeForSet test from above) // CHECK-LABEL: sil [transparent] [thunk] @_TTWC19protocol_extensions1CS_2P1S_FS1_m9subscriptFSiSi // CHECK: bb0(%0 : $Builtin.RawPointer, %1 : $*Builtin.UnsafeValueBuffer, %2 : $Int, %3 : $*C): // CHECK: function_ref @_TFE19protocol_extensionsPS_2P1g9subscriptFSiSi // CHECK: return class D : C { } struct S : P1 { func reqP1a() { } } struct G<T> : P1 { func reqP1a() { } } struct MetaHolder { var d: D.Type = D.self var s: S.Type = S.self } struct GenericMetaHolder<T> { var g: G<T>.Type = G<T>.self } func inout_func(n: inout Int) {} // CHECK-LABEL: sil hidden @_TF19protocol_extensions5testDFTVS_10MetaHolder2ddMCS_1D1dS1__T_ : $@convention(thin) (MetaHolder, @thick D.Type, @owned D) -> () // CHECK: bb0([[M:%[0-9]+]] : $MetaHolder, [[DD:%[0-9]+]] : $@thick D.Type, [[D:%[0-9]+]] : $D): func testD(m: MetaHolder, dd: D.Type, d: D) { // CHECK: [[D2:%[0-9]+]] = alloc_box $D // CHECK: [[RESULT:%.*]] = project_box [[D2]] // CHECK: [[FN:%[0-9]+]] = function_ref @_TFE19protocol_extensionsPS_2P111returnsSelf{{.*}} // CHECK: [[DCOPY:%[0-9]+]] = alloc_stack $D // CHECK: store [[D]] to [[DCOPY]] : $*D // CHECK: apply [[FN]]<D>([[RESULT]], [[DCOPY]]) : $@convention(method) <τ_0_0 where τ_0_0 : P1> (@in_guaranteed τ_0_0) -> @out τ_0_0 var d2: D = d.returnsSelf() // CHECK: metatype $@thick D.Type // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1g22staticReadOnlyPropertySi let _ = D.staticReadOnlyProperty // CHECK: metatype $@thick D.Type // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1s16staticReadWrite1Si D.staticReadWrite1 = 1 // CHECK: metatype $@thick D.Type // CHECK: alloc_stack $Int // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1g16staticReadWrite1Si // CHECK: store // CHECK: load // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1s16staticReadWrite1Si // CHECK: dealloc_stack D.staticReadWrite1 += 1 // CHECK: metatype $@thick D.Type // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1s16staticReadWrite2VS_3Box D.staticReadWrite2 = Box(number: 2) // CHECK: metatype $@thick D.Type // CHECK: alloc_stack $Box // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1g16staticReadWrite2VS_3Box // CHECK: store // CHECK: load // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1s16staticReadWrite2VS_3Box // CHECK: dealloc_stack D.staticReadWrite2.number += 5 // CHECK: function_ref @_TF19protocol_extensions10inout_funcFRSiT_ // CHECK: metatype $@thick D.Type // CHECK: alloc_stack $Box // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1g16staticReadWrite2VS_3Box // CHECK: store // CHECK: load // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1s16staticReadWrite2VS_3Box // CHECK: dealloc_stack inout_func(&D.staticReadWrite2.number) // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1g22staticReadOnlyPropertySi let _ = dd.staticReadOnlyProperty // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1s16staticReadWrite1Si dd.staticReadWrite1 = 1 // CHECK: alloc_stack $Int // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1g16staticReadWrite1Si // CHECK: store // CHECK: load // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1s16staticReadWrite1Si // CHECK: dealloc_stack dd.staticReadWrite1 += 1 // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1s16staticReadWrite2VS_3Box dd.staticReadWrite2 = Box(number: 2) // CHECK: alloc_stack $Box // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1g16staticReadWrite2VS_3Box // CHECK: store // CHECK: load // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1s16staticReadWrite2VS_3Box // CHECK: dealloc_stack dd.staticReadWrite2.number += 5 // CHECK: function_ref @_TF19protocol_extensions10inout_funcFRSiT_ // CHECK: alloc_stack $Box // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1g16staticReadWrite2VS_3Box // CHECK: store // CHECK: load // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1s16staticReadWrite2VS_3Box // CHECK: dealloc_stack inout_func(&dd.staticReadWrite2.number) // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1g22staticReadOnlyPropertySi let _ = m.d.staticReadOnlyProperty // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1s16staticReadWrite1Si m.d.staticReadWrite1 = 1 // CHECK: alloc_stack $Int // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1g16staticReadWrite1Si // CHECK: store // CHECK: load // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1s16staticReadWrite1Si // CHECK: dealloc_stack m.d.staticReadWrite1 += 1 // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1s16staticReadWrite2VS_3Box m.d.staticReadWrite2 = Box(number: 2) // CHECK: alloc_stack $Box // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1g16staticReadWrite2VS_3Box // CHECK: store // CHECK: load // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1s16staticReadWrite2VS_3Box // CHECK: dealloc_stack m.d.staticReadWrite2.number += 5 // CHECK: function_ref @_TF19protocol_extensions10inout_funcFRSiT_ // CHECK: alloc_stack $Box // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1g16staticReadWrite2VS_3Box // CHECK: store // CHECK: load // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1s16staticReadWrite2VS_3Box // CHECK: dealloc_stack inout_func(&m.d.staticReadWrite2.number) // CHECK: return } // CHECK-LABEL: sil hidden @_TF19protocol_extensions5testSFTVS_10MetaHolder2ssMVS_1S_T_ func testS(m: MetaHolder, ss: S.Type) { // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1g22staticReadOnlyPropertySi // CHECK: metatype $@thick S.Type let _ = S.staticReadOnlyProperty // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1s16staticReadWrite1Si // CHECK: metatype $@thick S.Type S.staticReadWrite1 = 1 // CHECK: alloc_stack $Int // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1g16staticReadWrite1Si // CHECK: metatype $@thick S.Type // CHECK: store // CHECK: load // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1s16staticReadWrite1Si // CHECK: dealloc_stack S.staticReadWrite1 += 1 // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1s16staticReadWrite2VS_3Box // CHECK: metatype $@thick S.Type S.staticReadWrite2 = Box(number: 2) // CHECK: alloc_stack $Box // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1g16staticReadWrite2VS_3Box // CHECK: metatype $@thick S.Type // CHECK: store // CHECK: load // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1s16staticReadWrite2VS_3Box // CHECK: dealloc_stack S.staticReadWrite2.number += 5 // CHECK: function_ref @_TF19protocol_extensions10inout_funcFRSiT_ // CHECK: alloc_stack $Box // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1g16staticReadWrite2VS_3Box // CHECK: metatype $@thick S.Type // CHECK: store // CHECK: load // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1s16staticReadWrite2VS_3Box // CHECK: dealloc_stack inout_func(&S.staticReadWrite2.number) // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1g22staticReadOnlyPropertySi // CHECK: metatype $@thick S.Type let _ = ss.staticReadOnlyProperty // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1s16staticReadWrite1Si // CHECK: metatype $@thick S.Type ss.staticReadWrite1 = 1 // CHECK: alloc_stack $Int // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1g16staticReadWrite1Si // CHECK: metatype $@thick S.Type // CHECK: store // CHECK: load // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1s16staticReadWrite1Si // CHECK: dealloc_stack ss.staticReadWrite1 += 1 // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1s16staticReadWrite2VS_3Box // CHECK: metatype $@thick S.Type ss.staticReadWrite2 = Box(number: 2) // CHECK: alloc_stack $Box // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1g16staticReadWrite2VS_3Box // CHECK: metatype $@thick S.Type // CHECK: store // CHECK: load // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1s16staticReadWrite2VS_3Box // CHECK: dealloc_stack ss.staticReadWrite2.number += 5 // CHECK: function_ref @_TF19protocol_extensions10inout_funcFRSiT_ // CHECK: alloc_stack $Box // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1g16staticReadWrite2VS_3Box // CHECK: metatype $@thick S.Type // CHECK: store // CHECK: load // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1s16staticReadWrite2VS_3Box // CHECK: dealloc_stack inout_func(&ss.staticReadWrite2.number) // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1g22staticReadOnlyPropertySi // CHECK: metatype $@thick S.Type let _ = m.s.staticReadOnlyProperty // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1s16staticReadWrite1Si // CHECK: metatype $@thick S.Type m.s.staticReadWrite1 = 1 // CHECK: alloc_stack $Int // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1g16staticReadWrite1Si // CHECK: metatype $@thick S.Type // CHECK: store // CHECK: load // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1s16staticReadWrite1Si // CHECK: dealloc_stack m.s.staticReadWrite1 += 1 // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1s16staticReadWrite2VS_3Box // CHECK: metatype $@thick S.Type m.s.staticReadWrite2 = Box(number: 2) // CHECK: alloc_stack $Box // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1g16staticReadWrite2VS_3Box // CHECK: metatype $@thick S.Type // CHECK: store // CHECK: load // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1s16staticReadWrite2VS_3Box // CHECK: dealloc_stack m.s.staticReadWrite2.number += 5 // CHECK: function_ref @_TF19protocol_extensions10inout_funcFRSiT_ // CHECK: alloc_stack $Box // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1g16staticReadWrite2VS_3Box // CHECK: metatype $@thick S.Type // CHECK: store // CHECK: load // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1s16staticReadWrite2VS_3Box // CHECK: dealloc_stack inout_func(&m.s.staticReadWrite2.number) // CHECK: return } // CHECK-LABEL: sil hidden @_TF19protocol_extensions5testG func testG<T>(m: GenericMetaHolder<T>, gg: G<T>.Type) { // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1g22staticReadOnlyPropertySi // CHECK: metatype $@thick G<T>.Type let _ = G<T>.staticReadOnlyProperty // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1s16staticReadWrite1Si // CHECK: metatype $@thick G<T>.Type G<T>.staticReadWrite1 = 1 // CHECK: alloc_stack $Int // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1g16staticReadWrite1Si // CHECK: metatype $@thick G<T>.Type // CHECK: store // CHECK: load // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1s16staticReadWrite1Si // CHECK: dealloc_stack G<T>.staticReadWrite1 += 1 // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1s16staticReadWrite2VS_3Box // CHECK: metatype $@thick G<T>.Type G<T>.staticReadWrite2 = Box(number: 2) // CHECK: alloc_stack $Box // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1g16staticReadWrite2VS_3Box // CHECK: metatype $@thick G<T>.Type // CHECK: store // CHECK: load // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1s16staticReadWrite2VS_3Box // CHECK: dealloc_stack G<T>.staticReadWrite2.number += 5 // CHECK: function_ref @_TF19protocol_extensions10inout_funcFRSiT_ // CHECK: alloc_stack $Box // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1g16staticReadWrite2VS_3Box // CHECK: metatype $@thick G<T>.Type // CHECK: store // CHECK: load // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1s16staticReadWrite2VS_3Box // CHECK: dealloc_stack inout_func(&G<T>.staticReadWrite2.number) // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1g22staticReadOnlyPropertySi // CHECK: metatype $@thick G<T>.Type let _ = gg.staticReadOnlyProperty // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1s16staticReadWrite1Si // CHECK: metatype $@thick G<T>.Type gg.staticReadWrite1 = 1 // CHECK: alloc_stack $Int // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1g16staticReadWrite1Si // CHECK: metatype $@thick G<T>.Type // CHECK: store // CHECK: load // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1s16staticReadWrite1Si // CHECK: dealloc_stack gg.staticReadWrite1 += 1 // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1s16staticReadWrite2VS_3Box // CHECK: metatype $@thick G<T>.Type gg.staticReadWrite2 = Box(number: 2) // CHECK: alloc_stack $Box // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1g16staticReadWrite2VS_3Box // CHECK: metatype $@thick G<T>.Type // CHECK: store // CHECK: load // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1s16staticReadWrite2VS_3Box // CHECK: dealloc_stack gg.staticReadWrite2.number += 5 // CHECK: function_ref @_TF19protocol_extensions10inout_funcFRSiT_ // CHECK: alloc_stack $Box // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1g16staticReadWrite2VS_3Box // CHECK: metatype $@thick G<T>.Type // CHECK: store // CHECK: load // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1s16staticReadWrite2VS_3Box // CHECK: dealloc_stack inout_func(&gg.staticReadWrite2.number) // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1g22staticReadOnlyPropertySi // CHECK: metatype $@thick G<T>.Type let _ = m.g.staticReadOnlyProperty // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1s16staticReadWrite1Si // CHECK: metatype $@thick G<T>.Type m.g.staticReadWrite1 = 1 // CHECK: alloc_stack $Int // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1g16staticReadWrite1Si // CHECK: metatype $@thick G<T>.Type // CHECK: store // CHECK: load // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1s16staticReadWrite1Si // CHECK: dealloc_stack m.g.staticReadWrite1 += 1 // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1s16staticReadWrite2VS_3Box // CHECK: metatype $@thick G<T>.Type m.g.staticReadWrite2 = Box(number: 2) // CHECK: alloc_stack $Box // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1g16staticReadWrite2VS_3Box // CHECK: metatype $@thick G<T>.Type // CHECK: store // CHECK: load // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1s16staticReadWrite2VS_3Box // CHECK: dealloc_stack m.g.staticReadWrite2.number += 5 // CHECK: function_ref @_TF19protocol_extensions10inout_funcFRSiT_ // CHECK: alloc_stack $Box // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1g16staticReadWrite2VS_3Box // CHECK: metatype $@thick G<T>.Type // CHECK: store // CHECK: load // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1s16staticReadWrite2VS_3Box // CHECK: dealloc_stack inout_func(&m.g.staticReadWrite2.number) // CHECK: return } // ---------------------------------------------------------------------------- // Using protocol extension members with existentials // ---------------------------------------------------------------------------- extension P1 { final func f1() { } final subscript (i: Int64) -> Bool { get { return true } } final var prop: Bool { get { return true } } final func returnsSelf() -> Self { return self } final var prop2: Bool { get { return true } set { } } final subscript (b: Bool) -> Bool { get { return b } set { } } } // CHECK-LABEL: sil hidden @_TF19protocol_extensions17testExistentials1 // CHECK: bb0([[P:%[0-9]+]] : $*P1, [[B:%[0-9]+]] : $Bool, [[I:%[0-9]+]] : $Int64): func testExistentials1(p1: P1, b: Bool, i: Int64) { // CHECK: [[POPENED:%[0-9]+]] = open_existential_addr [[P]] : $*P1 to $*@opened([[UUID:".*"]]) // CHECK: [[F1:%[0-9]+]] = function_ref @_TFE19protocol_extensionsPS_2P12f1{{.*}} // CHECK: apply [[F1]]<@opened([[UUID]]) P1>([[POPENED]]) : $@convention(method) <τ_0_0 where τ_0_0 : P1> (@in_guaranteed τ_0_0) -> () p1.f1() // CHECK: [[POPENED:%[0-9]+]] = open_existential_addr [[P]] : $*P1 to $*@opened([[UUID:".*"]]) P1 // CHECK: copy_addr [[POPENED]] to [initialization] [[POPENED_COPY:%.*]] : // CHECK: [[GETTER:%[0-9]+]] = function_ref @_TFE19protocol_extensionsPS_2P1g9subscriptFVs5Int64Sb // CHECK: apply [[GETTER]]<@opened([[UUID]]) P1>([[I]], [[POPENED_COPY]]) : $@convention(method) <τ_0_0 where τ_0_0 : P1> (Int64, @in_guaranteed τ_0_0) -> Bool // CHECK: destroy_addr [[POPENED_COPY]] // CHECK: store{{.*}} : $*Bool // CHECK: dealloc_stack [[POPENED_COPY]] var b2 = p1[i] // CHECK: [[POPENED:%[0-9]+]] = open_existential_addr [[P]] : $*P1 to $*@opened([[UUID:".*"]]) P1 // CHECK: copy_addr [[POPENED]] to [initialization] [[POPENED_COPY:%.*]] : // CHECK: [[GETTER:%[0-9]+]] = function_ref @_TFE19protocol_extensionsPS_2P1g4propSb // CHECK: apply [[GETTER]]<@opened([[UUID]]) P1>([[POPENED_COPY]]) : $@convention(method) <τ_0_0 where τ_0_0 : P1> (@in_guaranteed τ_0_0) -> Bool // CHECK: store{{.*}} : $*Bool // CHECK: dealloc_stack [[POPENED_COPY]] var b3 = p1.prop } // CHECK-LABEL: sil hidden @_TF19protocol_extensions17testExistentials2 // CHECK: bb0([[P:%[0-9]+]] : $*P1): func testExistentials2(p1: P1) { // CHECK: [[P1A:%[0-9]+]] = alloc_box $P1 // CHECK: [[PB:%.*]] = project_box [[P1A]] // CHECK: [[POPENED:%[0-9]+]] = open_existential_addr [[P]] : $*P1 to $*@opened([[UUID:".*"]]) P1 // CHECK: [[P1AINIT:%[0-9]+]] = init_existential_addr [[PB]] : $*P1, $@opened([[UUID2:".*"]]) P1 // CHECK: [[FN:%[0-9]+]] = function_ref @_TFE19protocol_extensionsPS_2P111returnsSelf{{.*}} // CHECK: apply [[FN]]<@opened([[UUID]]) P1>([[P1AINIT]], [[POPENED]]) : $@convention(method) <τ_0_0 where τ_0_0 : P1> (@in_guaranteed τ_0_0) -> @out τ_0_0 var p1a: P1 = p1.returnsSelf() } // CHECK-LABEL: sil hidden @_TF19protocol_extensions23testExistentialsGetters // CHECK: bb0([[P:%[0-9]+]] : $*P1): func testExistentialsGetters(p1: P1) { // CHECK: [[POPENED:%[0-9]+]] = open_existential_addr [[P]] : $*P1 to $*@opened([[UUID:".*"]]) P1 // CHECK: copy_addr [[POPENED]] to [initialization] [[POPENED_COPY:%.*]] : // CHECK: [[FN:%[0-9]+]] = function_ref @_TFE19protocol_extensionsPS_2P1g5prop2Sb // CHECK: [[B:%[0-9]+]] = apply [[FN]]<@opened([[UUID]]) P1>([[POPENED_COPY]]) : $@convention(method) <τ_0_0 where τ_0_0 : P1> (@in_guaranteed τ_0_0) -> Bool let b: Bool = p1.prop2 // CHECK: [[POPENED:%[0-9]+]] = open_existential_addr [[P]] : $*P1 to $*@opened([[UUID:".*"]]) P1 // CHECK: copy_addr [[POPENED]] to [initialization] [[POPENED_COPY:%.*]] : // CHECK: [[GETTER:%[0-9]+]] = function_ref @_TFE19protocol_extensionsPS_2P1g9subscriptFSbSb // CHECK: apply [[GETTER]]<@opened([[UUID]]) P1>([[B]], [[POPENED_COPY]]) : $@convention(method) <τ_0_0 where τ_0_0 : P1> (Bool, @in_guaranteed τ_0_0) -> Bool let b2: Bool = p1[b] } // CHECK-LABEL: sil hidden @_TF19protocol_extensions22testExistentialSetters // CHECK: bb0([[P:%[0-9]+]] : $*P1, [[B:%[0-9]+]] : $Bool): func testExistentialSetters(p1: P1, b: Bool) { var p1 = p1 // CHECK: [[PBOX:%[0-9]+]] = alloc_box $P1 // CHECK: [[PBP:%[0-9]+]] = project_box [[PBOX]] // CHECK-NEXT: copy_addr [[P]] to [initialization] [[PBP]] : $*P1 // CHECK: [[POPENED:%[0-9]+]] = open_existential_addr [[PBP]] : $*P1 to $*@opened([[UUID:".*"]]) P1 // CHECK: [[GETTER:%[0-9]+]] = function_ref @_TFE19protocol_extensionsPS_2P1s5prop2Sb // CHECK: apply [[GETTER]]<@opened([[UUID]]) P1>([[B]], [[POPENED]]) : $@convention(method) <τ_0_0 where τ_0_0 : P1> (Bool, @inout τ_0_0) -> () // CHECK-NOT: deinit_existential_addr p1.prop2 = b // CHECK: [[POPENED:%[0-9]+]] = open_existential_addr [[PBP]] : $*P1 to $*@opened([[UUID:".*"]]) P1 // CHECK: [[SUBSETTER:%[0-9]+]] = function_ref @_TFE19protocol_extensionsPS_2P1s9subscriptFSbSb // CHECK: apply [[SUBSETTER]]<@opened([[UUID]]) P1>([[B]], [[B]], [[POPENED]]) : $@convention(method) <τ_0_0 where τ_0_0 : P1> (Bool, Bool, @inout τ_0_0) -> () // CHECK-NOT: deinit_existential_addr [[PB]] : $*P1 p1[b] = b // CHECK: return } struct HasAP1 { var p1: P1 var someP1: P1 { get { return p1 } set { p1 = newValue } } } // CHECK-LABEL: sil hidden @_TF19protocol_extensions29testLogicalExistentialSetters // CHECK: bb0([[HASP1:%[0-9]+]] : $*HasAP1, [[B:%[0-9]+]] : $Bool) func testLogicalExistentialSetters(hasAP1: HasAP1, _ b: Bool) { var hasAP1 = hasAP1 // CHECK: [[HASP1_BOX:%[0-9]+]] = alloc_box $HasAP1 // CHECK: [[PBHASP1:%[0-9]+]] = project_box [[HASP1_BOX]] // CHECK-NEXT: copy_addr [[HASP1]] to [initialization] [[PBHASP1]] : $*HasAP1 // CHECK: [[P1_COPY:%[0-9]+]] = alloc_stack $P1 // CHECK-NEXT: [[HASP1_COPY:%[0-9]+]] = alloc_stack $HasAP1 // CHECK-NEXT: copy_addr [[PBHASP1]] to [initialization] [[HASP1_COPY]] : $*HasAP1 // CHECK: [[SOMEP1_GETTER:%[0-9]+]] = function_ref @_TFV19protocol_extensions6HasAP1g6someP1PS_2P1_ : $@convention(method) (@in_guaranteed HasAP1) -> @out P1 // CHECK: [[RESULT:%[0-9]+]] = apply [[SOMEP1_GETTER]]([[P1_COPY]], %8) : $@convention(method) (@in_guaranteed HasAP1) -> @out P1 // CHECK: [[P1_OPENED:%[0-9]+]] = open_existential_addr [[P1_COPY]] : $*P1 to $*@opened([[UUID:".*"]]) P1 // CHECK: [[PROP2_SETTER:%[0-9]+]] = function_ref @_TFE19protocol_extensionsPS_2P1s5prop2Sb : $@convention(method) <τ_0_0 where τ_0_0 : P1> (Bool, @inout τ_0_0) -> () // CHECK: apply [[PROP2_SETTER]]<@opened([[UUID]]) P1>([[B]], [[P1_OPENED]]) : $@convention(method) <τ_0_0 where τ_0_0 : P1> (Bool, @inout τ_0_0) -> () // CHECK: [[SOMEP1_SETTER:%[0-9]+]] = function_ref @_TFV19protocol_extensions6HasAP1s6someP1PS_2P1_ : $@convention(method) (@in P1, @inout HasAP1) -> () // CHECK: apply [[SOMEP1_SETTER]]([[P1_COPY]], [[PBHASP1]]) : $@convention(method) (@in P1, @inout HasAP1) -> () // CHECK-NOT: deinit_existential_addr hasAP1.someP1.prop2 = b // CHECK: return } func plusOneP1() -> P1 {} // CHECK-LABEL: sil hidden @_TF19protocol_extensions38test_open_existential_semantics_opaque func test_open_existential_semantics_opaque(guaranteed: P1, immediate: P1) { var immediate = immediate // CHECK: [[IMMEDIATE_BOX:%.*]] = alloc_box $P1 // CHECK: [[PB:%.*]] = project_box [[IMMEDIATE_BOX]] // CHECK: [[VALUE:%.*]] = open_existential_addr %0 // CHECK: [[METHOD:%.*]] = function_ref // CHECK: apply [[METHOD]]<{{.*}}>([[VALUE]]) guaranteed.f1() // -- Need a guaranteed copy because it's immutable // CHECK: copy_addr [[PB]] to [initialization] [[IMMEDIATE:%.*]] : // CHECK: [[VALUE:%.*]] = open_existential_addr [[IMMEDIATE]] // CHECK: [[METHOD:%.*]] = function_ref // -- Can consume the value from our own copy // CHECK: apply [[METHOD]]<{{.*}}>([[VALUE]]) // CHECK: deinit_existential_addr [[IMMEDIATE]] // CHECK: dealloc_stack [[IMMEDIATE]] immediate.f1() // CHECK: [[PLUS_ONE:%.*]] = alloc_stack $P1 // CHECK: [[VALUE:%.*]] = open_existential_addr [[PLUS_ONE]] // CHECK: [[METHOD:%.*]] = function_ref // -- Can consume the value from our own copy // CHECK: apply [[METHOD]]<{{.*}}>([[VALUE]]) // CHECK: deinit_existential_addr [[PLUS_ONE]] // CHECK: dealloc_stack [[PLUS_ONE]] plusOneP1().f1() } protocol CP1: class {} extension CP1 { final func f1() { } } func plusOneCP1() -> CP1 {} // CHECK-LABEL: sil hidden @_TF19protocol_extensions37test_open_existential_semantics_class func test_open_existential_semantics_class(guaranteed: CP1, immediate: CP1) { var immediate = immediate // CHECK: [[IMMEDIATE_BOX:%.*]] = alloc_box $CP1 // CHECK: [[PB:%.*]] = project_box [[IMMEDIATE_BOX]] // CHECK-NOT: strong_retain %0 // CHECK: [[VALUE:%.*]] = open_existential_ref %0 // CHECK: [[METHOD:%.*]] = function_ref // CHECK: apply [[METHOD]]<{{.*}}>([[VALUE]]) // CHECK-NOT: strong_release [[VALUE]] // CHECK-NOT: strong_release %0 guaranteed.f1() // CHECK: [[IMMEDIATE:%.*]] = load [[PB]] // CHECK: strong_retain [[IMMEDIATE]] // CHECK: [[VALUE:%.*]] = open_existential_ref [[IMMEDIATE]] // CHECK: [[METHOD:%.*]] = function_ref // CHECK: apply [[METHOD]]<{{.*}}>([[VALUE]]) // CHECK: strong_release [[VALUE]] // CHECK-NOT: strong_release [[IMMEDIATE]] immediate.f1() // CHECK: [[F:%.*]] = function_ref {{.*}}plusOneCP1 // CHECK: [[PLUS_ONE:%.*]] = apply [[F]]() // CHECK: [[VALUE:%.*]] = open_existential_ref [[PLUS_ONE]] // CHECK: [[METHOD:%.*]] = function_ref // CHECK: apply [[METHOD]]<{{.*}}>([[VALUE]]) // CHECK: strong_release [[VALUE]] // CHECK-NOT: strong_release [[PLUS_ONE]] plusOneCP1().f1() } protocol InitRequirement { init(c: C) } extension InitRequirement { // CHECK-LABEL: sil hidden @_TFE19protocol_extensionsPS_15InitRequirementC{{.*}} : $@convention(thin) <Self where Self : InitRequirement> (@owned D, @thick Self.Type) -> @out Self // CHECK: bb0([[OUT:%.*]] : $*Self, [[ARG:%.*]] : $D, [[SELF_TYPE:%.*]] : $@thick Self.Type): init(d: D) { // CHECK: [[DELEGATEE:%.*]] = witness_method $Self, #InitRequirement.init!allocator.1 : $@convention(witness_method) <τ_0_0 where τ_0_0 : InitRequirement> (@owned C, @thick τ_0_0.Type) -> @out τ_0_0 // CHECK: [[ARG_UP:%.*]] = upcast [[ARG]] // CHECK: apply [[DELEGATEE]]<Self>({{%.*}}, [[ARG_UP]], [[SELF_TYPE]]) self.init(c: d) } // CHECK-LABEL: sil hidden @_TFE19protocol_extensionsPS_15InitRequirementC{{.*}} // CHECK: function_ref @_TFE19protocol_extensionsPS_15InitRequirementC{{.*}} init(d2: D) { self.init(d: d2) } } protocol ClassInitRequirement: class { init(c: C) } extension ClassInitRequirement { // CHECK-LABEL: sil hidden @_TFE19protocol_extensionsPS_20ClassInitRequirementC{{.*}} : $@convention(thin) <Self where Self : ClassInitRequirement> (@owned D, @thick Self.Type) -> @owned Self // CHECK: bb0([[ARG:%.*]] : $D, [[SELF_TYPE:%.*]] : $@thick Self.Type): // CHECK: [[DELEGATEE:%.*]] = witness_method $Self, #ClassInitRequirement.init!allocator.1 : $@convention(witness_method) <τ_0_0 where τ_0_0 : ClassInitRequirement> (@owned C, @thick τ_0_0.Type) -> @owned τ_0_0 // CHECK: [[ARG_UP:%.*]] = upcast [[ARG]] // CHECK: apply [[DELEGATEE]]<Self>([[ARG_UP]], [[SELF_TYPE]]) init(d: D) { self.init(c: d) } } @objc class OC {} @objc class OD: OC {} @objc protocol ObjCInitRequirement { init(c: OC, d: OC) } func foo(t: ObjCInitRequirement.Type, c: OC) -> ObjCInitRequirement { return t.init(c: OC(), d: OC()) } extension ObjCInitRequirement { // CHECK-LABEL: sil hidden @_TFE19protocol_extensionsPS_19ObjCInitRequirementC{{.*}} : $@convention(thin) <Self where Self : ObjCInitRequirement> (@owned OD, @thick Self.Type) -> @owned Self // CHECK: bb0([[ARG:%.*]] : $OD, [[SELF_TYPE:%.*]] : $@thick Self.Type): // CHECK: [[OBJC_SELF_TYPE:%.*]] = thick_to_objc_metatype [[SELF_TYPE]] // CHECK: [[SELF:%.*]] = alloc_ref_dynamic [objc] [[OBJC_SELF_TYPE]] : $@objc_metatype Self.Type, $Self // CHECK: [[WITNESS:%.*]] = witness_method [volatile] $Self, #ObjCInitRequirement.init!initializer.1.foreign : $@convention(objc_method) <τ_0_0 where τ_0_0 : ObjCInitRequirement> (OC, OC, @owned τ_0_0) -> @owned τ_0_0 // CHECK: [[UPCAST1:%.*]] = upcast [[ARG]] // CHECK: [[UPCAST2:%.*]] = upcast [[ARG]] // CHECK: apply [[WITNESS]]<Self>([[UPCAST1]], [[UPCAST2]], [[SELF]]) init(d: OD) { self.init(c: d, d: d) } } // rdar://problem/21370992 - delegation from an initializer in a // protocol extension to an @objc initializer in a class. class ObjCInitClass { @objc init() { } } protocol ProtoDelegatesToObjC { } extension ProtoDelegatesToObjC where Self : ObjCInitClass { // CHECK-LABEL: sil hidden @_TFe19protocol_extensionsRxCS_13ObjCInitClassxS_20ProtoDelegatesToObjCrS1_C{{.*}} // CHECK: bb0([[STR:%[0-9]+]] : $String, [[SELF_META:%[0-9]+]] : $@thick Self.Type): init(string: String) { // CHECK: [[SELF_BOX:%[0-9]+]] = alloc_box $Self // CHECK: [[PB:%.*]] = project_box [[SELF_BOX]] // CHECK: [[SELF:%[0-9]+]] = mark_uninitialized [delegatingself] [[PB]] : $*Self // CHECK: [[SELF_META_OBJC:%[0-9]+]] = thick_to_objc_metatype [[SELF_META]] : $@thick Self.Type to $@objc_metatype Self.Type // CHECK: [[SELF_ALLOC:%[0-9]+]] = alloc_ref_dynamic [objc] [[SELF_META_OBJC]] : $@objc_metatype Self.Type, $Self // CHECK: [[SELF_ALLOC_C:%[0-9]+]] = upcast [[SELF_ALLOC]] : $Self to $ObjCInitClass // CHECK: [[OBJC_INIT:%[0-9]+]] = class_method [[SELF_ALLOC_C]] : $ObjCInitClass, #ObjCInitClass.init!initializer.1 : ObjCInitClass.Type -> () -> ObjCInitClass , $@convention(method) (@owned ObjCInitClass) -> @owned ObjCInitClass // CHECK: [[SELF_RESULT:%[0-9]+]] = apply [[OBJC_INIT]]([[SELF_ALLOC_C]]) : $@convention(method) (@owned ObjCInitClass) -> @owned ObjCInitClass // CHECK: [[SELF_RESULT_AS_SELF:%[0-9]+]] = unchecked_ref_cast [[SELF_RESULT]] : $ObjCInitClass to $Self // CHECK: assign [[SELF_RESULT_AS_SELF]] to [[SELF]] : $*Self self.init() } } // Delegating from an initializer in a protocol extension where Self // has a superclass to a required initializer of that class. class RequiredInitClass { required init() { } } protocol ProtoDelegatesToRequired { } extension ProtoDelegatesToRequired where Self : RequiredInitClass { // CHECK-LABEL: sil hidden @_TFe19protocol_extensionsRxCS_17RequiredInitClassxS_24ProtoDelegatesToRequiredrS1_C{{.*}} // CHECK: bb0([[STR:%[0-9]+]] : $String, [[SELF_META:%[0-9]+]] : $@thick Self.Type): init(string: String) { // CHECK: [[SELF_BOX:%[0-9]+]] = alloc_box $Self // CHECK: [[PB:%.*]] = project_box [[SELF_BOX]] // CHECK: [[SELF:%[0-9]+]] = mark_uninitialized [delegatingself] [[PB]] : $*Self // CHECK: [[SELF_META_AS_CLASS_META:%[0-9]+]] = upcast [[SELF_META]] : $@thick Self.Type to $@thick RequiredInitClass.Type // CHECK: [[INIT:%[0-9]+]] = class_method [[SELF_META_AS_CLASS_META]] : $@thick RequiredInitClass.Type, #RequiredInitClass.init!allocator.1 : RequiredInitClass.Type -> () -> RequiredInitClass , $@convention(thin) (@thick RequiredInitClass.Type) -> @owned RequiredInitClass // CHECK: [[SELF_RESULT:%[0-9]+]] = apply [[INIT]]([[SELF_META_AS_CLASS_META]]) : $@convention(thin) (@thick RequiredInitClass.Type) -> @owned RequiredInitClass // CHECK: [[SELF_RESULT_AS_SELF:%[0-9]+]] = unchecked_ref_cast [[SELF_RESULT]] : $RequiredInitClass to $Self // CHECK: assign [[SELF_RESULT_AS_SELF]] to [[SELF]] : $*Self self.init() } } // ---------------------------------------------------------------------------- // Default implementations via protocol extensions // ---------------------------------------------------------------------------- protocol P2 { associatedtype A func f1(a: A) func f2(a: A) var x: A { get } } extension P2 { // CHECK-LABEL: sil hidden @_TFE19protocol_extensionsPS_2P22f1{{.*}} // CHECK: witness_method $Self, #P2.f2!1 // CHECK: function_ref @_TFE19protocol_extensionsPS_2P22f3{{.*}} // CHECK: return func f1(a: A) { f2(a) f3(a) } // CHECK-LABEL: sil hidden @_TFE19protocol_extensionsPS_2P22f2{{.*}} // CHECK: witness_method $Self, #P2.f1!1 // CHECK: function_ref @_TFE19protocol_extensionsPS_2P22f3{{.*}} // CHECK: return func f2(a: A) { f1(a) f3(a) } func f3(a: A) {} // CHECK-LABEL: sil hidden @_TFE19protocol_extensionsPS_2P22f4{{.*}} // CHECK: witness_method $Self, #P2.f1!1 // CHECK: witness_method $Self, #P2.f2!1 // CHECK: return func f4() { f1(x) f2(x) } }
apache-2.0
636c4175ed8a54278093854d48116b21
39.906137
276
0.648869
3.31639
false
false
false
false
ric2b/Vivaldi-browser
thirdparty/macsparkle/Sparkle/CheckLocalizations.swift
1
4025
#!/usr/bin/xcrun swift import Foundation func die(_ msg: String) { print("ERROR: \(msg)") exit(1) } extension XMLElement { convenience init(name: String, attributes: [String: String], stringValue string: String? = nil) { self.init(name: name, stringValue: string) setAttributesWith(attributes) } } let ud = UserDefaults.standard let sparkleRoot = ud.object(forKey: "root") as? String let htmlPath = ud.object(forKey: "htmlPath") as? String if sparkleRoot == nil || htmlPath == nil { die("Missing arguments") } let enStringsPath = sparkleRoot! + "/Sparkle/Base.lproj/Sparkle.strings" let enStringsDict = NSDictionary(contentsOfFile: enStringsPath) if enStringsDict == nil { die("Invalid English strings") } let enStringsDictKeys = enStringsDict!.allKeys let dirPath = NSString(string: sparkleRoot! + "/Sparkle") let dirContents = try! FileManager.default.contentsOfDirectory(atPath: dirPath as String) let css = "body { font-family: sans-serif; font-size: 10pt; }" + "h1 { font-size: 12pt; }" + ".missing { background-color: #FFBABA; color: #D6010E; white-space: pre; }" + ".unused { background-color: #BDE5F8; color: #00529B; white-space: pre; }" + ".unlocalized { background-color: #FEEFB3; color: #9F6000; white-space: pre; }" var html = XMLDocument(rootElement: XMLElement(name: "html")) html.dtd = XMLDTD() html.dtd!.name = html.rootElement()!.name html.characterEncoding = "UTF-8" html.documentContentKind = XMLDocument.ContentKind.xhtml var body = XMLElement(name: "body") var head = XMLElement(name: "head") html.rootElement()!.addChild(head) html.rootElement()!.addChild(body) head.addChild(XMLElement(name: "meta", attributes: ["charset": html.characterEncoding!])) head.addChild(XMLElement(name: "title", stringValue: "Sparkle Localizations Report")) head.addChild(XMLElement(name: "style", stringValue: css)) let locale = Locale.current for dirEntry in dirContents { if NSString(string: dirEntry).pathExtension != "lproj" || dirEntry == "Base.lproj" || dirEntry == "en.lproj" { continue } let lang = (locale as NSLocale).displayName(forKey: NSLocale.Key.languageCode, value: NSString(string: dirEntry).deletingPathExtension) body.addChild(XMLElement(name: "h1", stringValue: "\(dirEntry) (\(lang!))")) let stringsPath = NSString(string: dirPath.appendingPathComponent(dirEntry)).appendingPathComponent("Sparkle.strings") let stringsDict = NSDictionary(contentsOfFile: stringsPath) if stringsDict == nil { die("Invalid strings file \(dirEntry)") continue } var missing: [String] = [] var unlocalized: [String] = [] var unused: [String] = [] for key in enStringsDictKeys { let str = stringsDict?.object(forKey: key) as? String if str == nil { missing.append(key as! String) } else if let enStr = enStringsDict?.object(forKey: key) as? String { if enStr == str { unlocalized.append(key as! String) } } } let stringsDictKeys = stringsDict!.allKeys for key in stringsDictKeys { if enStringsDict?.object(forKey: key) == nil { unused.append(key as! String) } } let sorter = { (s1: String, s2: String) -> Bool in return s1 < s2 } missing.sort(by: sorter) unlocalized.sort(by: sorter) unused.sort(by: sorter) let addRow = { (prefix: String, cssClass: String, key: String) -> Void in body.addChild(XMLElement(name: "span", attributes: ["class": cssClass], stringValue: [prefix, key].joined(separator: " ") + "\n")) } for key in missing { addRow("Missing", "missing", key) } for key in unlocalized { addRow("Unlocalized", "unlocalized", key) } for key in unused { addRow("Unused", "unused", key) } } var err: NSError? if !((try? html.xmlData.write(to: URL(fileURLWithPath: htmlPath!), options: [.atomic])) != nil) { die("Can't write report: \(err!)") }
bsd-3-clause
47a522f0c4750c863dc723ae223f948e
34
139
0.65913
3.702852
false
false
false
false
StanZabroda/Hydra
Pods/Nuke/Nuke/Source/Core/ImageProcessor.swift
4
3416
// The MIT License (MIT) // // Copyright (c) 2015 Alexander Grebenyuk (github.com/kean). import UIKit public protocol ImageProcessing { func isEquivalentToProcessor(processor: ImageProcessing) -> Bool func processImage(image: UIImage) -> UIImage? } public class ImageDecompressor: ImageProcessing { public let targetSize: CGSize public let contentMode: ImageContentMode public init(targetSize: CGSize = ImageMaximumSize, contentMode: ImageContentMode = .AspectFill) { self.targetSize = targetSize self.contentMode = contentMode } public func isEquivalentToProcessor(processor: ImageProcessing) -> Bool { guard let other = processor as? ImageDecompressor else { return false } return self.targetSize == other.targetSize && self.contentMode == other.contentMode } public func processImage(image: UIImage) -> UIImage? { return decompressImage(image, targetSize: self.targetSize, contentMode: self.contentMode) } } public class ImageProcessorComposition: ImageProcessing { public let processors: [ImageProcessing] public init(processors: [ImageProcessing]) { assert(processors.count > 0) self.processors = processors } public func isEquivalentToProcessor(processor: ImageProcessing) -> Bool { guard let other = processor as? ImageProcessorComposition else { return false } guard self.processors.count == other.processors.count else { return false } for (lhs, rhs) in zip(self.processors, other.processors) { if !lhs.isEquivalentToProcessor(rhs) { return false } } return true } public func processImage(input: UIImage) -> UIImage? { return processors.reduce(input) { image, processor in return image != nil ? processor.processImage(image!) : nil } } } private func decompressImage(image: UIImage, targetSize: CGSize, contentMode: ImageContentMode) -> UIImage { let bitmapSize = CGSize(width: CGImageGetWidth(image.CGImage), height: CGImageGetHeight(image.CGImage)) let scaleWidth = targetSize.width / bitmapSize.width let scaleHeight = targetSize.height / bitmapSize.height let scale = contentMode == .AspectFill ? max(scaleWidth, scaleHeight) : min(scaleWidth, scaleHeight) return decompressImage(image, scale: Double(scale)) } private func decompressImage(image: UIImage, scale: Double) -> UIImage { let imageRef = image.CGImage var imageSize = CGSize(width: CGImageGetWidth(imageRef), height: CGImageGetHeight(imageRef)) if scale < 1.0 { imageSize = CGSize(width: Double(imageSize.width) * scale, height: Double(imageSize.height) * scale) } guard let contextRef = CGBitmapContextCreate(nil, Int(imageSize.width), Int(imageSize.height), CGImageGetBitsPerComponent(imageRef), 0, CGColorSpaceCreateDeviceRGB(), CGImageGetBitmapInfo(imageRef).rawValue) else { return image } CGContextDrawImage(contextRef, CGRect(origin: CGPointZero, size: imageSize), imageRef) guard let decompressedImageRef = CGBitmapContextCreateImage(contextRef) else { return image } return UIImage(CGImage: decompressedImageRef, scale: image.scale, orientation: image.imageOrientation) }
mit
0418436f18993ad18c21438cdfccae04
36.538462
108
0.686768
4.94356
false
false
false
false
tscholze/swift-macos-airpod-availability-checker
AirPods Pro Checker/Models.swift
1
1875
// // Models.swift // AirPods Pro Checker // // Created by Tobias Scholze on 01.11.19. // Copyright © 2019 Tobias Scholze. All rights reserved. // import Foundation // MARK: - Container - struct Container: Codable { let body: Body } // MARK: - Body - struct Body: Codable { let stores: [Store] } // MARK: - Store - struct Store: Codable { let name: String let city: String let partsAvailability: PartsAvailability enum CodingKeys: String, CodingKey { case name = "storeName" case city case partsAvailability } } // MARK: - PartsAvailability - struct PartsAvailability: Codable { let mwp22ZmA: Mwp22ZmA enum CodingKeys: String, CodingKey { case mwp22ZmA = "MWP22ZM/A" } } // MARK: - Mwp22ZmA - struct Mwp22ZmA: Codable { let pickupSearchQuote: String var sanitizedAvailableDate: String { // Parse required information from string. let today = Calendar.current.startOfDay(for: Date()) let value = pickupSearchQuote.replacingOccurrences(of: "Verfügbar<br/>", with: "") let date = DateFormatter.shortDate.date(from: "\(value) \(NSCalendar.current.component(.year, from: today))") // If given value is not a valid date, return value. guard let _date = date else { return value } // Calculate delta in days from now till availability date. let deltaToAvailbility = Int(today.distance(to: _date) / 60 / 60 / 24) // Add special formatting for known values. if deltaToAvailbility == 0 { return "Heute" } else if deltaToAvailbility == 1 { return "Morgen" } else { return "in \(deltaToAvailbility) Tagen" } } }
mit
79595e25b289ed9062f3f545df1b6ef5
19.582418
117
0.585158
3.951477
false
false
false
false
AugustRush/ARCollectionViewDynamicSizeCell
Classes/ARCollectionDynamicSizeCell.swift
1
3871
//The MIT License (MIT) // //Copyright (c) 2015 // //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 extension UICollectionView{ private struct associateKey{ static var templeCellsKey = "templeCells" } private var templeCells : [String:AnyObject] { get{ var dict = objc_getAssociatedObject(self, &associateKey.templeCellsKey) as? [String:AnyObject] if dict == nil { dict = Dictionary() objc_setAssociatedObject(self, &associateKey.templeCellsKey, dict!, UInt(OBJC_ASSOCIATION_RETAIN_NONATOMIC)) } return dict! } set{ objc_setAssociatedObject(self, &associateKey.templeCellsKey, newValue, UInt(OBJC_ASSOCIATION_RETAIN_NONATOMIC)) } } func ar_dynamicSize(reuseIdentifier:String,indexPath:NSIndexPath,configuration:((AnyObject)->Void),fixedWidth:CGFloat = 0,fixedHeight:CGFloat = 0) -> CGSize { let cell = templeCell(reuseIdentifier) as! UICollectionViewCell cell.prepareForReuse() configuration(cell) if fixedWidth > 0 && fixedHeight > 0{ return CGSizeMake(fixedWidth, fixedHeight) } var fixedValue : CGFloat = 0 var attribute : NSLayoutAttribute = NSLayoutAttribute.NotAnAttribute if fixedWidth > 0 { fixedValue = fixedWidth attribute = NSLayoutAttribute.Width }else if fixedHeight > 0{ fixedValue = fixedHeight attribute = NSLayoutAttribute.Height } let fixedLayout = NSLayoutConstraint(item: cell.contentView, attribute: attribute, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: attribute, multiplier: 1, constant: fixedValue) cell.contentView.addConstraint(fixedLayout) var size = cell.contentView.systemLayoutSizeFittingSize(UILayoutFittingCompressedSize) cell.contentView.removeConstraint(fixedLayout) return size } private func templeCell(reuseIdentifier:String) -> AnyObject { var cell: AnyObject? = templeCells[reuseIdentifier] if cell == nil{ let cellNibDict = self.valueForKey("_cellNibDict") as! [String:AnyObject] let cellNib = cellNibDict[reuseIdentifier] as! UINib cell = cellNib.instantiateWithOwner(nil, options: nil).last templeCells[reuseIdentifier] = cell } return cell! } private func templeCellsDict() -> [String:AnyObject]{ let selector = "templeCellsDict" var dict = objc_getAssociatedObject(self, selector) as? [String:AnyObject] if dict == nil { dict = Dictionary() objc_setAssociatedObject(self, selector, dict, UInt(OBJC_ASSOCIATION_RETAIN_NONATOMIC)) } return dict! } }
mit
75d9b46309a6ea1977e47447e97361bb
42.011111
197
0.679411
4.90621
false
false
false
false
smoope/swift-client-conversation
Framework/Source/ConversationInitialLoadingView.swift
1
2576
// // Copyright 2017 smoope GmbH // // 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 internal class ConversationInitialLoadingView: UIView { private var textLabel: UILabel private var activityIndicator: UIActivityIndicatorView override init(frame: CGRect) { textLabel = UILabel() textLabel.translatesAutoresizingMaskIntoConstraints = false textLabel.numberOfLines = 0 textLabel.textAlignment = .center textLabel.font = UIFont.boldSystemFont(ofSize: 15) textLabel.textColor = .darkGray activityIndicator = UIActivityIndicatorView(activityIndicatorStyle: .gray) activityIndicator.translatesAutoresizingMaskIntoConstraints = false super.init(frame: frame) autoresizingMask = [.flexibleWidth, .flexibleHeight] backgroundColor = .white addSubview(textLabel) centerXAnchor.constraint(equalTo: textLabel.centerXAnchor).isActive = true centerYAnchor.constraint(equalTo: textLabel.centerYAnchor).isActive = true textLabel.leadingAnchor.constraint(greaterThanOrEqualTo: layoutMarginsGuide.leadingAnchor).isActive = true layoutMarginsGuide.trailingAnchor.constraint(greaterThanOrEqualTo: textLabel.trailingAnchor).isActive = true textLabel.widthAnchor.constraint(lessThanOrEqualToConstant: 400).isActive = true addSubview(activityIndicator) activityIndicator.topAnchor.constraint(equalTo: textLabel.bottomAnchor, constant: 16).isActive = true activityIndicator.centerXAnchor.constraint(equalTo: textLabel.centerXAnchor).isActive = true } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func show(_ text: String, loading: Bool = false) { textLabel.text = text activityIndicator.isHidden = !loading if loading { activityIndicator.startAnimating() } } }
apache-2.0
e4f645d897854e3cd8fc9e9435e6d6b5
35.8
116
0.697205
5.737194
false
false
false
false
dxdp/Stage
Stage/PropertyBindings/UITextFieldBindings.swift
1
4617
// // UITextFieldBindings.swift // Stage // // Copyright © 2016 David Parton // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and // associated documentation files (the "Software"), to deal in the Software without restriction, // including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, // subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies // or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE // AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. import Foundation public extension StageRegister { public class func TextField(_ registration: StagePropertyRegistration) { tap(registration) { $0.registerBool("adjustsFontSizeToFitWidth") .apply { (view: UITextField, value) in view.adjustsFontSizeToFitWidth = value } $0.register("font") { scanner in try UIFont.create(using: scanner, defaultPointSize: 14) } .apply { (view: UITextField, value) in view.font = value } $0.registerCGFloat("minimumFontSize") .apply { (view: UITextField, value) in view.minimumFontSize = value } $0.registerBool("clearsOnBeginEditing") .apply { (view: UITextField, value) in view.clearsOnBeginEditing = value } $0.register("keyboardType") { scanner in try UIKeyboardType.create(using: scanner) } .apply { (view: UITextField, value) in view.keyboardType = value } $0.register("placeholder") { scanner in scanner.scanLinesTrimmed().joined(separator: "\n") } .apply { (view: UITextField, value) in view.placeholder = value } $0.registerBool("secureTextEntry") .apply { (view: UITextField, value) in view.isSecureTextEntry = value } $0.register("text") { scanner in scanner.scanLinesTrimmed().joined(separator: "\n") } .apply { (view: UITextField, value) in view.text = value } $0.register("textAlignment") { scanner in try NSTextAlignment.create(using: scanner) } .apply { (view: UITextField, value) in view.textAlignment = value } $0.registerColor("textColor") .apply { (view: UITextField, value) in view.textColor = value } $0.register("clearButtonMode") { scanner in try UITextFieldViewMode.create(using: scanner) } .apply { (view: UITextField, value) in view.clearButtonMode = value } $0.register("leftViewMode") { scanner in try UITextFieldViewMode.create(using: scanner) } .apply { (view: UITextField, value) in view.leftViewMode = value } $0.register("rightViewMode") { scanner in try UITextFieldViewMode.create(using: scanner) } .apply { (view: UITextField, value) in view.rightViewMode = value } $0.register("inputAccessoryView") { scanner in scanner.string.trimmed() } .apply { (view: UITextField, value, context) in guard let accessoryView = try? context.view(named: value) else { print("Warning. inputAccessoryView '\(value)' for UITextField not present in the StageLiveContext") return } if let superview = accessoryView.superview { accessoryView.removeFromSuperview() superview.setNeedsUpdateConstraints() } view.inputAccessoryView = accessoryView DispatchQueue.main.async { let size = accessoryView.systemLayoutSizeFitting(UIScreen.main.bounds.size) let frame = accessoryView.frame accessoryView.frame = CGRect(origin: frame.origin, size: size) } } } } }
mit
ff1e54dddc7f567beaa827d0ccfa3a64
55.987654
123
0.618718
5.066959
false
false
false
false
aktowns/swen
Sources/SwenDemo/Enemy.swift
1
1575
// // Enemy.swift created on 30/12/15 // Swen project // // Copyright 2015 Ashley Towns <[email protected]> // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // import Swen public class Enemy: Sprite, GameLoop { let walkingAnimation = ["bee", "bee_move", "bee_dead"] var enemy: Texture? var enemyMap: [String:Rect] = [:] var animationStep: Int = 0 public override func setup() { let enemySpriteMap: ImageMapFile = pipeline.get(fromPath: "assets/sprites/spritesheet_enemies.xml")! self.enemy = try? enemySpriteMap.imageFile.asTexture() self.enemyMap = enemySpriteMap.mapping let anim = enemyMap[walkingAnimation[animationStep]]! self.size = anim.size self.position = Vector(x: 820.0, y: 290.0) } public func draw(game: Game) { enemy!.render(atPoint: position, clip: enemyMap[walkingAnimation[self.animationStep / 6]]!) } public func update(game: Game) { self.animationStep += 1 if ((self.animationStep / 6) >= walkingAnimation.count) { self.animationStep = 0 } } }
apache-2.0
d307e10100465d323655b1bc34d21443
30.5
104
0.693333
3.62069
false
false
false
false
teads/TeadsSDK-iOS
TeadsSampleApp/Controllers/InRead/SAS/TableView/InReadSASTableViewController.swift
1
3871
// // InReadSASTableViewController.swift // TeadsSampleApp // // Created by Jérémy Grosjean on 19/11/2020. // Copyright © 2020 Teads. All rights reserved. // import SASDisplayKit import TeadsSASAdapter import TeadsSDK import UIKit class InReadSASTableViewController: TeadsViewController { @IBOutlet var tableView: UITableView! var banner: SASBannerView? let contentCell = "TeadsContentCell" let teadsAdCellIndentifier = "TeadsAdCell" let fakeArticleCell = "fakeArticleCell" let adRowNumber = 2 var adHeight: CGFloat? var adRatio: TeadsAdRatio? var teadsAdIsLoaded = false var tableViewAdCellWidth: CGFloat! override func viewDidLoad() { super.viewDidLoad() banner = SASBannerView(frame: CGRect(x: 0, y: 0, width: view.frame.width, height: 200), loader: .activityIndicatorStyleWhite) banner?.modalParentViewController = self let teadsAdSettings = TeadsAdapterSettings { settings in settings.enableDebug() settings.pageUrl("https://teads.tv") try? settings.registerAdView(banner!, delegate: self) } let webSiteId = 385_317 let pageId = 1_331_331 let formatId = Int(pid) ?? 96445 var keywordsTargetting = "yourkw=something" keywordsTargetting = TeadsSASAdapterHelper.concatAdSettingsToKeywords(keywordsStrings: keywordsTargetting, adSettings: teadsAdSettings) // Create a placement let adPlacement = SASAdPlacement(siteId: webSiteId, pageId: pageId, formatId: formatId, keywordTargeting: keywordsTargetting) banner?.load(with: adPlacement) } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() tableViewAdCellWidth = tableView.frame.width - 20 } @objc func rotationDetected() { if let adRatio = adRatio { resizeTeadsAd(adRatio: adRatio) } } func resizeTeadsAd(adRatio: TeadsAdRatio) { adHeight = adRatio.calculateHeight(for: tableViewAdCellWidth) updateAdCellHeight() } func closeSlot() { adHeight = 0 updateAdCellHeight() } func updateAdCellHeight() { tableView.reloadRows(at: [IndexPath(row: adRowNumber, section: 0)], with: .automatic) } } extension InReadSASTableViewController: UITableViewDelegate, UITableViewDataSource { func tableView(_: UITableView, numberOfRowsInSection _: Int) -> Int { return 4 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { switch indexPath.row { case 0: let cell = tableView.dequeueReusableCell(withIdentifier: contentCell, for: indexPath) return cell case adRowNumber: // need to create a cell and just add a teadsAd to it, so we have only one teads ad let cellAd = tableView.dequeueReusableCell(withIdentifier: teadsAdCellIndentifier, for: indexPath) if let banner = banner { cellAd.addSubview(banner) banner.frame = CGRect(x: 10, y: 0, width: tableViewAdCellWidth, height: adHeight ?? 250) } return cellAd default: let cell = tableView.dequeueReusableCell(withIdentifier: fakeArticleCell, for: indexPath) return cell } } func tableView(_: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { if indexPath.row == adRowNumber { return adHeight ?? 0 } else { return UITableView.automaticDimension } } } extension InReadSASTableViewController: TeadsMediatedAdViewDelegate { func didUpdateRatio(_: UIView, adRatio: TeadsAdRatio) { self.adRatio = adRatio resizeTeadsAd(adRatio: adRatio) } }
mit
9e8057085d50db16d10d39ec307637e6
33.230088
143
0.657704
4.482039
false
false
false
false
noxytrux/ButtonsGoodPracticeTutorial
FlatButtons/UIColor+Extension.swift
1
1369
// // UIColor+Extension.swift // FlatButtons // // Created by Marcin Pędzimąż on 24.09.2014. // Copyright (c) 2014 Marcin Pedzimaz. All rights reserved. // import UIKit extension UIColor { class func colorWithHex(hexString: String?, alpha: CGFloat = 1.0) -> UIColor? { if let hexString = hexString { var error : NSError? = nil let regexp = NSRegularExpression(pattern: "\\A#[0-9a-f]{6}\\z", options: .CaseInsensitive, error: &error) let count = regexp.numberOfMatchesInString(hexString, options: .ReportProgress, range: NSMakeRange(0, countElements(hexString))) if count != 1 { return nil } var rgbValue : UInt32 = 0 let scanner = NSScanner(string: hexString) scanner.scanLocation = 1 scanner.scanHexInt(&rgbValue) let red = CGFloat( (rgbValue & 0xFF0000) >> 16) / 255.0 let green = CGFloat( (rgbValue & 0xFF00) >> 8) / 255.0 let blue = CGFloat( (rgbValue & 0xFF) ) / 255.0 return UIColor(red: red, green: green, blue: blue, alpha: alpha) } return nil } }
mit
f96b690b22177a6dbc06f02974a44505
26.877551
83
0.500732
4.630508
false
false
false
false
7ulipa/ReactiveDataSource
Example/ReactiveDataSource/ViewController.swift
1
896
// // ViewController.swift // ReactiveDataSource // // Created by Tulipa on 11/07/2016. // Copyright (c) 2016 Tulipa. All rights reserved. // import UIKit class ViewController: UIViewController, UICollectionViewDelegateFlowLayout { let viewModel: ViewModel = ViewModel() override func viewDidLoad() { super.viewDidLoad() let layout = UICollectionViewFlowLayout() layout.itemSize = CGSize(width: 100, height: 100) let collectionView = UICollectionView(frame: view.bounds, collectionViewLayout: layout) collectionView.delegate = self collectionView.dataSource = viewModel collectionView.backgroundColor = UIColor.white view.addSubview(collectionView) MyCell.register(for: collectionView) viewModel.delegate = collectionView viewModel.refresh() } }
mit
e77c2e1f8769d08b39595ad7afa57acb
25.352941
95
0.669643
5.301775
false
false
false
false
llxyls/DYTV
DYTV/DYTV/Classes/Main/Model/AnchorModel.swift
1
822
// // AnchorModel.swift // DYTV // // Created by liuqi on 16/10/28. // Copyright © 2016年 liuqi. All rights reserved. // import UIKit class AnchorModel: NSObject { // MARK: - 属性 /// 房间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
28f48314887ce63b248bd3c360fcf7fb
17.538462
72
0.542185
3.544118
false
false
false
false
jemmons/SessionArtist
Sources/SessionArtist/URL+PathMatcher.swift
1
2044
import Foundation public extension URL { @available(*, deprecated, message: "This functionality has been moved to `MyNameIsURL` (https://github.com/jemmons/MyNameIsURL)") struct Host { private let host: String public init(_ host: String) { self.host = host } public static func ~= (pattern: URL.Host, value: URL) -> Bool { return pattern.host == value.host } } @available(*, deprecated, message: "This functionality has been moved to `MyNameIsURL` (https://github.com/jemmons/MyNameIsURL)") struct Path { private let pathRepresentation: PathRepresentation public init(_ path: String) { pathRepresentation = .string(path) } public init(_ components: [String]) { pathRepresentation = .components(components) } public static func ~= (pattern: URL.Path, value: URL) -> Bool { switch pattern.pathRepresentation { case .string(let path): return path == value.path case .components(let components): return components == value.pathComponents } } } @available(*, deprecated, message: "This functionality has been moved to `MyNameIsURL` (https://github.com/jemmons/MyNameIsURL)") struct PathPrefix { private let pathPrefixRepresentation: PathRepresentation public init(_ pathPrefix: String) { pathPrefixRepresentation = .string(pathPrefix) } public init(_ components: [String]) { pathPrefixRepresentation = .components(components) } public static func ~= (pattern: URL.PathPrefix, value: URL) -> Bool { switch pattern.pathPrefixRepresentation { case .string(let path): return value.path.hasPrefix(path) case .components(let components): let valueComponentsPrefix = Array(value.pathComponents.prefix(components.count)) return valueComponentsPrefix == components } } } } private enum PathRepresentation { case string(String) case components([String]) }
mit
1e55bd24d58ab2d4ebf018c92282c014
24.55
131
0.653131
4.443478
false
false
false
false
brentdax/swift
test/IRGen/lazy_multi_file.swift
2
1199
// RUN: %target-swift-frontend -assume-parsing-unqualified-ownership-sil -primary-file %s %S/Inputs/lazy_multi_file_helper.swift -emit-ir | %FileCheck %s // REQUIRES: CPU=i386 || CPU=x86_64 // CHECK: %T15lazy_multi_file8SubclassC = type <{ %swift.refcounted, %[[OPTIONAL_INT_TY:TSiSg]], [{{[0-9]+}} x i8], %TSS }> // CHECK: %[[OPTIONAL_INT_TY]] = type <{ [{{[0-9]+}} x i8], [1 x i8] }> // CHECK: %T15lazy_multi_file13LazyContainerV = type <{ %[[OPTIONAL_INT_TY]] }> class Subclass : LazyContainerClass { final var str = "abc" // FIXME(TODO: JIRA): i386 String grew beyond 3 words, so we have to allow // an indirect return value. When it shrinks back, remove the optional // indirect out. // // CHECK-LABEL: @"$s15lazy_multi_file8SubclassC6getStrSSyF"({{(\%TSS\* noalias nocapture sret, )?}}%T15lazy_multi_file8SubclassC* swiftself) {{.*}} { func getStr() -> String { // CHECK: = getelementptr inbounds %T15lazy_multi_file8SubclassC, %T15lazy_multi_file8SubclassC* %0, i32 0, i32 3 return str } } // CHECK-LABEL: @"$s15lazy_multi_file4testSiyF"() {{.*}} { func test() -> Int { var container = LazyContainer() useLazyContainer(container) return container.lazyVar }
apache-2.0
b8e59c780b1e543cb046e3d1b58ba3b4
41.821429
153
0.668057
3.171958
false
true
false
false
exyte/Macaw
MacawTests/Animation/DelayedAnimationTests.swift
1
1632
// // DelayedAnimationTests.swift // Macaw // // Created by Victor Sukochev on 21/02/2017. // Copyright © 2017 Exyte. All rights reserved. // import XCTest #if os(OSX) @testable import MacawOSX #elseif os(iOS) @testable import Macaw #endif class DelayedAnimationTests: XCTestCase { var testView: MacawView! var testGroup: Group! var window: MWindow! override func setUp() { super.setUp() testGroup = [Shape(form:Rect(x: 0.0, y: 0.0, w: 0.0, h: 0.0))].group() testView = MacawView(node: testGroup, frame: .zero) window = MWindow() window.addSubview(testView) } func testStates() { let animation = testGroup.placeVar.animation(to: Transform.move(dx: 1.0, dy: 1.0), delay: 1000.0) as! TransformAnimation animation.play() let playExpectation = expectation(description: "play expectation") DispatchQueue.main.asyncAfter(deadline: .now() + 1.0) { playExpectation.fulfill() } self.waitForExpectations(timeout: 2.0) { error in XCTAssertNil(error, "Async test failed") } animation.pause() let pauseExpectation = expectation(description: "pause expectation") DispatchQueue.main.asyncAfter(deadline: .now() + 1.0) { pauseExpectation.fulfill() } self.waitForExpectations(timeout: 2.0) { error in XCTAssertNil(error, "Async test failed") } XCTAssert(animation.paused && !animation.manualStop, "Wrong animation state on pause") } }
mit
510a2c34e84ee816d3bb3a920c97c94a
27.12069
128
0.604537
4.182051
false
true
false
false
randallli/material-components-ios
components/FlexibleHeader/tests/unit/FlexibleHeaderInjectionTopLayoutGuideTests.swift
1
7944
/* Copyright 2018-present the Material Components for iOS authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ import XCTest import MaterialComponents.MaterialFlexibleHeader import MaterialComponents.MaterialUIMetrics class FlexibleHeaderInjectionTopLayoutGuideTests: XCTestCase { var fhvc: MDCFlexibleHeaderViewController! override func setUp() { super.setUp() fhvc = MDCFlexibleHeaderViewController() fhvc.isTopLayoutGuideAdjustmentEnabled = true fhvc.headerView.minMaxHeightIncludesSafeArea = false fhvc.headerView.minimumHeight = 50 fhvc.headerView.maximumHeight = 100 } override func tearDown() { fhvc = nil super.tearDown() } // MARK: No scroll view func testNoScrollViewTopLayoutGuideEqualsBottomEdgeOfHeaderView() { // Given let contentViewController = UIViewController() contentViewController.addChildViewController(fhvc) contentViewController.view.addSubview(fhvc.view) fhvc.didMove(toParentViewController: contentViewController) // Then XCTAssertEqual(contentViewController.topLayoutGuide.length, fhvc.headerView.frame.maxY) #if swift(>=3.2) if #available(iOS 11.0, *) { XCTAssertEqual(contentViewController.additionalSafeAreaInsets.top, fhvc.headerView.frame.maxY - MDCDeviceTopSafeAreaInset()) } #endif } // MARK: Untracked table view func testUntrackedTableViewTopLayoutGuideEqualsBottomEdgeOfHeaderView() { // Given let contentViewController = UITableViewController() contentViewController.addChildViewController(fhvc) contentViewController.view.addSubview(fhvc.view) fhvc.didMove(toParentViewController: contentViewController) // Then XCTAssertEqual(contentViewController.topLayoutGuide.length, fhvc.headerView.frame.maxY) #if swift(>=3.2) if #available(iOS 11.0, *) { XCTAssertEqual(contentViewController.additionalSafeAreaInsets.top, fhvc.headerView.frame.maxY - MDCDeviceTopSafeAreaInset()) XCTAssertEqual(contentViewController.tableView.adjustedContentInset.top, 0) } #endif } // MARK: Tracked table view func testTrackedTableViewTopLayoutGuideEqualsBottomEdgeOfHeaderView() { // Given let contentViewController = UITableViewController() fhvc.headerView.trackingScrollView = contentViewController.tableView contentViewController.addChildViewController(fhvc) contentViewController.view.addSubview(fhvc.view) fhvc.didMove(toParentViewController: contentViewController) fhvc.headerView.trackingScrollDidScroll() // Then XCTAssertEqual(contentViewController.topLayoutGuide.length, fhvc.headerView.frame.maxY) #if swift(>=3.2) if #available(iOS 11.0, *) { XCTAssertEqual(contentViewController.additionalSafeAreaInsets.top, 0) XCTAssertEqual(contentViewController.tableView.adjustedContentInset.top, fhvc.headerView.maximumHeight + MDCDeviceTopSafeAreaInset()) } #endif } func testTrackedTableViewTopLayoutGuideEqualsBottomEdgeOfHeaderViewAfterScrolling() { // Given let contentViewController = UITableViewController() contentViewController.tableView.contentSize = CGSize(width: contentViewController.tableView.bounds.width, height: contentViewController.tableView.bounds.height * 2) fhvc.headerView.trackingScrollView = contentViewController.tableView contentViewController.addChildViewController(fhvc) contentViewController.view.addSubview(fhvc.view) fhvc.didMove(toParentViewController: contentViewController) fhvc.headerView.trackingScrollDidScroll() contentViewController.tableView.contentOffset = CGPoint(x: 0, y: -contentViewController.tableView.contentInset.top) fhvc.headerView.trackingScrollDidScroll() // Then XCTAssertEqual(contentViewController.topLayoutGuide.length, fhvc.headerView.frame.maxY) #if swift(>=3.2) if #available(iOS 11.0, *) { XCTAssertEqual(contentViewController.additionalSafeAreaInsets.top, 0) XCTAssertEqual(contentViewController.tableView.adjustedContentInset.top, fhvc.headerView.maximumHeight + MDCDeviceTopSafeAreaInset()) } #endif } // MARK: Untracked collection view func testUntrackedCollectionViewTopLayoutGuideEqualsBottomEdgeOfHeaderView() { // Given let flow = UICollectionViewFlowLayout() let contentViewController = UICollectionViewController(collectionViewLayout: flow) contentViewController.addChildViewController(fhvc) contentViewController.view.addSubview(fhvc.view) fhvc.didMove(toParentViewController: contentViewController) // Then XCTAssertEqual(contentViewController.topLayoutGuide.length, fhvc.headerView.frame.maxY) #if swift(>=3.2) if #available(iOS 11.0, *) { XCTAssertEqual(contentViewController.additionalSafeAreaInsets.top, fhvc.headerView.frame.maxY - MDCDeviceTopSafeAreaInset()) XCTAssertEqual(contentViewController.collectionView!.adjustedContentInset.top, 0) } #endif } // MARK: Tracked collection view view func testTrackedCollectionViewTopLayoutGuideEqualsBottomEdgeOfHeaderView() { // Given let flow = UICollectionViewFlowLayout() let contentViewController = UICollectionViewController(collectionViewLayout: flow) fhvc.headerView.trackingScrollView = contentViewController.collectionView contentViewController.addChildViewController(fhvc) contentViewController.view.addSubview(fhvc.view) fhvc.didMove(toParentViewController: contentViewController) fhvc.headerView.trackingScrollDidScroll() // Then XCTAssertEqual(contentViewController.topLayoutGuide.length, fhvc.headerView.frame.maxY) #if swift(>=3.2) if #available(iOS 11.0, *) { XCTAssertEqual(contentViewController.additionalSafeAreaInsets.top, 0) XCTAssertEqual(contentViewController.collectionView!.adjustedContentInset.top, fhvc.headerView.maximumHeight + MDCDeviceTopSafeAreaInset()) } #endif } func testTrackedCollectionViewTopLayoutGuideEqualsBottomEdgeOfHeaderViewAfterScrolling() { // Given let flow = UICollectionViewFlowLayout() let contentViewController = UICollectionViewController(collectionViewLayout: flow) contentViewController.collectionView!.contentSize = CGSize(width: contentViewController.collectionView!.bounds.width, height: contentViewController.collectionView!.bounds.height * 2) fhvc.headerView.trackingScrollView = contentViewController.collectionView! contentViewController.addChildViewController(fhvc) contentViewController.view.addSubview(fhvc.view) fhvc.didMove(toParentViewController: contentViewController) fhvc.headerView.trackingScrollDidScroll() contentViewController.collectionView!.contentOffset = CGPoint(x: 0, y: -contentViewController.collectionView!.contentInset.top) fhvc.headerView.trackingScrollDidScroll() // Then XCTAssertEqual(contentViewController.topLayoutGuide.length, fhvc.headerView.frame.maxY) #if swift(>=3.2) if #available(iOS 11.0, *) { XCTAssertEqual(contentViewController.additionalSafeAreaInsets.top, 0) XCTAssertEqual(contentViewController.collectionView!.adjustedContentInset.top, fhvc.headerView.maximumHeight + MDCDeviceTopSafeAreaInset()) } #endif } }
apache-2.0
72b523c234195cd625b89f3026192a2c
38.522388
92
0.764476
5.292472
false
false
false
false