hexsha
stringlengths
40
40
size
int64
3
1.03M
content
stringlengths
3
1.03M
avg_line_length
float64
1.33
100
max_line_length
int64
2
1k
alphanum_fraction
float64
0.25
0.99
2f0a88422e8c61210821e8b6dffb0b78af84b187
1,539
// // Created by Shaban Kamel on 05/02/2020. // Copyright (c) 2020 sha. All rights reserved. // import UIKit public class ItemPicker<T: CustomStringConvertible>: UIPickerView, UIPickerViewDataSource, UIPickerViewDelegate { private var list: [T] = [] private var callback: ((T) -> Void)! private var isFirstDisplay = true public func create( list: [T], callback: @escaping (T) -> Void ) -> ItemPicker<T>{ self.list = list self.callback = callback delegate = self dataSource = self return self } public func numberOfComponents(in pickerView: UIPickerView) -> Int { 1 } public func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { list.count } public func pickerView( _ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? { selectDefaultItem(row: row) return list[row].description } private func selectDefaultItem(row: Int) { guard isFirstDisplay, row == 0 else { return } // select the first item on the first display callback(list[row]) isFirstDisplay = false } public func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) { callback(list[row]) } public override func didUpdateFocus(in context: UIFocusUpdateContext, with coordinator: UIFocusAnimationCoordinator) { super.didUpdateFocus(in: context, with: coordinator) } }
32.744681
122
0.666017
1c8a04315922b4a3d0ea5184c2c40e22c7cdf274
18,617
// // ESPullToRefresh.swift // // Created by egg swift on 16/4/7. // Copyright (c) 2013-2016 ESPullToRefresh (https://github.com/eggswift/pull-to-refresh) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Foundation import UIKit public enum ESRefreshViewState { case loading case pullToRefresh case releaseToRefresh case noMoreData } private var kESRefreshHeaderKey: String = "" private var kESRefreshFooterKey: String = "" public extension UIScrollView { /// Pull-to-refresh associated property public var es_header: ESRefreshHeaderView? { get { return (objc_getAssociatedObject(self, &kESRefreshHeaderKey) as? ESRefreshHeaderView) } set(newValue) { objc_setAssociatedObject(self, &kESRefreshHeaderKey, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN) } } /// Infinitiy scroll associated property public var es_footer: ESRefreshFooterView? { get { return (objc_getAssociatedObject(self, &kESRefreshFooterKey) as? ESRefreshFooterView) } set(newValue) { objc_setAssociatedObject(self, &kESRefreshFooterKey, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN) } } /// Add pull-to-refresh public func es_addPullToRefresh(handler: @escaping ESRefreshHandler) -> ESRefreshHeaderView { es_removeRefreshHeader() let header = ESRefreshHeaderView(frame: CGRect.zero, handler: handler) let headerH = header.animator.executeIncremental header.frame = CGRect.init(x: 0.0, y: -headerH /* - contentInset.top */, width: bounds.size.width, height: headerH) addSubview(header) es_header = header return header } public func es_addPullToRefresh(animator: ESRefreshProtocol & ESRefreshAnimatorProtocol, handler: @escaping ESRefreshHandler) -> ESRefreshHeaderView { es_removeRefreshHeader() let header = ESRefreshHeaderView(frame: CGRect.zero, handler: handler, customAnimator: animator) let headerH = animator.executeIncremental header.frame = CGRect.init(x: 0.0, y: -headerH /* - contentInset.top */, width: bounds.size.width, height: headerH) addSubview(header) es_header = header return header } /// Add infinite-scrolling public func es_addInfiniteScrolling(handler: @escaping ESRefreshHandler) -> ESRefreshFooterView { es_removeRefreshFooter() let footer = ESRefreshFooterView(frame: CGRect.zero, handler: handler) let footerH = footer.animator.executeIncremental footer.frame = CGRect.init(x: 0.0, y: contentSize.height + contentInset.bottom, width: bounds.size.width, height: footerH) addSubview(footer) es_footer = footer return footer } public func es_addInfiniteScrolling(animator: ESRefreshProtocol & ESRefreshAnimatorProtocol, handler: @escaping ESRefreshHandler) -> ESRefreshFooterView { es_removeRefreshFooter() let footer = ESRefreshFooterView(frame: CGRect.zero, handler: handler, customAnimator: animator) let footerH = footer.animator.executeIncremental footer.frame = CGRect.init(x: 0.0, y: contentSize.height + contentInset.bottom, width: bounds.size.width, height: footerH) es_footer = footer addSubview(footer) return footer } /// Remove public func es_removeRefreshHeader() { es_header?.loading = false es_header?.removeFromSuperview() es_header = nil } public func es_removeRefreshFooter() { es_footer?.loading = false es_footer?.removeFromSuperview() es_footer = nil } /// Manual refresh public func es_startPullToRefresh() { DispatchQueue.main.async { [weak self] in guard let weakSelf = self else { return } UIView.performWithoutAnimation { weakSelf.es_header?.loading = true } } } /// Auto refresh if expried. public func es_autoPullToRefresh() { if self.expried == true { es_startPullToRefresh() } } /// Stop pull to refresh public func es_stopPullToRefresh(completion: Bool, ignoreFooter: Bool) { es_header?.loading = false if completion { // Refresh succeed if let key = self.es_header?.refreshIdentifier { ESRefreshDataManager.sharedManager.setDate(Date(), forKey: key) } es_footer?.resetNoMoreData() } es_footer?.isHidden = ignoreFooter } public func es_stopPullToRefresh(completion: Bool) { es_stopPullToRefresh(completion: completion, ignoreFooter: false) } /// Footer notice method public func es_noticeNoMoreData() { es_footer?.loading = false es_footer?.noMoreData = true } public func es_resetNoMoreData() { es_footer?.noMoreData = false } public func es_stopLoadingMore() { es_footer?.loading = false } } public extension UIScrollView /* Date Manager */ { /// Identifier for cache expried timeinterval and last refresh date. public var refreshIdentifier: String? { get { return self.es_header?.refreshIdentifier } set { self.es_header?.refreshIdentifier = newValue } } /// If you setted refreshIdentifier and expriedTimeInterval, return nearest refresh expried or not. Default is false. public var expried: Bool { get { if let key = self.es_header?.refreshIdentifier { return ESRefreshDataManager.sharedManager.isExpried(forKey: key) } return false } } public var expriedTimeInterval: TimeInterval? { get { if let key = self.es_header?.refreshIdentifier { let interval = ESRefreshDataManager.sharedManager.expriedTimeInterval(forKey: key) return interval } return nil } set { if let key = self.es_header?.refreshIdentifier { ESRefreshDataManager.sharedManager.setExpriedTimeInterval(newValue, forKey: key) } } } /// Auto cached last refresh date when you setted refreshIdentifier. public var lastRefreshDate: Date? { get { if let key = self.es_header?.refreshIdentifier { return ESRefreshDataManager.sharedManager.date(forKey: key) } return nil } } } open class ESRefreshHeaderView: ESRefreshComponent { fileprivate var previousOffset: CGFloat = 0.0 fileprivate var bounces: Bool = false fileprivate var scrollViewInsets: UIEdgeInsets = UIEdgeInsets.zero open var lastRefreshTimestamp: TimeInterval? open var refreshIdentifier: String? public convenience init(frame: CGRect, handler: @escaping ESRefreshHandler) { self.init(frame: frame) self.handler = handler self.animator = ESRefreshHeaderAnimator.init() } open override func willMove(toSuperview newSuperview: UIView?) { super.willMove(toSuperview: newSuperview) /* DispatchQueue.main.async { [weak self] in // It's better } */ } open override func didMoveToSuperview() { super.didMoveToSuperview() DispatchQueue.main.async { [weak self] in guard let weakSelf = self else { return } weakSelf.bounces = weakSelf.scrollView?.bounces ?? false weakSelf.scrollViewInsets = weakSelf.scrollView?.contentInset ?? UIEdgeInsets.zero } } open override func offsetChangeAction(object: AnyObject?, change: [NSKeyValueChangeKey : Any]?) { guard let scrollView = scrollView else { return } super.offsetChangeAction(object: object, change: change) var update = false // Check needs re-set animator's progress or not. let offsetWithoutInsets = previousOffset + scrollViewInsets.top if offsetWithoutInsets < -self.animator.trigger { // Reached critical if loading == false && animating == false { if scrollView.isDragging == false { // Start to refresh! self.loading = true } else { // Release to refresh! Please drop down hard... self.animator.refresh(view: self, stateDidChange: .releaseToRefresh) update = true } } } else if offsetWithoutInsets < 0 { // Pull to refresh! if loading == false && animating == false { self.animator.refresh(view: self, stateDidChange: .pullToRefresh) update = true } } else { // Normal state } defer { previousOffset = scrollView.contentOffset.y if update == true { let percent = -(previousOffset + scrollViewInsets.top) / self.animator.trigger self.animator.refresh(view: self, progressDidChange: percent) } } } open override func startAnimating() { guard let scrollView = scrollView else { return } super.startAnimating() self.animator.refreshAnimationDidBegin(self) // 缓存scrollview当前的contentInset, 并根据animator的executeIncremental属性计算刷新时所需要的contentInset,它将在接下来的动画中应用。 // Tips: 这里将self.scrollViewInsets.top更新,也可以将scrollViewInsets整个更新,因为left、right、bottom属性都没有用到,如果接下来的迭代需要使用这三个属性的话,这里可能需要额外的处理。 var insets = scrollView.contentInset self.scrollViewInsets.top = insets.top insets.top += animator.executeIncremental // We need to restore previous offset because we will animate scroll view insets and regular scroll view animating is not applied then. scrollView.contentOffset.y = previousOffset scrollView.bounces = false UIView.animate(withDuration: 0.2, delay: 0, options: .curveLinear, animations: { scrollView.contentInset = insets scrollView.contentOffset = CGPoint.init(x: scrollView.contentOffset.x, y: -insets.top) }, completion: { (finished) in self.animator.refresh(view: self, stateDidChange: .loading) // Loading state self.handler?() }) } open override func stopAnimating() { guard let scrollView = scrollView else { return } self.animator.refreshAnimationDidEnd(self) self.animator.refresh(view: self, stateDidChange: .pullToRefresh) scrollView.bounces = self.bounces UIView.animate(withDuration: 0.3, delay: 0, options: .curveLinear, animations: { scrollView.contentInset.top = self.scrollViewInsets.top self.animator.refresh(view: self, progressDidChange: 0.0) // If you need to complete with animation }, completion: { (finished) in super.stopAnimating() }) } } open class ESRefreshFooterView: ESRefreshComponent { fileprivate var scrollViewInsets: UIEdgeInsets = UIEdgeInsets.zero open var noMoreData = false { didSet { if noMoreData != oldValue { if noMoreData { self.animator.refresh(view: self, stateDidChange: .noMoreData) } else { self.animator.refresh(view: self, stateDidChange: .pullToRefresh) } } } } open override var isHidden: Bool { didSet { if isHidden == true { scrollView?.contentInset.bottom = scrollViewInsets.bottom var rect = self.frame rect.origin.y = scrollView?.contentSize.height ?? 0.0 self.frame = rect } else { scrollView?.contentInset.bottom = scrollViewInsets.bottom + animator.executeIncremental var rect = self.frame rect.origin.y = scrollView?.contentSize.height ?? 0.0 self.frame = rect } } } public convenience init(frame: CGRect, handler: @escaping ESRefreshHandler) { self.init(frame: frame) self.handler = handler self.animator = ESRefreshFooterAnimator.init() } open override func willMove(toSuperview newSuperview: UIView?) { super.willMove(toSuperview: newSuperview) /* DispatchQueue.main.async { [weak self] in // It's better } */ } /** In didMoveToSuperview, it will cache superview(UIScrollView)'s contentInset and update self's frame. It called ESRefreshComponent's didMoveToSuperview. */ open override func didMoveToSuperview() { super.didMoveToSuperview() DispatchQueue.main.async { [weak self] in guard let weakSelf = self else { return } weakSelf.scrollViewInsets = weakSelf.scrollView?.contentInset ?? UIEdgeInsets.zero weakSelf.scrollView?.contentInset.bottom = weakSelf.scrollViewInsets.bottom + weakSelf.bounds.size.height var rect = weakSelf.frame rect.origin.y = weakSelf.scrollView?.contentSize.height ?? 0.0 weakSelf.frame = rect } } open override func sizeChangeAction(object: AnyObject?, change: [NSKeyValueChangeKey : Any]?) { guard let scrollView = scrollView else { return } super.sizeChangeAction(object: object, change: change) let targetY = scrollView.contentSize.height + scrollViewInsets.bottom if self.frame.origin.y != targetY { var rect = self.frame rect.origin.y = targetY self.frame = rect } } open override func offsetChangeAction(object: AnyObject?, change: [NSKeyValueChangeKey : Any]?) { guard let scrollView = scrollView else { return } super.offsetChangeAction(object: object, change: change) if self.loading == true || self.noMoreData == true || animating == true || isHidden == true { // 正在loading more或者内容为空时不相应变化 return } if scrollView.contentSize.height <= 0.0 || scrollView.contentOffset.y + scrollView.contentInset.top <= 0.0 { self.alpha = 0.0 return } else { self.alpha = 1.0 } if scrollView.contentSize.height + scrollView.contentInset.top > scrollView.bounds.size.height { // 内容超过一个屏幕 计算公式,判断是不是在拖在到了底部 if scrollView.contentSize.height - scrollView.contentOffset.y + scrollView.contentInset.bottom <= scrollView.bounds.size.height { self.loading = true } } else { //内容没有超过一个屏幕,这时拖拽高度大于1/2footer的高度就表示请求上拉 if scrollView.contentOffset.y + scrollView.contentInset.top >= animator.trigger / 2.0 { self.loading = true } } } open override func startAnimating() { if let _ = scrollView { super.startAnimating() self.animator.refreshAnimationDidBegin(self) UIView.animate(withDuration: 0.3, delay: 0.0, options: .curveLinear, animations: { if let scrollView = self.scrollView { let x = scrollView.contentOffset.x let y = max(0.0, scrollView.contentSize.height - scrollView.bounds.size.height + scrollView.contentInset.bottom) scrollView.contentOffset = CGPoint.init(x: x, y: y) } }, completion: { (animated) in self.animator.refresh(view: self, stateDidChange: .loading) self.handler?() }) } } open override func stopAnimating() { guard let scrollView = scrollView else { return } self.animator.refreshAnimationDidEnd(self) self.animator.refresh(view: self, stateDidChange: .pullToRefresh) UIView .animate(withDuration: 0.3, delay: 0, options: .curveLinear, animations: { self.animator.refresh(view: self, progressDidChange: 0.0) }) { (finished) in super.stopAnimating() } // Stop deceleration of UIScrollView. When the button tap event is caught, you read what the [scrollView contentOffset].x is, and set the offset to this value with animation OFF. // http://stackoverflow.com/questions/2037892/stop-deceleration-of-uiscrollview if scrollView.isDecelerating { var contentOffset = scrollView.contentOffset contentOffset.y = min(contentOffset.y, scrollView.contentSize.height - scrollView.frame.size.height) if contentOffset.y < 0.0 { contentOffset.y = 0.0 UIView.animate(withDuration: 0.1, animations: { scrollView.setContentOffset(contentOffset, animated: false) }) } else { scrollView.setContentOffset(contentOffset, animated: false) } } } /// Change to no-more-data status. open func noticeNoMoreData() { self.noMoreData = true } /// Reset no-more-data status. open func resetNoMoreData() { self.noMoreData = false } }
39.276371
187
0.625289
267bf57e04dcf5cde305efe08f997f63e709b240
3,848
// // AnyResource.swift // Foto // // Created by Ilya Kharabet on 25.03.17. // Copyright © 2017 Mesterra. All rights reserved. // import Photos public enum ResourceSource { case library case cloud case iTunes init(sourceType: PHAssetSourceType) { if sourceType == .typeCloudShared { self = .cloud } else if sourceType == .typeiTunesSynced { self = .iTunes } else { self = .library } } public var canDelete: Bool { return self != .iTunes } public var canEdit: Bool { return self == .library } } protocol AnyResourceStore { func remove(object: AnyResource) } // MARK: - Any resource /// Base class of gallery object. public class AnyResource { public class var mediaType: PHAssetMediaType { return .unknown } let asset: PHAsset let store: AnyResourceStore var pendingRequests: [PHImageRequestID] = [] init(asset: PHAsset, store: AnyResourceStore) { self.asset = asset self.store = store } // MARK: Object properties /// Source of object lazy public var source: ResourceSource = { return ResourceSource(sourceType: self.asset.sourceType) }() lazy public var filename: String? = { return self.asset.value(forKey: "filename") as? String }() /// Pixel size of object lazy public var size: CGSize = { return CGSize(width: self.asset.pixelWidth, height: self.asset.pixelHeight) }() /// Creation date of object lazy public var creationDate: Date? = { return self.asset.creationDate }() /// Modification date of object lazy public var modificationDate: Date? = { return self.asset.modificationDate }() /// The location saved with the object lazy public var location: CLLocation? = { return self.asset.location }() /// A boolean value that indicates whether the user has hidden the object lazy public var isHidden: Bool = { return self.asset.isHidden }() /// A Boolean value that indicates whether the user has marked the asset as a favorite lazy public var isFavorite: Bool = { return self.asset.isFavorite }() } // MARK: - Object methods extension AnyResource { /** Checks that operation can be performed - Parameter editOperation: Operation */ public func canPerform(_ editOperation: PHAssetEditOperation) -> Bool { return asset.canPerform(editOperation) } /** Removes itself */ public func remove() { store.remove(object: self) } } // MARK: - Pending requests managing extension AnyResource { func performPendignRequestsChange(_ change: () -> Void) { objc_sync_enter(self) change() objc_sync_exit(self) } func removePendingRequest(with id: PHImageRequestID) { performPendignRequestsChange { if let index = pendingRequests.index(of: id) { pendingRequests.remove(at: index) } } } } // MARK: - Load request cancellation extension AnyResource { public func cancelLastRequest() { performPendignRequestsChange { guard let lastRequestID = pendingRequests.last else { return } PHImageManager.default().cancelImageRequest(lastRequestID) pendingRequests.removeLast() } } } // MARK: - Hashable extension AnyResource: Hashable { public static func ==(lhs: AnyResource, rhs: AnyResource) -> Bool { return lhs.asset == rhs.asset } public var hashValue: Int { return asset.hashValue } }
21.027322
90
0.599272
0e0e291f4120aa00a7da21a49bfdffd8892d3246
225
// // PostRowItem.swift // Posts // // Created by Joshua Simmons on 19/03/2019. // Copyright © 2019 Joshua. All rights reserved. // import Foundation struct PostRowItem { let title: String let author: String? }
15
49
0.671111
1d8117b62ce4baaa1664d3a56393c1c6bfd706ad
2,616
// // FindWorkAnnotationView.swift // MoYu // // Created by lxb on 2016/11/28. // Copyright © 2016年 Chris. All rights reserved. // import UIKit class FindWorkAnnotationView: BMKAnnotationView { //MARK: - life cycle override init!(annotation: BMKAnnotation!, reuseIdentifier: String!) { super.init(annotation: annotation, reuseIdentifier: reuseIdentifier) self.bounds = CGRect(x: 0, y: 0, width: 60, height: 64) self.backgroundColor = UIColor.clear setupView() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } //MARK: - public method func updateSelect(status isSelected:Bool){ if isSelected { self.bounds = CGRect(x: 0, y: 0, width: 80, height: 85) avatorImageView.snp.updateConstraints{ (make) in make.size.equalTo(CGSize(width: 66, height: 66)) } annotationImageView.image = UIImage(named: "avatarActiveBg") let pointY = (85.0 - 64.0/2.0)/85.0 self.layer.anchorPoint = CGPoint(x: 0.5, y: pointY) }else{ self.bounds = CGRect(x: 0, y: 0, width: 60, height: 64) avatorImageView.snp.updateConstraints{ (make) in make.size.equalTo(CGSize(width: 46, height: 46)) } annotationImageView.image = UIImage(named: "avatarBg") self.layer.anchorPoint = CGPoint(x: 0.5, y: 0.5) } self.layoutIfNeeded() } //MARK: - private method private func setupView(){ self.addSubview(annotationImageView) annotationImageView.snp.makeConstraints { (make) in make.edges.equalTo(self) } annotationImageView.addSubview(avatorImageView) avatorImageView.snp.makeConstraints { (make) in make.size.equalTo(CGSize(width: 46, height: 46)) make.centerX.equalTo(annotationImageView) make.centerY.equalTo(annotationImageView).offset(-4) } } //MARK: - var & let private let annotationImageView:UIImageView = { let imageView = UIImageView() imageView.contentMode = .scaleAspectFit imageView.image = UIImage(named: "avatarBg") return imageView }() private let avatorImageView:UIImageView = { let imageView = UIImageView() imageView.contentMode = .scaleAspectFit imageView.image = UIImage(named: "defaultAvator") return imageView }() }
30.418605
76
0.592125
752757ffc68216191176ef3914a71627c09041da
665
/** * Notification++.swift * NowPlayingTweet * * © 2018 kPherox. **/ import Foundation extension Notification.Name { static let login = Notification.Name("com.kr-kp.NowPlayingTweet.login") static let logout = Notification.Name("com.kr-kp.NowPlayingTweet.logout") static let disableAutoTweet = Notification.Name("com.kr-kp.NowPlayingTweet.disableAutoTweet") static let initializeAccounts = Notification.Name("com.kr-kp.NowPlayingTweet.initializeAccounts") static let alreadyAccounts = Notification.Name("com.kr-kp.NowPlayingTweet.alreadyAccounts") static let iTunesPlayerInfo = Notification.Name("com.apple.iTunes.playerInfo") }
30.227273
101
0.757895
7a87f1e2554645e39dca7d46e2039f82869ac6e1
1,365
import UIKit import SnapKit import ThemeKit class MarkdownTextCell: UITableViewCell { private static let verticalPadding: CGFloat = .margin3x private static let horizontalPadding: CGFloat = .margin6x private let textView = MarkdownTextView() override public init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) backgroundColor = .clear contentView.addSubview(textView) textView.snp.makeConstraints { maker in maker.leading.trailing.equalToSuperview().inset(MarkdownTextCell.horizontalPadding) maker.top.bottom.equalToSuperview().inset(MarkdownTextCell.verticalPadding) } } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func bind(attributedString: NSAttributedString, delegate: UITextViewDelegate?) { textView.attributedText = attributedString textView.delegate = delegate } } extension MarkdownTextCell { static func height(containerWidth: CGFloat, attributedString: NSAttributedString) -> CGFloat { let textWidth = containerWidth - 2 * horizontalPadding let textHeight = attributedString.height(containerWidth: textWidth) return textHeight + 2 * verticalPadding } }
31.022727
98
0.722344
282135768261ae7dd76a3203eb889b84c588ea17
11,527
// // OptionSpec.swift // Commandant // // Created by Justin Spahr-Summers on 2014-10-25. // Copyright (c) 2014 Carthage. All rights reserved. // @testable import Commandant import Foundation import Nimble import Quick import Result class OptionsProtocolSpec: QuickSpec { override func spec() { describe("CommandMode.Arguments") { func tryArguments(_ arguments: String...) -> Result<TestOptions, CommandantError<NoError>> { return TestOptions.evaluate(.arguments(ArgumentParser(arguments))) } it("should fail if a required argument is missing") { expect(tryArguments().value).to(beNil()) } it("should fail if an option is missing a value") { expect(tryArguments("required", "--intValue").value).to(beNil()) } it("should succeed without optional string arguments") { let value = tryArguments("required").value let expected = TestOptions(intValue: 42, stringValue: "foobar", stringsArray: [], optionalStringsArray: nil, optionalStringValue: nil, optionalFilename: "filename", requiredName: "required", enabled: false, force: false, glob: false, arguments: []) expect(value).to(equal(expected)) } it("should succeed with some strings array arguments separated by comma") { let value = tryArguments("required", "--intValue", "3", "--optionalStringValue", "baz", "fuzzbuzz", "--stringsArray", "a,b,c").value let expected = TestOptions(intValue: 3, stringValue: "foobar", stringsArray: ["a","b","c"], optionalStringsArray: nil, optionalStringValue: "baz", optionalFilename: "fuzzbuzz", requiredName: "required", enabled: false, force: false, glob: false, arguments: []) expect(value).to(equal(expected)) } it("should succeed with some strings array arguments separated by space") { let value = tryArguments("required", "--intValue", "3", "--optionalStringValue", "baz", "--stringsArray", "a b c", "fuzzbuzz").value let expected = TestOptions(intValue: 3, stringValue: "foobar", stringsArray: ["a", "b", "c"], optionalStringsArray: nil, optionalStringValue: "baz", optionalFilename: "fuzzbuzz", requiredName: "required", enabled: false, force: false, glob: false, arguments: []) expect(value).to(equal(expected)) } it("should succeed with some strings array arguments separated by comma and space") { let value = tryArguments("required", "--intValue", "3", "--optionalStringValue", "baz", "--stringsArray", "a, b, c", "fuzzbuzz").value let expected = TestOptions(intValue: 3, stringValue: "foobar", stringsArray: ["a", "b", "c"], optionalStringsArray: nil, optionalStringValue: "baz", optionalFilename: "fuzzbuzz", requiredName: "required", enabled: false, force: false, glob: false, arguments: []) expect(value).to(equal(expected)) } it("should succeed with some optional string arguments") { let value = tryArguments("required", "--intValue", "3", "--optionalStringValue", "baz", "fuzzbuzz").value let expected = TestOptions(intValue: 3, stringValue: "foobar", stringsArray: [], optionalStringsArray: nil, optionalStringValue: "baz", optionalFilename: "fuzzbuzz", requiredName: "required", enabled: false, force: false, glob: false, arguments: []) expect(value).to(equal(expected)) } it("should succeed without optional array arguments") { let value = tryArguments("required").value let expected = TestOptions(intValue: 42, stringValue: "foobar", stringsArray: [], optionalStringsArray: nil, optionalStringValue: nil, optionalFilename: "filename", requiredName: "required", enabled: false, force: false, glob: false, arguments: []) expect(value).to(equal(expected)) } it("should succeed with some optional array arguments") { let value = tryArguments("required", "--intValue", "3", "--optionalStringsArray", "one, two", "fuzzbuzz").value let expected = TestOptions(intValue: 3, stringValue: "foobar", stringsArray: [], optionalStringsArray: ["one", "two"], optionalStringValue: nil, optionalFilename: "fuzzbuzz", requiredName: "required", enabled: false, force: false, glob: false, arguments: []) expect(value).to(equal(expected)) } it("should override previous optional arguments") { let value = tryArguments("required", "--intValue", "3", "--stringValue", "fuzzbuzz", "--intValue", "5", "--stringValue", "bazbuzz").value let expected = TestOptions(intValue: 5, stringValue: "bazbuzz", stringsArray: [], optionalStringsArray: nil, optionalStringValue: nil, optionalFilename: "filename", requiredName: "required", enabled: false, force: false, glob: false, arguments: []) expect(value).to(equal(expected)) } it("should enable a boolean flag") { let value = tryArguments("required", "--enabled", "--intValue", "3", "fuzzbuzz").value let expected = TestOptions(intValue: 3, stringValue: "foobar", stringsArray: [], optionalStringsArray: nil, optionalStringValue: nil, optionalFilename: "fuzzbuzz", requiredName: "required", enabled: true, force: false, glob: false, arguments: []) expect(value).to(equal(expected)) } it("should re-disable a boolean flag") { let value = tryArguments("required", "--enabled", "--no-enabled", "--intValue", "3", "fuzzbuzz").value let expected = TestOptions(intValue: 3, stringValue: "foobar", stringsArray: [], optionalStringsArray: nil, optionalStringValue: nil, optionalFilename: "fuzzbuzz", requiredName: "required", enabled: false, force: false, glob: false, arguments: []) expect(value).to(equal(expected)) } it("should enable a boolean flag if a single Switch flag is passed") { let value = tryArguments("required", "-f").value let expected = TestOptions(intValue: 42, stringValue: "foobar", stringsArray: [], optionalStringsArray: nil, optionalStringValue: nil, optionalFilename: "filename", requiredName: "required", enabled: false, force: true, glob: false, arguments: []) expect(value).to(equal(expected)) } it("should enable multiple boolean flags if multiple grouped Switch flags are passed") { let value = tryArguments("required", "-fg").value let expected = TestOptions(intValue: 42, stringValue: "foobar", stringsArray: [], optionalStringsArray: nil, optionalStringValue: nil, optionalFilename: "filename", requiredName: "required", enabled: false, force: true, glob: true, arguments: []) expect(value).to(equal(expected)) } it("should enable a boolean flag if a single Switch key is passed") { let value = tryArguments("required", "--force").value let expected = TestOptions(intValue: 42, stringValue: "foobar", stringsArray: [], optionalStringsArray: nil, optionalStringValue: nil, optionalFilename: "filename", requiredName: "required", enabled: false, force: true, glob: false, arguments: []) expect(value).to(equal(expected)) } it("should enable multiple boolean flags if multiple Switch keys are passed") { let value = tryArguments("required", "--force", "--glob").value let expected = TestOptions(intValue: 42, stringValue: "foobar", stringsArray: [], optionalStringsArray: nil, optionalStringValue: nil, optionalFilename: "filename", requiredName: "required", enabled: false, force: true, glob: true, arguments: []) expect(value).to(equal(expected)) } it("should consume the rest of positional arguments") { let value = tryArguments("required", "optional", "value1", "value2").value let expected = TestOptions(intValue: 42, stringValue: "foobar", stringsArray: [], optionalStringsArray: nil, optionalStringValue: nil, optionalFilename: "optional", requiredName: "required", enabled: false, force: false, glob: false, arguments: [ "value1", "value2" ]) expect(value).to(equal(expected)) } it("should treat -- as the end of valued options") { let value = tryArguments("--", "--intValue").value let expected = TestOptions(intValue: 42, stringValue: "foobar", stringsArray: [], optionalStringsArray: nil, optionalStringValue: nil, optionalFilename: "filename", requiredName: "--intValue", enabled: false, force: false, glob: false, arguments: []) expect(value).to(equal(expected)) } } describe("CommandMode.Usage") { it("should return an error containing usage information") { let error = TestOptions.evaluate(.usage).error expect(error?.description).to(contain("intValue")) expect(error?.description).to(contain("stringValue")) expect(error?.description).to(contain("name you're required to")) expect(error?.description).to(contain("optionally specify")) } } } } struct TestOptions: OptionsProtocol, Equatable { let intValue: Int let stringValue: String let stringsArray: [String] let optionalStringsArray: [String]? let optionalStringValue: String? let optionalFilename: String let requiredName: String let enabled: Bool let force: Bool let glob: Bool let arguments: [String] typealias ClientError = NoError static func create(_ a: Int) -> (String) -> ([String]) -> ([String]?) -> (String?) -> (String) -> (String) -> (Bool) -> (Bool) -> (Bool) -> ([String]) -> TestOptions { return { b in { c in { d in { e in { f in { g in { h in { i in { j in { k in return self.init(intValue: a, stringValue: b, stringsArray: c, optionalStringsArray: d, optionalStringValue: e, optionalFilename: g, requiredName: f, enabled: h, force: i, glob: j, arguments: k) } } } } } } } } } } } static func evaluate(_ m: CommandMode) -> Result<TestOptions, CommandantError<NoError>> { return create <*> m <| Option(key: "intValue", defaultValue: 42, usage: "Some integer value") <*> m <| Option(key: "stringValue", defaultValue: "foobar", usage: "Some string value") <*> m <| Option<[String]>(key: "stringsArray", defaultValue: [], usage: "Some array of arguments") <*> m <| Option<[String]?>(key: "optionalStringsArray", defaultValue: nil, usage: "Some array of arguments") <*> m <| Option<String?>(key: "optionalStringValue", defaultValue: nil, usage: "Some string value") <*> m <| Argument(usage: "A name you're required to specify") <*> m <| Argument(defaultValue: "filename", usage: "A filename that you can optionally specify") <*> m <| Option(key: "enabled", defaultValue: false, usage: "Whether to be enabled") <*> m <| Switch(flag: "f", key: "force", usage: "Whether to force") <*> m <| Switch(flag: "g", key: "glob", usage: "Whether to glob") <*> m <| Argument(defaultValue: [], usage: "An argument list that consumes the rest of positional arguments") } } func ==(lhs: TestOptions, rhs: TestOptions) -> Bool { return lhs.intValue == rhs.intValue && lhs.stringValue == rhs.stringValue && lhs.stringsArray == rhs.stringsArray && lhs.optionalStringsArray == rhs.optionalStringsArray && lhs.optionalStringValue == rhs.optionalStringValue && lhs.optionalFilename == rhs.optionalFilename && lhs.requiredName == rhs.requiredName && lhs.enabled == rhs.enabled && lhs.force == rhs.force && lhs.glob == rhs.glob && lhs.arguments == rhs.arguments } func ==<T: Equatable>(lhs: [T]?, rhs: [T]?) -> Bool { switch (lhs,rhs) { case let (lhs?, rhs?): return lhs == rhs case (nil, nil): return true default: return false } } extension TestOptions: CustomStringConvertible { var description: String { return "{ intValue: \(intValue), stringValue: \(stringValue), stringsArray: \(stringsArray), optionalStringsArray: \(optionalStringsArray), optionalStringValue: \(optionalStringValue), optionalFilename: \(optionalFilename), requiredName: \(requiredName), enabled: \(enabled), force: \(force), glob: \(glob), arguments: \(arguments) }" } }
58.811224
426
0.697493
d965a0c1f327ca07e03e60fafe8d9995b2dc237e
294
// // HTTP.swift // // // Created by lonnie on 2020/9/27. // import Foundation public enum HTTP { public static let query = QueryGenerator() public static let json = DictionaryGenerator<Codable>() public static let header = DictionaryGenerator<String>() }
15.473684
60
0.639456
11b1bcb202d0706293819bcac787bb6e2e658001
1,001
// swift-tools-version:5.0 // The swift-tools-version declares the minimum version of Swift required to build this package. import PackageDescription let package = Package( name: "Notus", products: [ // Products define the executables and libraries produced by a package, and make them visible to other packages. .library( name: "Notus", targets: ["Notus"]), ], dependencies: [ // Dependencies declare other packages that this package depends on. // .package(url: /* package url */, from: "1.0.0"), ], targets: [ // Targets are the basic building blocks of a package. A target can define a module or a test suite. // Targets can depend on other targets in this package, and on products in packages which this package depends on. .target( name: "Notus", dependencies: []), .testTarget( name: "NotusTests", dependencies: ["Notus"]), ] )
34.517241
122
0.611389
f974b15d476af32bdd4868ef1020bddf46ea19e7
1,135
// // DepthTableViewCell.swift // Canonchain // // Created by LEE on 5/2/18. // Copyright © 2018 LEE. All rights reserved. // import UIKit public class DepthTableViewCell: UITableViewCell { @IBOutlet weak var serialLabel: UILabel! @IBOutlet weak var amountLabel: UILabel! @IBOutlet weak var priceLabel: UILabel! var backgroundPercent : CGFloat = 0 public var amountdigit = 4 public func setUPCellWithKLineDepthModel(model : KLineDepthModel) { // let serialNum = ((model.serial == nil) ? 0 : model.serial!) serialLabel.text = String(model.serial ) if model.amount == 0 { amountLabel.text = "--" priceLabel.text = "--" }else{ amountLabel.text = PKDataProcessManager.keepMultidigitDoublesOperationToString(model.amount, amountdigit) priceLabel.text = model.price } backgroundPercent = model.percentage setNeedsDisplay() } override public func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } }
29.102564
113
0.666079
46cc827dc44263866e7b2f7e3606d41756993ff0
1,519
// // Delete.swift // SQLiteStORM // // Created by Jonathan Guthrie on 2016-10-07. // // import PerfectLib import StORM import PerfectLogger import Foundation /// Performs delete-specific functions as an extension extension SQLiteStORM { func deleteSQL(_ table: String, idName: String = "id") -> String { return "DELETE FROM \(table) WHERE \(idName) = :1" } /// Deletes one row, with an id as an integer @discardableResult public func delete(_ id: Int, idName: String = "id") throws -> Bool { do { try exec(deleteSQL(self.table(), idName: idName), params: [String(id)]) } catch { LogFile.error("Error msg: \(error)", logFile: "./StORMlog.txt") self.error = StORMError.error("\(error)") throw error } return true } /// Deletes one row, with an id as a String @discardableResult public func delete(_ id: String, idName: String = "id") throws -> Bool { do { try exec(deleteSQL(self.table(), idName: idName), params: [id]) } catch { LogFile.error("Error msg: \(error)", logFile: "./StORMlog.txt") self.error = StORMError.error("\(error)") throw error } return true } /// Deletes one row, with an id as a UUID @discardableResult public func delete(_ id: Foundation.UUID, idName: String = "id") throws -> Bool { do { try exec(deleteSQL(self.table(), idName: idName), params: [id.uuidString]) } catch { LogFile.error("Error msg: \(error)", logFile: "./StORMlog.txt") self.error = StORMError.error("\(error)") throw error } return true } }
24.901639
82
0.658986
26428432e7017e55aae5dd851f440ed4046f1d40
264
// // See LICENSE file for this package’s licensing information. // import SwiftUI /// A helper protocol for popcorn setup. public protocol PopcornProtocol { var names: [Any.Type] { get } var types: [Any.Type] { get } var views: [AnyView] { get } }
20.307692
61
0.662879
75bbafeb729067de02546f06c88c7ccce739a57c
165
// // FlyweightFactory.swift // Flyweight // // Created by Pszertlek on 2018/2/22. // Copyright © 2018年 Pszertlek. All rights reserved. // import Foundation
12.692308
53
0.684848
71a0e971b5e75ddf9e96c44869b32f01be6fc53b
12,529
// // Copyright Amazon.com Inc. or its affiliates. // All Rights Reserved. // // SPDX-License-Identifier: Apache-2.0 // import Combine import XCTest import Amplify @testable import AmplifyTestCommon @testable import AWSAPICategoryPlugin import AppSyncRealTimeClient @available(iOS 13.0, *) class GraphQLSubscribeCombineTests: OperationTestBase { // Setup expectations var onSubscribeInvoked: XCTestExpectation! // Subscription state expectations var receivedStateCompletionSuccess: XCTestExpectation! var receivedStateCompletionFailure: XCTestExpectation! var receivedStateValueConnecting: XCTestExpectation! var receivedStateValueConnected: XCTestExpectation! var receivedStateValueDisconnected: XCTestExpectation! // Subscription item expectations var receivedDataCompletionSuccess: XCTestExpectation! var receivedDataCompletionFailure: XCTestExpectation! var receivedDataValueSuccess: XCTestExpectation! var receivedDataValueError: XCTestExpectation! // Handles to the subscription item and event handler used to make mock calls into the // subscription system var subscriptionItem: SubscriptionItem! var subscriptionEventHandler: SubscriptionEventHandler! var connectionStateSink: AnyCancellable? var subscriptionDataSink: AnyCancellable? override func setUpWithError() throws { try super.setUpWithError() onSubscribeInvoked = expectation(description: "onSubscribeInvoked") receivedStateCompletionSuccess = expectation(description: "receivedStateCompletionSuccess") receivedStateCompletionFailure = expectation(description: "receivedStateCompletionFailure") receivedStateValueConnecting = expectation(description: "receivedStateValueConnecting") receivedStateValueConnected = expectation(description: "receivedStateValueConnected") receivedStateValueDisconnected = expectation(description: "receivedStateValueDisconnected") receivedDataCompletionSuccess = expectation(description: "receivedDataCompletionSuccess") receivedDataCompletionFailure = expectation(description: "receivedDataCompletionFailure") receivedDataValueSuccess = expectation(description: "receivedDataValueSuccess") receivedDataValueError = expectation(description: "receivedDataValueError") try setUpMocksAndSubscriptionItems() } func testHappyPath() throws { receivedStateCompletionSuccess.shouldTrigger = true receivedStateCompletionFailure.shouldTrigger = false receivedStateValueConnecting.shouldTrigger = true receivedStateValueConnected.shouldTrigger = true receivedStateValueDisconnected.shouldTrigger = true receivedDataCompletionSuccess.shouldTrigger = true receivedDataCompletionFailure.shouldTrigger = false receivedDataValueSuccess.shouldTrigger = true receivedDataValueError.shouldTrigger = false let testJSON: JSONValue = ["foo": true] let testData = #"{"data": {"foo": true}}"# .data(using: .utf8)! subscribe(expecting: testJSON) wait(for: [onSubscribeInvoked], timeout: 0.05) subscriptionEventHandler(.connection(.connecting), subscriptionItem) subscriptionEventHandler(.connection(.connected), subscriptionItem) subscriptionEventHandler(.data(testData), subscriptionItem) subscriptionEventHandler(.connection(.disconnected), subscriptionItem) waitForExpectations(timeout: 0.05) } func testConnectionWithNoData() throws { receivedStateCompletionSuccess.shouldTrigger = true receivedStateCompletionFailure.shouldTrigger = false receivedStateValueConnecting.shouldTrigger = true receivedStateValueConnected.shouldTrigger = true receivedStateValueDisconnected.shouldTrigger = true receivedDataCompletionSuccess.shouldTrigger = true receivedDataCompletionFailure.shouldTrigger = false receivedDataValueSuccess.shouldTrigger = false receivedDataValueError.shouldTrigger = false subscribe() wait(for: [onSubscribeInvoked], timeout: 0.05) subscriptionEventHandler(.connection(.connecting), subscriptionItem) subscriptionEventHandler(.connection(.connected), subscriptionItem) subscriptionEventHandler(.connection(.disconnected), subscriptionItem) waitForExpectations(timeout: 0.05) } func testConnectionError() throws { receivedStateCompletionSuccess.shouldTrigger = false receivedStateCompletionFailure.shouldTrigger = true receivedStateValueConnecting.shouldTrigger = true receivedStateValueConnected.shouldTrigger = false receivedStateValueDisconnected.shouldTrigger = false receivedDataCompletionSuccess.shouldTrigger = false receivedDataCompletionFailure.shouldTrigger = true receivedDataValueSuccess.shouldTrigger = false receivedDataValueError.shouldTrigger = false subscribe() wait(for: [onSubscribeInvoked], timeout: 0.05) subscriptionEventHandler(.connection(.connecting), subscriptionItem) subscriptionEventHandler(.failed("Error"), subscriptionItem) waitForExpectations(timeout: 0.05) } func testDecodingError() throws { let testData = #"{"data": {"foo": true}, "errors": []}"# .data(using: .utf8)! receivedStateCompletionSuccess.shouldTrigger = true receivedStateCompletionFailure.shouldTrigger = false receivedStateValueConnecting.shouldTrigger = true receivedStateValueConnected.shouldTrigger = true receivedStateValueDisconnected.shouldTrigger = true receivedDataCompletionSuccess.shouldTrigger = true receivedDataCompletionFailure.shouldTrigger = false receivedDataValueSuccess.shouldTrigger = false receivedDataValueError.shouldTrigger = true subscribe() wait(for: [onSubscribeInvoked], timeout: 0.05) subscriptionEventHandler(.connection(.connecting), subscriptionItem) subscriptionEventHandler(.connection(.connected), subscriptionItem) subscriptionEventHandler(.data(testData), subscriptionItem) subscriptionEventHandler(.connection(.disconnected), subscriptionItem) waitForExpectations(timeout: 0.05) } func testMultipleSuccessValues() throws { let testJSON: JSONValue = ["foo": true] let testData = #"{"data": {"foo": true}}"# .data(using: .utf8)! receivedStateCompletionSuccess.shouldTrigger = true receivedStateCompletionFailure.shouldTrigger = false receivedStateValueConnecting.shouldTrigger = true receivedStateValueConnected.shouldTrigger = true receivedStateValueDisconnected.shouldTrigger = true receivedDataCompletionSuccess.shouldTrigger = true receivedDataCompletionFailure.shouldTrigger = false receivedDataValueSuccess.shouldTrigger = true receivedDataValueSuccess.expectedFulfillmentCount = 2 receivedDataValueError.shouldTrigger = false subscribe(expecting: testJSON) wait(for: [onSubscribeInvoked], timeout: 0.05) subscriptionEventHandler(.connection(.connecting), subscriptionItem) subscriptionEventHandler(.connection(.connected), subscriptionItem) subscriptionEventHandler(.data(testData), subscriptionItem) subscriptionEventHandler(.data(testData), subscriptionItem) subscriptionEventHandler(.connection(.disconnected), subscriptionItem) waitForExpectations(timeout: 0.05) } func testMixedSuccessAndErrorValues() throws { let successfulTestData = #"{"data": {"foo": true}}"# .data(using: .utf8)! let invalidTestData = #"{"data": {"foo": true}, "errors": []}"# .data(using: .utf8)! receivedStateCompletionSuccess.shouldTrigger = true receivedStateCompletionFailure.shouldTrigger = false receivedStateValueConnecting.shouldTrigger = true receivedStateValueConnected.shouldTrigger = true receivedStateValueDisconnected.shouldTrigger = true receivedDataCompletionSuccess.shouldTrigger = true receivedDataCompletionFailure.shouldTrigger = false receivedDataValueSuccess.shouldTrigger = true receivedDataValueSuccess.expectedFulfillmentCount = 2 receivedDataValueError.shouldTrigger = true subscribe() wait(for: [onSubscribeInvoked], timeout: 0.05) subscriptionEventHandler(.connection(.connecting), subscriptionItem) subscriptionEventHandler(.connection(.connected), subscriptionItem) subscriptionEventHandler(.data(successfulTestData), subscriptionItem) subscriptionEventHandler(.data(invalidTestData), subscriptionItem) subscriptionEventHandler(.data(successfulTestData), subscriptionItem) subscriptionEventHandler(.connection(.disconnected), subscriptionItem) waitForExpectations(timeout: 0.05) } // MARK: - Utilities /// Sets up test with a mock subscription connection handler that populates /// self.subscriptionItem and self.subscriptionEventHandler, then fulfills /// self.onSubscribeInvoked func setUpMocksAndSubscriptionItems() throws { let onSubscribe: MockSubscriptionConnection.OnSubscribe = { requestString, variables, eventHandler in let item = SubscriptionItem( requestString: requestString, variables: variables, eventHandler: eventHandler ) self.subscriptionItem = item self.subscriptionEventHandler = eventHandler self.onSubscribeInvoked.fulfill() return item } let onGetOrCreateConnection: MockSubscriptionConnectionFactory.OnGetOrCreateConnection = { _, _, _, _ in MockSubscriptionConnection(onSubscribe: onSubscribe, onUnsubscribe: { _ in }) } try setUpPluginForSubscriptionResponse(onGetOrCreateConnection: onGetOrCreateConnection) } /// Calls `Amplify.API.subscribe` with a request made from a generic document, and returns /// the operation created from that subscription. If `expectedValue` is not nil, also asserts /// that the received value is equal to the expected value @discardableResult func subscribe( expecting expectedValue: JSONValue? = nil ) -> GraphQLSubscriptionOperation<JSONValue> { let testDocument = "subscribe { subscribeTodos { id name description }}" let request = GraphQLRequest( document: testDocument, variables: nil, responseType: JSONValue.self ) let operation = apiPlugin.subscribe(request: request) connectionStateSink = operation .connectionStatePublisher .sink( receiveCompletion: { completion in switch completion { case .failure: self.receivedStateCompletionFailure.fulfill() case .finished: self.receivedStateCompletionSuccess.fulfill() } }, receiveValue: { connectionState in switch connectionState { case .connecting: self.receivedStateValueConnecting.fulfill() case .connected: self.receivedStateValueConnected.fulfill() case .disconnected: self.receivedStateValueDisconnected.fulfill() } } ) subscriptionDataSink = operation .subscriptionDataPublisher .sink(receiveCompletion: { completion in switch completion { case .failure: self.receivedDataCompletionFailure.fulfill() case .finished: self.receivedDataCompletionSuccess.fulfill() } }, receiveValue: { result in switch result { case .success(let actualValue): if let expectedValue = expectedValue { XCTAssertEqual(actualValue, expectedValue) } self.receivedDataValueSuccess.fulfill() case .failure: self.receivedDataValueError.fulfill() } } ) return operation } }
41.486755
113
0.701413
4ad642207a4fc26eca13145c628be57a6dda77ac
4,897
// // Copyright 2011 - 2020 Schibsted Products & Technology AS. // Licensed under the terms of the MIT license. See LICENSE in the project root. // import Foundation /* A lot of code here is explained in Mike Ash's "Let's Build Swift Notifications" article: https://mikeash.com/pyblog/friday-qa-2015-01-23-lets-build-swift-notifications.html */ class ReceiverHandle<Parameters>: Hashable { fileprivate weak var object: AnyObject? fileprivate var objectHandler: ((AnyObject) -> (Parameters) -> Void)? fileprivate var block: ((Parameters) -> Void)? var descriptionText: String fileprivate init(object: AnyObject, handler: @escaping (AnyObject) -> (Parameters) -> Void) { self.object = object objectHandler = handler descriptionText = "AnyObject" } fileprivate init(block: @escaping (Parameters) -> Void) { self.block = block descriptionText = "block" } func hash(into hasher: inout Hasher) { hasher.combine(Unmanaged.passUnretained(self).toOpaque()) } } func == <P>(lhs: ReceiverHandle<P>, rhs: ReceiverHandle<P>) -> Bool { return lhs === rhs } class EventEmitter<Parameters> { private let dispatchQueue = DispatchQueue(label: "com.schibsted.identity.EventEmitter", attributes: []) private var handles = Set<ReceiverHandle<Parameters>>() private var descriptionText: String init(description: String) { descriptionText = description } init() { descriptionText = "\(EventEmitter<Parameters>.self)" } @discardableResult func register(_ block: @escaping (Parameters) -> Void) -> ReceiverHandle<Parameters> { let handle = ReceiverHandle<Parameters>(block: block) _ = dispatchQueue.sync { self.handles.insert(handle) } return handle } func register<T: AnyObject>(_ object: T, handler: @escaping (T) -> (Parameters) -> Void) -> ReceiverHandle<Parameters> { let typeErasedHandler: (AnyObject) -> (Parameters) -> Void = { any in /* We need this wrapped up because the ReceiverHandle expects type: AnyObject -> Parameters -> Void but here we have a type: T -> Parameters -> Void. So we make a "wrapped" function that takes a type erased T and calls handler on the actual type T. */ handler(any as! T) // swiftlint:disable:this force_cast } let handle = ReceiverHandle<Parameters>(object: object, handler: typeErasedHandler) _ = dispatchQueue.sync { self.handles.insert(handle) } return handle } func unregister(_ handle: ReceiverHandle<Parameters>) { _ = dispatchQueue.sync { self.handles.remove(handle) } } func compactAndTakeHandles() -> [ReceiverHandle<Parameters>] { var validHandles: [ReceiverHandle<Parameters>] = [] dispatchQueue.sync { for handle in self.handles { if handle.block != nil || handle.object != nil { validHandles.append(handle) } } // No point in leaving invalid handles in the set self.handles = Set(validHandles) } return validHandles } func normalizeHandlers(in handles: [ReceiverHandle<Parameters>]) -> [(ReceiverHandle<Parameters>, (Parameters) -> Void)] { return handles.compactOrFlatMap { (handle) -> (ReceiverHandle<Parameters>, (Parameters) -> Void)? in var maybeHandler: ((Parameters) -> Void)? if let block = handle.block { maybeHandler = block } else if let object = handle.object, let objectHandler = handle.objectHandler { maybeHandler = objectHandler(object) } guard let handler = maybeHandler else { return nil } return (handle, handler) } } func emitSync(_ parameters: Parameters) { log(level: .verbose, from: self, "\(descriptionText) on \(self.handles.count) handles") let handles = compactAndTakeHandles() normalizeHandlers(in: handles).forEach { handle, handler in log(level: .debug, from: self, "\(self.descriptionText) -> \(handle.descriptionText)") handler(parameters) } } func emitAsync(_ parameters: Parameters) { log(level: .verbose, from: self, "\(descriptionText) on \(self.handles.count) handles") let handles = compactAndTakeHandles() let normalizedHandlers = normalizeHandlers(in: handles) dispatchQueue.async { [weak self] in normalizedHandlers.forEach { handle, handler in log(level: .debug, from: self, "\(self?.descriptionText as Any) -> \(handle.descriptionText)") handler(parameters) } } } }
36.544776
126
0.618338
efffbf2bca8b9644b5aa01bef136ad5fd39b514e
437
// // SponsorCollectionViewCell.swift // TigerHacks-App // // Created by Jonah Zukosky on 3/9/18. // Copyright © 2018 Zukosky, Jonah. All rights reserved. // import UIKit class SponsorCollectionViewCell: UICollectionViewCell { @IBOutlet weak var sponsorImage: UIImageView! @IBOutlet weak var view: UIView! override func prepareForReuse() { super.prepareForReuse() sponsorImage.image = nil } }
20.809524
57
0.693364
67b7a02b3168ff7edd2504e904f3bb94f41625f7
3,688
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. // // Code generated by Microsoft (R) AutoRest Code Generator. import Foundation import azureSwiftRuntime internal struct PolicyPropertiesFragmentData : PolicyPropertiesFragmentProtocol { public var description: String? public var status: PolicyStatusEnum? public var factName: PolicyFactNameEnum? public var factData: String? public var threshold: String? public var evaluatorType: PolicyEvaluatorTypeEnum? public var provisioningState: String? public var uniqueIdentifier: String? enum CodingKeys: String, CodingKey {case description = "description" case status = "status" case factName = "factName" case factData = "factData" case threshold = "threshold" case evaluatorType = "evaluatorType" case provisioningState = "provisioningState" case uniqueIdentifier = "uniqueIdentifier" } public init() { } public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) if container.contains(.description) { self.description = try container.decode(String?.self, forKey: .description) } if container.contains(.status) { self.status = try container.decode(PolicyStatusEnum?.self, forKey: .status) } if container.contains(.factName) { self.factName = try container.decode(PolicyFactNameEnum?.self, forKey: .factName) } if container.contains(.factData) { self.factData = try container.decode(String?.self, forKey: .factData) } if container.contains(.threshold) { self.threshold = try container.decode(String?.self, forKey: .threshold) } if container.contains(.evaluatorType) { self.evaluatorType = try container.decode(PolicyEvaluatorTypeEnum?.self, forKey: .evaluatorType) } if container.contains(.provisioningState) { self.provisioningState = try container.decode(String?.self, forKey: .provisioningState) } if container.contains(.uniqueIdentifier) { self.uniqueIdentifier = try container.decode(String?.self, forKey: .uniqueIdentifier) } if var pageDecoder = decoder as? PageDecoder { if pageDecoder.isPagedData, let nextLinkName = pageDecoder.nextLinkName { pageDecoder.nextLink = try UnknownCodingKey.decodeStringForKey(decoder: decoder, keyForDecode: nextLinkName) } } } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) if self.description != nil {try container.encode(self.description, forKey: .description)} if self.status != nil {try container.encode(self.status, forKey: .status)} if self.factName != nil {try container.encode(self.factName, forKey: .factName)} if self.factData != nil {try container.encode(self.factData, forKey: .factData)} if self.threshold != nil {try container.encode(self.threshold, forKey: .threshold)} if self.evaluatorType != nil {try container.encode(self.evaluatorType, forKey: .evaluatorType)} if self.provisioningState != nil {try container.encode(self.provisioningState, forKey: .provisioningState)} if self.uniqueIdentifier != nil {try container.encode(self.uniqueIdentifier, forKey: .uniqueIdentifier)} } } extension DataFactory { public static func createPolicyPropertiesFragmentProtocol() -> PolicyPropertiesFragmentProtocol { return PolicyPropertiesFragmentData() } }
44.97561
119
0.704989
76e16939d015361b88c10c02dd220b165f5c6f06
2,258
// // ControlView.swift // CwlViewsCatalog_iOS // // Created by Matt Gallagher on 10/2/19. // Copyright © 2019 Matt Gallagher ( https://www.cocoawithlove.com ). All rights reserved. // // Permission to use, copy, modify, and/or distribute this software for any purpose with or without // fee is hereby granted, provided that the above copyright notice and this permission notice // appear in all copies. // // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS // SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE // AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES // WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, // NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE // OF THIS SOFTWARE. // import CwlViews struct ControlViewState: CodableContainer { let lastEvent: Var<String> init() { lastEvent = Var(.noEvent) } } func controlView(_ controlViewState: ControlViewState, _ navigationItem: NavigationItem) -> ViewControllerConvertible { return ViewController( .navigationItem -- navigationItem, .view -- View( .backgroundColor -- .white, .layout -- .center( .view(Label(.text <-- controlViewState.lastEvent)), .space(), .view( length: 60, breadth: 220, Control( .backgroundColor -- .orange, .layer -- Layer(.borderWidth -- 2, .borderColor -- UIColor.brown.cgColor, .cornerRadius -- 8), .action(.touchDown) --> Input().map { .touchDownEvent }.bind(to: controlViewState.lastEvent), .action(.touchUpInside) --> Input().map { .touchUpEvent }.bind(to: controlViewState.lastEvent), .action(.touchDragInside) --> Input().map { .touchDragEvent }.bind(to:controlViewState.lastEvent) ) ) ) ) ) } private extension String { static let noEvent = NSLocalizedString("No actions emitted", comment: "") static let touchDownEvent = NSLocalizedString("TouchDown emitted", comment: "") static let touchUpEvent = NSLocalizedString("TouchUp emitted", comment: "") static let touchDragEvent = NSLocalizedString("Touch drag emitted", comment: "") }
38.271186
119
0.716563
6a91f88132cf010a49df5dca8e86bea3e5c8356e
4,853
import MongoSwift import Nimble import TestsCommon extension WriteConcern { /// Initialize a new `WriteConcern` from a `Document`. We can't /// use `decode` because the format is different in spec tests /// ("journal" instead of "j", etc.) fileprivate init(_ doc: Document) throws { let j = doc["journal"]?.boolValue var w: W? if let wtag = doc["w"]?.stringValue { w = wtag == "majority" ? .majority : .tag(wtag) } else if let wInt = doc["w"]?.asInt32() { w = .number(wInt) } let wt = doc["wtimeoutMS"]?.asInt64() try self.init(journal: j, w: w, wtimeoutMS: wt) } } class ReadWriteConcernSpecTests: MongoSwiftTestCase { func testConnectionStrings() throws { let testFiles = try retrieveSpecTestFiles( specName: "read-write-concern", subdirectory: "connection-string", asType: Document.self ) for (_, asDocument) in testFiles { let tests: [Document] = asDocument["tests"]!.arrayValue!.compactMap { $0.documentValue } for test in tests { let description: String = try test.get("description") // skipping because C driver does not comply with these; see CDRIVER-2621 if description.lowercased().contains("wtimeoutms") { continue } let uri: String = try test.get("uri") let valid: Bool = try test.get("valid") if valid { let client = try MongoClient(uri) if let readConcern = test["readConcern"]?.documentValue { let rc = try BSONDecoder().decode(ReadConcern.self, from: readConcern) if rc.isDefault { expect(client.readConcern).to(beNil()) } else { expect(client.readConcern).to(equal(rc)) } } else if let writeConcern = test["writeConcern"]?.documentValue { let wc = try WriteConcern(writeConcern) if wc.isDefault { expect(client.writeConcern).to(beNil()) } else { expect(client.writeConcern).to(equal(wc)) } } } else { expect(try MongoClient(uri)).to(throwError(errorType: InvalidArgumentError.self)) } } } } func testDocuments() throws { let encoder = BSONEncoder() let testFiles = try retrieveSpecTestFiles( specName: "read-write-concern", subdirectory: "document", asType: Document.self ) for (_, asDocument) in testFiles { let tests = asDocument["tests"]!.arrayValue!.compactMap { $0.documentValue } for test in tests { let valid: Bool = try test.get("valid") if let rcToUse = test["readConcern"]?.documentValue { let rc = try BSONDecoder().decode(ReadConcern.self, from: rcToUse) let isDefault: Bool = try test.get("isServerDefault") expect(rc.isDefault).to(equal(isDefault)) let expected: Document = try test.get("readConcernDocument") if expected == [:] { expect(try encoder.encode(rc)).to(beNil()) } else { expect(try encoder.encode(rc)).to(equal(expected)) } } else if let wcToUse = test["writeConcern"]?.documentValue { if valid { let wc = try WriteConcern(wcToUse) let isAcknowledged: Bool = try test.get("isAcknowledged") expect(wc.isAcknowledged).to(equal(isAcknowledged)) let isDefault: Bool = try test.get("isServerDefault") expect(wc.isDefault).to(equal(isDefault)) var expected: Document = try test.get("writeConcernDocument") if expected == [:] { expect(try encoder.encode(wc)).to(beNil()) } else { if let wtimeoutMS = expected["wtimeout"] { expected["wtimeout"] = .int64(wtimeoutMS.asInt64()!) } expect(try encoder.encode(wc)).to(sortedEqual(expected)) } } else { expect(try WriteConcern(wcToUse)).to(throwError(errorType: InvalidArgumentError.self)) } } } } } }
42.2
110
0.495982
0807d033b48dd68355830ad939427354e60edba4
4,527
import UIKit protocol HeaderViewDelegate: class { func headerView(_ headerView: HeaderView, didPressDeleteButton deleteButton: UIButton) func headerView(_ headerView: HeaderView, didPressCloseButton closeButton: UIButton) func headerView(_ headerView: HeaderView, didPressEditButton editButton: UIButton) } open class HeaderView: UIView { open fileprivate(set) lazy var closeButton: UIButton = { [unowned self] in let title = NSAttributedString( string: LightboxConfig.CloseButton.text, attributes: LightboxConfig.CloseButton.textAttributes) let button = UIButton(type: .system) button.setAttributedTitle(title, for: UIControl.State()) if let size = LightboxConfig.CloseButton.size { button.frame.size = size } else { button.sizeToFit() } button.addTarget(self, action: #selector(closeButtonDidPress(_:)), for: .touchUpInside) if let image = LightboxConfig.CloseButton.image { button.setBackgroundImage(image, for: UIControl.State()) } button.isHidden = !LightboxConfig.CloseButton.enabled return button }() open fileprivate(set) lazy var deleteButton: UIButton = { [unowned self] in let title = NSAttributedString( string: LightboxConfig.DeleteButton.text, attributes: LightboxConfig.DeleteButton.textAttributes) let button = UIButton(type: .system) button.setAttributedTitle(title, for: .normal) if let size = LightboxConfig.DeleteButton.size { button.frame.size = size } else { button.sizeToFit() } button.addTarget(self, action: #selector(deleteButtonDidPress(_:)), for: .touchUpInside) if let image = LightboxConfig.DeleteButton.image { button.setBackgroundImage(image, for: UIControl.State()) } button.isHidden = !LightboxConfig.DeleteButton.enabled return button }() open fileprivate(set) lazy var editButton: UIButton = { [unowned self] in let title = NSAttributedString( string: LightboxConfig.EditButton.text, attributes: LightboxConfig.EditButton.textAttributes) let button = UIButton(type: .system) button.setAttributedTitle(title, for: UIControl.State()) if let size = LightboxConfig.EditButton.size { button.frame.size = size } else { button.sizeToFit() } button.addTarget(self, action: #selector(editButtonDidPress(_:)), for: .touchUpInside) if let image = LightboxConfig.EditButton.image { button.setBackgroundImage(image, for: UIControl.State()) } button.isHidden = !LightboxConfig.EditButton.enabled return button }() weak var delegate: HeaderViewDelegate? // MARK: - Initializers public init() { super.init(frame: CGRect.zero) backgroundColor = UIColor.clear // MDM 20200325 - Remove Delete and Edit Buttons because the `enabled` property isn't working // [closeButton, deleteButton, editButton].forEach { addSubview($0) } [closeButton].forEach { addSubview($0) } } public required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: - Actions @objc func deleteButtonDidPress(_ button: UIButton) { delegate?.headerView(self, didPressDeleteButton: button) } @objc func closeButtonDidPress(_ button: UIButton) { delegate?.headerView(self, didPressCloseButton: button) } @objc func editButtonDidPress(_ button: UIButton) { delegate?.headerView(self, didPressEditButton: button) } } // MARK: - LayoutConfigurable extension HeaderView: LayoutConfigurable { @objc public func configureLayout() { let topPadding: CGFloat if #available(iOS 11, *) { topPadding = safeAreaInsets.top } else { topPadding = 0 } closeButton.frame.origin = CGPoint( x: bounds.width - closeButton.frame.width - 17, y: topPadding ) deleteButton.frame.origin = CGPoint( x: 17, y: topPadding ) editButton.frame.origin = CGPoint( x: deleteButton.frame.width + 30, y: topPadding ) } }
29.588235
101
0.625801
0e671e635ce90bdab9f677588193d2cf3fb37b2d
11,024
// // WebController.swift // Ext // // Created by naijoug on 2020/5/27. // import UIKit import WebKit /** Reference: - https://developer.apple.com/documentation/webkit/wkusercontentcontroller - https://stackoverflow.com/questions/27105094/how-to-remove-cache-in-wkwebview */ public extension ExtWrapper where Base: WKWebView { /// 清理 WKWebView 缓存数据 /// - Parameter handler: 清理完成回调 static func clean(_ handler: @escaping Ext.VoidHandler) { HTTPCookieStorage.shared.removeCookies(since: Date.distantPast) WKWebsiteDataStore.default().removeData( ofTypes: [WKWebsiteDataTypeDiskCache, WKWebsiteDataTypeMemoryCache], modifiedSince: Date(timeIntervalSince1970: 0)) { handler() } } } open class WebController: UIViewController { /// 是否 modal 方式显示 public var isModal: Bool = false /// Web 页面 URL public var urlString: String? // MARK: - Status /// 日志标记 public var logEnabled: Bool = false /// 进度监听员 private var progressObserver: NSKeyValueObservation? /// 网页加载进度 public private(set) var progress: Double = 0 { didSet { guard oldValue != progress else { return } Ext.debug("web progress: \(oldValue) -> \(progress)", logEnabled: logEnabled) } } /// 开始加载时间 private var startDate = Date() /// Web 加载成功时间 (秒数) public private(set) var loadingSeconds: TimeInterval = 0 /** 默认 handler 名字: native - 实现功能 body 中 JSON 参数 * toWeb : 打开内嵌网页 { "method": "toWeb", "title": "xxx", "url": "http://xxx" } * toRoot : 回到根页面 { "method": "toRoot" } */ private let defaultJSHandlerName = "native" /// 默认 JS 交换功能是否可用 public var defaultJSHandlerEnabled: Bool = false { didSet { let names = [defaultJSHandlerName] defaultJSHandlerEnabled ? addJSHandlerNames(names) : removeJSHandlerNames(names) } } /// JS 交互函数名列表 public private(set) var jsHandlerNames = [String]() /// 下拉刷新是否可用 open var pullToRefreshEnabled: Bool = false { didSet { guard pullToRefreshEnabled else { refreshControl.removeFromSuperview() return } webView.scrollView.addSubview(refreshControl) } } // MARK: - UI private lazy var userContentController: WKUserContentController = { WKUserContentController() }() private lazy var refreshControl: UIRefreshControl = { let refreshControl = UIRefreshControl() refreshControl.addTarget(self, action: #selector(pullToRefresh), for: .valueChanged) return refreshControl }() public lazy private(set) var webView: WKWebView = { let preferences = WKPreferences() preferences.javaScriptEnabled = true let configuration = WKWebViewConfiguration() configuration.preferences = preferences configuration.userContentController = userContentController let webView = WKWebView(frame: CGRect.zero, configuration: configuration) view.addSubview(webView) webView.uiDelegate = self webView.navigationDelegate = self webView.scrollView.bounces = true webView.scrollView.alwaysBounceVertical = true webView.scrollView.contentInsetAdjustmentBehavior = .never webView.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint.activate([ webView.topAnchor.constraint(equalTo: view.topAnchor), webView.leadingAnchor.constraint(equalTo: view.leadingAnchor), webView.trailingAnchor.constraint(equalTo: view.trailingAnchor), webView.bottomAnchor.constraint(equalTo: view.bottomAnchor) ]) return webView }() private lazy var indicator: UIActivityIndicatorView = { let indicator = UIActivityIndicatorView(style: .gray) view.addSubview(indicator) indicator.center = view.center return indicator }() /// 是否显示中间指示器 public var indicatorEnabled: Bool = false // MARK: - Lifecycle deinit { removeJSHandlerNames(jsHandlerNames) progressObserver?.invalidate() progressObserver = nil } override open func viewDidLoad() { super.viewDidLoad() view.backgroundColor = .white edgesForExtendedLayout = [] navigationItem.largeTitleDisplayMode = .never if isModal { if #available(iOS 13.0, *) { navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .close, target: self, action: #selector(closeAction)) } else { navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .cancel, target: self, action: #selector(closeAction)) } } pullToRefreshEnabled = true progressObserver = webView.observe(\.estimatedProgress, options: [.initial, .new], changeHandler: { [weak self] _, change in guard let `self` = self else { return } self.progress = change.newValue ?? 0 }) reloadWebView() } @objc private func closeAction() { dismiss(animated: true, completion: nil) } } // MARK: - Override extension WebController { /// 下拉刷新 @objc open func pullToRefresh() { reloadWebView() } /// 刷新网页 @objc open func reloadWebView() { guard let urlString = urlString, let url = URL(string: urlString) else { return } Ext.debug("open url: \(url.absoluteString)", logEnabled: logEnabled) startDate = Date() webView.load(URLRequest(url: url)) beginNetworking() } } // MARK: - WKUIDelegate extension WebController: WKUIDelegate { public func webViewDidClose(_ webView: WKWebView) { Ext.debug("") } public func webView(_ webView: WKWebView, runJavaScriptAlertPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping () -> Void) { Ext.debug(message) } public func webView(_ webView: WKWebView, runJavaScriptConfirmPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping (Bool) -> Void) { Ext.debug(message) } public func webView(_ webView: WKWebView, runJavaScriptTextInputPanelWithPrompt prompt: String, defaultText: String?, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping (String?) -> Void) { Ext.debug("prompt: \(prompt) | defaultText: \(defaultText ?? "")", logEnabled: logEnabled) } } // MARK: - WKNavigationDelegate extension WebController: WKNavigationDelegate { public func webView(_ webView: WKWebView, didCommit navigation: WKNavigation!) { } public func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) { endNetworking() loadingSeconds = Date().timeIntervalSince(startDate) Ext.debug("webView load succeeded. \(loadingSeconds)", logEnabled: logEnabled) } public func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) { Ext.debug("webView load failed.", error: error) endNetworking() } private func beginNetworking() { refreshControl.beginRefreshing() if indicatorEnabled { indicator.startAnimating() } } private func endNetworking() { if indicatorEnabled { indicator.stopAnimating() } refreshControl.endRefreshing() } } // MARK: - WKScriptMessageHandler extension WebController: WKScriptMessageHandler { public func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) { Ext.debug("names: \(jsHandlerNames) | name: \(message.name) | body: \(message.body) | \(message.frameInfo)", logEnabled: logEnabled) guard jsHandlerNames.contains(message.name) else { return } jsHandler(message.name, body: message.body) } } // MARK: - JS Method Router extension WebController { /// 添加 JS 交互函数名 /// - Parameter names: 函数名列表 public func addJSHandlerNames(_ names: [String]) { for name in names { guard !jsHandlerNames.contains(where: { $0 == name }) else { continue } userContentController.add(self, name: name) jsHandlerNames.append(name) } } /// 移除 JS 交互函数名 /// - Parameter names: 函数名列表 public func removeJSHandlerNames(_ names: [String]) { for name in names { guard jsHandlerNames.contains(where: { $0 == name }) else { continue } userContentController.removeScriptMessageHandler(forName: name) jsHandlerNames.removeAll(where: { $0 == name }) } } /// JS 方法处理者 (子类重载实现) /// - Parameter name: 方法名 /// - Parameter body: 消息体 @objc open func jsHandler(_ name: String, body: Any) { if name == defaultJSHandlerName { defaultJSHandler(body) } } /// 解析 JS 发送的消息体 -> JSON public func parseJSON(_ body: Any) -> [String: Any]? { if body is String, let string = body as? String { var json: [String: Any]? do { json = try JSONSerialization.jsonObject(with: Data(string.utf8), options: [.allowFragments, .mutableLeaves]) as? Dictionary<String, Any> } catch { Ext.debug("JSON parse error.", error: error) } return json } else if body is [String: Any], let json = body as? [String: Any] { return json } return nil } } private extension WebController { func defaultJSHandler(_ body: Any) { guard let json = parseJSON(body) else { return } Ext.debug("\(String(describing: json))", logEnabled: logEnabled) guard let method = json["method"] as? String else { Ext.debug("method not exist.", logEnabled: logEnabled) return } switch method { case "openWeb": let title = json["title"] as? String let urlString = json["url"] as? String openWeb(title, urlString: urlString) case "toRoot": toRoot() default: Ext.debug("method: \(method) not implement.", logEnabled: logEnabled) break } } /// 打开新的网页页面 private func openWeb(_ title: String?, urlString: String?) { guard let urlString = urlString else { return } let vc = WebController() vc.title = title vc.urlString = urlString vc.hidesBottomBarWhenPushed = true navigationController?.pushViewController(vc, animated: true) } /// 回到根控制器 private func toRoot() { navigationController?.popToRootViewController(animated: true) } }
32.907463
208
0.625907
e6c1676eb4316ba13b13cfbdc6481c5ba32758f4
236
import Foundation public extension Bundle { /// ZJaDe: 加载nib static func loadNib<T>(_ name: String, owner: AnyObject? = nil) -> T? { return Bundle.main.loadNibNamed(name, owner: owner, options: nil)?[0] as? T } }
21.454545
83
0.635593
c1968ac22f99e69e98f12a48368b48635fa9e4fe
2,673
// // Created by Artem Novichkov on 24.04.2021. // import SwiftUI final class ContentViewModel { //MARK: - Button Data struct ButtonData: Identifiable { let title: String let url: URL let sheet: Sheet var id: String { url.absoluteString } init(title: String, sheet: Sheet) { self.title = title self.sheet = sheet switch sheet { case .png(let url): self.url = url case .pdf(let url): self.url = url case .webarchive(let url): self.url = url } } } var buttonsData: [ButtonData] { [.init(title: "Open Snapshot", sheet: .png(pngURL)), .init(title: "Open PDF", sheet: .pdf(pdfURL)), .init(title: "Open WebArchive", sheet: .webarchive(webarchiveURL))] } //MARK: - Managers private lazy var webDataManager: WebDataManager = .init() private lazy var fileManager: FileManager = .default //MARK: - URLs private var documentsURL: URL { fileManager.urls(for: .documentDirectory, in: .userDomainMask)[0] } private var webarchiveURL: URL { documentsURL .appendingPathComponent("data") .appendingPathExtension("webarchive") } private var pdfURL: URL { documentsURL .appendingPathComponent("data") .appendingPathExtension("pdf") } private var pngURL: URL { documentsURL .appendingPathComponent("data") .appendingPathExtension("png") } //MARK: - Lifecycle func createData(url: URL, type: WebDataManager.DataType, completion: @escaping (Result<Bool, Error>) -> Void) { webDataManager.createData(url: url, type: type) { result in switch result { case .success(let data): let saved = self.fileManager.createFile(atPath: self.path(for: type), contents: data, attributes: nil) completion(.success(saved)) case .failure(let error): completion(.failure(error)) } } } func fileExists(for data: ButtonData) -> Bool { fileManager.fileExists(atPath: data.url.path) } //MARK: - Private private func path(for type: WebDataManager.DataType) -> String { switch type { case .webArchive: return webarchiveURL.path case .pdf: return pdfURL.path case .snapshot: return pngURL.path } } }
26.73
118
0.542462
01d17313dde8cc24256a6db3826f804f420f17a6
2,419
// // PublisherExtensions.swift // TriforkSwiftExtensions // // Created by Kim de Vos on 14/11/2020. // Copyright © 2020 Trifork A/S. All rights reserved. // import Foundation #if canImport(Combine) import Combine @available(iOS 13.0, *) extension Publisher { /// Receives on `DispatchQueue.main` public func receiveOnMain() -> Publishers.ReceiveOn<Self, DispatchQueue> { return self.receive(on: DispatchQueue.main) } /// Zips conditionally based on `condition`. /// Uses `Just` with fallback value if `condition` is `false` public func zipIf<P>( _ condition: @autoclosure () -> Bool, _ constructPublisher: @autoclosure () -> P, fallbackOutput: P.Output) -> Publishers.Zip<Self, AnyPublisher<P.Output, P.Failure>> where P : Publisher, P.Failure == Self.Failure { let publisher = PublisherHelper.conditional(condition: condition(), constructPublisher: constructPublisher(), fallbackOutput: fallbackOutput) return zip(publisher) } /// FlatMaps conditionally based on `condition` /// Uses `Just` with fallback value if `condition` is `false` public func flatMapIf<P>( _ condition: @escaping @autoclosure () -> Bool, _ constructPublisher: @escaping (Self.Output) -> P, fallbackOutput: P.Output) -> Publishers.FlatMap<AnyPublisher<P.Output, P.Failure>, Self> where P : Publisher, Self.Failure == P.Failure { self.flatMap { (output) in PublisherHelper.conditional(condition: condition(), constructPublisher: constructPublisher(output), fallbackOutput: fallbackOutput) } } } @available(iOS 13.0, *) private final class PublisherHelper { /// Takes a bool (as autoclosure) which indicates whether the publisher should be constructed. /// If the `condition` returns `true` the publisher will be constructed, otherwise it will fallback on /// a `Just` publisher with `fallbackOutput` static func conditional<P>( condition: @autoclosure () -> Bool, constructPublisher: @autoclosure () -> P, fallbackOutput: P.Output) -> AnyPublisher<P.Output, P.Failure> where P : Publisher { if condition() { return constructPublisher().eraseToAnyPublisher() } else { return Just(fallbackOutput) .setFailureType(to: P.Failure.self) .eraseToAnyPublisher() } } } #endif
38.396825
149
0.666391
e0dc48a8b9736cdade978847441c121f299afb7c
3,911
// // ReportViewController.swift // EASIPRO-Clinic // // Created by Raheel Sayeed on 8/2/19. // Copyright © 2019 Boston Children's Hospital. All rights reserved. // import Foundation import UIKit import SMART class ReportViewController: UITableViewController { public final var questionnaireResponses: [QuestionnaireResponse]! public convenience init(_ responses: [QuestionnaireResponse]) { self.init(style: .grouped) self.questionnaireResponses = responses self.title = "QuestionnaireResponses" } override func viewDidLoad() { super.viewDidLoad() navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(dismissSelf(_:))) navigationItem.leftBarButtonItem = UIBarButtonItem(title: "Submit", style: .plain, target: self, action: #selector(submitToEHR(_:))) } @objc func submitToEHR(_ sender: Any) { guard let client = SMARTClient.shared.client else { showMsg(msg: "Server not found, Login to the FHIR server") return } let group = DispatchGroup() for q in questionnaireResponses { group.enter() q.create(client.server) { (error) in if let error = error { print(error) } group.leave() } } group.notify(queue: .main) { self.showMsg(msg: "Submission Complete") self.tableView.reloadData() } } @objc func dismissSelf(_ sender: Any) { dismiss(animated: true, completion: nil) } // MARK: - Table View public override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { return "Completed" } override public func numberOfSections(in tableView: UITableView) -> Int { return questionnaireResponses != nil ? 1 : 0 } override public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return questionnaireResponses?.count ?? 0 } override public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "QCell") ?? UITableViewCell(style: .subtitle, reuseIdentifier: "QCell") cell.accessoryType = .detailDisclosureButton let response = questionnaireResponses![indexPath.row] cell.textLabel?.text = "QuestionnaireResponse" cell.detailTextLabel?.text = response.sm_metaData return cell } override func tableView(_ tableView: UITableView, accessoryButtonTappedForRowWith indexPath: IndexPath) { let qr = questionnaireResponses![indexPath.row] let fhirViewer = FHIRViewController(qr) navigationController?.pushViewController(fhirViewer, animated: true) } } open class FHIRViewController: UIViewController { public final var resource: DomainResource? var textView: UITextView! convenience init(_ resource: DomainResource?) { self.init() self.resource = resource } open override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = UIColor.white let frame = view.frame textView = UITextView(frame: frame) textView.translatesAutoresizingMaskIntoConstraints = false view.addSubview(textView) let views = ["textView": textView as Any] view.sm_addVisualConstraint("H:|-[textView]-|", views) view.sm_addVisualConstraint("V:|-[textView]-|", views) if let json = resource?.sm_jsonString { textView.text = json } } }
29.854962
141
0.62695
f8ba019e07c980acb6f6abd8f519ddfd7194740e
712
// // LegaSerieAViewController.swift // Example // // Created by ShevaKuilin on 2019/6/11. // Copyright © 2019 Warpdrives Team. All rights reserved. // import UIKit class LegaSerieAViewController: LeagueViewController { override func viewDidLoad() { super.viewDidLoad() loadData() } } private extension LegaSerieAViewController { private func loadData() { updateTeam(["Milan", "Inter Milan", "Juventus", "Roma", "Lazio", "Fiorentina", "Napoli", "Sampdoria", "Torino", "Atalanta"]) } }
22.25
58
0.5
282f9c75b203c8f7e0c5539fced8c8dc9cdcbf92
614
// // UITextField+BottomBorder.swift // SeaseAssist // // Created by lsease on 5/16/17. // Copyright © 2017 Logan Sease. All rights reserved. // import UIKit @objc public extension UITextField { @objc func setBottomBorder(color: UIColor = UIColor(hex: "A5A5A5")) { self.borderStyle = .none self.layer.backgroundColor = UIColor.white.cgColor self.layer.masksToBounds = false self.layer.shadowColor = color.cgColor self.layer.shadowOffset = CGSize(width: 0.0, height: 1.0) self.layer.shadowOpacity = 0.5 self.layer.shadowRadius = 0.0 } }
26.695652
72
0.656352
7af785a878bf1dedbe319c1b91699be5609d75ff
1,430
// // Copyright (c) 2021 gematik 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. // @testable import CardReaderProviderApi import Nimble import XCTest public class TestReader: CardReaderType { public private(set) var cardPresent: Bool = false public func onCardPresenceChanged(_: @escaping (CardReaderType) -> Void) {} // swiftlint:disable unavailable_function public func connect(_: [String: Any]) throws -> CardType? { fatalError("connect() has not been implemented") } public private(set) var name: String = "" init(_ name: String) { self.name = name } } final class CardReaderTest: XCTestCase { func testDisplayNameDefault() { let reader = TestReader("Reader's name") expect(reader.name).to(equal(reader.displayName)) } static var allTests = [ ("testDisplayNameDefault", testDisplayNameDefault), ] }
29.183673
79
0.695105
33644d12a45390380281f8bf1a701a7434d147a6
6,565
// // ReviewViewController.swift // WeScan // // Created by Boris Emorine on 2/25/18. // Copyright © 2018 WeTransfer. All rights reserved. // import UIKit /// The `ReviewViewController` offers an interface to review the image after it has been cropped and deskwed according to the passed in quadrilateral. final class ReviewViewController: UIViewController { private var rotationAngle: CGFloat = 0 private var enhancedImageIsAvailable = false private var isCurrentlyDisplayingEnhancedImage = false lazy var imageView: UIImageView = { let imageView = UIImageView() imageView.clipsToBounds = true imageView.isOpaque = true imageView.image = results.croppedScan.image imageView.backgroundColor = .black imageView.contentMode = .scaleAspectFit imageView.translatesAutoresizingMaskIntoConstraints = false return imageView }() private lazy var enhanceButton: UIBarButtonItem = { let image = UIImage(systemName: "wand.and.rays.inverse", named: "enhance", in: Bundle(for: ScannerViewController.self), compatibleWith: nil) let button = UIBarButtonItem(image: image, style: .plain, target: self, action: #selector(toggleEnhancedImage)) button.tintColor = .white return button }() private lazy var rotateButton: UIBarButtonItem = { let image = UIImage(systemName: "rotate.right", named: "rotate", in: Bundle(for: ScannerViewController.self), compatibleWith: nil) let button = UIBarButtonItem(image: image, style: .plain, target: self, action: #selector(rotateImage)) button.tintColor = .white return button }() private lazy var doneButton: UIBarButtonItem = { let button = UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(finishScan)) button.tintColor = navigationController?.navigationBar.tintColor return button }() private let results: ImageScannerResults // MARK: - Life Cycle init(results: ImageScannerResults) { self.results = results super.init(nibName: nil, bundle: nil) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() enhancedImageIsAvailable = results.enhancedScan != nil setupViews() setupToolbar() setupConstraints() title = NSLocalizedString("Edit", comment: "") navigationItem.rightBarButtonItem = doneButton } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) // We only show the toolbar (with the enhance button) if the enhanced image is available. if enhancedImageIsAvailable { navigationController?.setToolbarHidden(false, animated: true) } } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) navigationController?.setToolbarHidden(true, animated: true) } // MARK: Setups private func setupViews() { view.addSubview(imageView) } private func setupToolbar() { guard enhancedImageIsAvailable else { return } navigationController?.toolbar.barStyle = .blackTranslucent let fixedSpace = UIBarButtonItem(barButtonSystemItem: .fixedSpace, target: nil, action: nil) let flexibleSpace = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil) toolbarItems = [fixedSpace, enhanceButton, flexibleSpace, rotateButton, fixedSpace] } private func setupConstraints() { imageView.translatesAutoresizingMaskIntoConstraints = false var imageViewConstraints: [NSLayoutConstraint] = [] if #available(iOS 11.0, *) { imageViewConstraints = [ view.safeAreaLayoutGuide.topAnchor.constraint(equalTo: imageView.safeAreaLayoutGuide.topAnchor), view.safeAreaLayoutGuide.trailingAnchor.constraint(equalTo: imageView.safeAreaLayoutGuide.trailingAnchor), view.safeAreaLayoutGuide.bottomAnchor.constraint(equalTo: imageView.safeAreaLayoutGuide.bottomAnchor), view.safeAreaLayoutGuide.leadingAnchor.constraint(equalTo: imageView.safeAreaLayoutGuide.leadingAnchor) ] } else { imageViewConstraints = [ view.topAnchor.constraint(equalTo: imageView.topAnchor), view.trailingAnchor.constraint(equalTo: imageView.trailingAnchor), view.bottomAnchor.constraint(equalTo: imageView.bottomAnchor), view.leadingAnchor.constraint(equalTo: imageView.leadingAnchor) ] } NSLayoutConstraint.activate(imageViewConstraints) } // MARK: - Actions @objc private func reloadImage() { if enhancedImageIsAvailable, isCurrentlyDisplayingEnhancedImage { imageView.image = results.enhancedScan?.image.rotate(degress: rotationAngle) ?? results.enhancedScan?.image } else { imageView.image = results.croppedScan.image.rotate(degress: rotationAngle) ?? results.croppedScan.image } } @objc func toggleEnhancedImage() { guard enhancedImageIsAvailable else { return } isCurrentlyDisplayingEnhancedImage.toggle() reloadImage() if isCurrentlyDisplayingEnhancedImage { enhanceButton.tintColor = .yellow } else { enhanceButton.tintColor = .white } } @objc func rotateImage() { rotationAngle += 90 if rotationAngle == 360 { rotationAngle = 0 } reloadImage() } @objc private func finishScan() { guard let imageScannerController = navigationController as? ImageScannerController else { return } var newResults = results if let cropped = newResults.croppedScan.image.rotate(degress: rotationAngle) { newResults.croppedScan.image = cropped } if let enhanced = newResults.enhancedScan?.image.rotate(degress: rotationAngle) { newResults.enhancedScan?.image = enhanced } newResults.doesUserPreferEnhancedScan = isCurrentlyDisplayingEnhancedImage imageScannerController.imageScannerDelegate?.imageScannerController(imageScannerController, didFinishScanningWithResults: newResults) } }
36.882022
150
0.670069
ed9e30f13050618bc6bcb08f75c7d11db2e81fbc
1,811
// // String+NYPLAdditionsTests.swift // SimplyETests // // Created by Ettore Pasquini on 4/8/20. // Copyright © 2020 NYPL Labs. All rights reserved. // import XCTest @testable import SimplyE class String_NYPLAdditionsTests: XCTestCase { func testURLEncodingQueryParam() { let multiASCIIWord = "Pinco Pallino".stringURLEncodedAsQueryParamValue() XCTAssertEqual(multiASCIIWord, "Pinco%20Pallino") let queryCharsSeparators = "?=&".stringURLEncodedAsQueryParamValue() XCTAssertEqual(queryCharsSeparators, "%3F%3D%26") let accentedVowels = "àèîóú".stringURLEncodedAsQueryParamValue() XCTAssertEqual(accentedVowels, "%C3%A0%C3%A8%C3%AE%C3%B3%C3%BA") let legacyEscapes = ";/?:@&=$+{}<>,".stringURLEncodedAsQueryParamValue() XCTAssertEqual(legacyEscapes, "%3B%2F%3F%3A%40%26%3D%24%2B%7B%7D%3C%3E%2C") let noEscapes = "-_".stringURLEncodedAsQueryParamValue() XCTAssertEqual(noEscapes, "-_") let otherEscapes = "~`!#%^*()[]|\\".stringURLEncodedAsQueryParamValue() XCTAssertEqual(otherEscapes, "~%60!%23%25%5E*()%5B%5D%7C%5C") } func testMD5() { XCTAssertEqual("password".md5hex(), "5f4dcc3b5aa765d61d8327deb882cf99") } func testBase64Encode() { let s = ("ynJZEsWMnTudEGg646Tmua" as NSString).fileSystemSafeBase64EncodedString(usingEncoding: String.Encoding.utf8.rawValue) XCTAssertEqual(s, "eW5KWkVzV01uVHVkRUdnNjQ2VG11YQ") } func testBase64Decode() { let s = ("eW5KWkVzV01uVHVkRUdnNjQ2VG11YQ" as NSString).fileSystemSafeBase64DecodedString(usingEncoding: String.Encoding.utf8.rawValue) XCTAssertEqual(s, "ynJZEsWMnTudEGg646Tmua") } func testSHA256() { XCTAssertEqual(("967824¬Ó¨⁄€™®©♟♞♝♜♛♚♙♘♗♖♕♔" as NSString).sha256(), "269b80eff0cd705e4b1de9fdbb2e1b0bccf30e6124cdc3487e8d74620eedf254") } }
34.826923
138
0.722805
f4dbd40f8a43b8aa7f8477fc3412e8e2277b2b07
2,081
// Syrup auto-generated file import Foundation public extension MerchantApi { struct QueryWithReservedWordOnInlineFragmentQuery: GraphApiQuery, ResponseAssociable, Equatable { // MARK: - Query Variables // MARK: - Initializer public init() { } // MARK: - Helpers public static let customEncoder: JSONEncoder = MerchantApi.customEncoder private enum CodingKeys: CodingKey { } public typealias Response = QueryWithReservedWordOnInlineFragmentResponse public let queryString: String = """ query QueryWithReservedWordOnInlineFragment { __typename node(id: "123") { __typename id ... on Product { __typename let: title } } } """ } } extension MerchantApi.QueryWithReservedWordOnInlineFragmentQuery { public static let operationSelections: GraphSelections.Operation? = GraphSelections.Operation( type: .query("QueryRoot"), selectionSet: [ .field(GraphSelections.Field(name: "__typename", alias: nil , arguments: [] , parentType: .object("QueryRoot"), type: .scalar("String"), selectionSet: [] )) , .field(GraphSelections.Field(name: "node", alias: nil , arguments: [ GraphSelections.Argument(name: "id", value: .stringValue("123") ) ] , parentType: .object("QueryRoot"), type: .interface("Node"), selectionSet: [ .field(GraphSelections.Field(name: "__typename", alias: nil , arguments: [] , parentType: .interface("Node"), type: .scalar("String"), selectionSet: [] )) , .field(GraphSelections.Field(name: "id", alias: nil , arguments: [] , parentType: .interface("Node"), type: .scalar("ID"), selectionSet: [] )) , .inlineFragment(GraphSelections.InlineFragment(typeCondition: .object("Product") , selectionSet: [ .field(GraphSelections.Field(name: "__typename", alias: nil , arguments: [] , parentType: .object("Product"), type: .scalar("String"), selectionSet: [] )) , .field(GraphSelections.Field(name: "title", alias: "let" , arguments: [] , parentType: .object("Product"), type: .scalar("String"), selectionSet: [] )) ] )) ] )) ] ) }
24.197674
135
0.682364
d95a28f2b5f25c1b4a104321c48076d4ec351960
534
//: [Table of Contents](Table%20of%20Contents) import UIKit //: Credit to [@soffes](https://twitter.com/soffes) extension UIFont { public var fontWithMonospaceNumbers: UIFont { let fontDescriptor = UIFontDescriptor(name: fontName, size: pointSize).addingAttributes([ UIFontDescriptorFeatureSettingsAttribute: [ [ UIFontFeatureTypeIdentifierKey: kNumberSpacingType, UIFontFeatureSelectorIdentifierKey: kMonospacedNumbersSelector ] ] ]) return UIFont(descriptor: fontDescriptor, size: pointSize) } }
26.7
91
0.758427
72168e7e816c535853f537dfc8d221cc24a5c4e5
551
// // Environment.swift // NearByApp // // Created by Islam on 8/15/20. // Copyright © 2020 Spaces. All rights reserved. // import Foundation public enum Environment: String { case debug, release public static var current: Environment? { guard let infoDictionary = Bundle.main.infoDictionary else { return nil } guard let environment = infoDictionary["Configuration"] as? String else { return nil } return Environment(rawValue: environment.lowercased()) } }
19.678571
81
0.627949
d73f8335d1703c0d7e9f1b8504d4b263ce9876b0
1,502
// // NEP5Token.swift // NeoSwift // // Created by Andrei Terentiev on 10/29/17. // Copyright © 2017 drei. All rights reserved. // import Foundation @objc public class NEP5Token: NSObject, Codable { @objc public var name: String @objc public var symbol: String @objc public var decimals: Int @objc public var totalSupply: Int enum CodingKeys: String, CodingKey { case name = "name" case symbol = "symbol" case decimals = "decimals" case totalSupply = "totalSupply" } @objc public init(name: String, symbol: String, decimals: Int, totalSupply: Int) { self.name = name self.symbol = symbol self.decimals = decimals self.totalSupply = totalSupply } @objc public convenience init?(from vmStack: [StackEntry]) { let nameEntry = vmStack[0] let symbolEntry = vmStack[1] let decimalsEntry = vmStack[2] let totalSupplyEntry = vmStack[3] let name = String(data: (nameEntry.hexDataValue.dataWithHexString()), encoding: .utf8) ?? "" let symbol = String(data: (symbolEntry.hexDataValue.dataWithHexString()), encoding: .utf8) ?? "" let totalSupplyData = totalSupplyEntry.hexDataValue let totalSupply = UInt64(littleEndian: totalSupplyData.dataWithHexString().withUnsafeBytes { $0.pointee }) self.init(name: name, symbol: symbol, decimals: decimalsEntry.intValue, totalSupply: Int(totalSupply / 100000000)) } }
34.136364
122
0.653129
8f905338c096fbe7e430c235ae8b334c6e93dfc6
1,515
// // AdobeContentProtectionService.swift // Palace // // Created by Vladimir Fedorov on 30.06.2021. // Copyright © 2021 The Palace Project. All rights reserved. // #if FEATURE_DRM_CONNECTOR import Foundation import R2Shared import R2Streamer import R2Navigator /// Provides information about a publication's content protection and manages user rights. final class AdobeContentProtectionService: ContentProtectionService { var error: Error? let context: PublicationServiceContext init(context: PublicationServiceContext) { self.context = context self.error = nil if let adobeFetcher = context.fetcher as? AdobeDRMFetcher { if let drmError = adobeFetcher.container.epubDecodingError { self.error = NSError(domain: "Adobe DRM decoding error", code: TPPErrorCode.adobeDRMFulfillmentFail.rawValue, userInfo: [ "AdobeDRMContainer error msg": drmError ]) } } } /// A restricted publication has a limited access to its manifest and /// resources and can’t be rendered with a Navigator. It is usually /// only used to import a publication to the user’s bookshelf. var isRestricted: Bool { context.publication.ref == nil || error != nil } var rights: UserRights { isRestricted ? AllRestrictedUserRights() : UnrestrictedUserRights() } var name: LocalizedString? { LocalizedString.nonlocalized("Adobe DRM") } } #endif
28.584906
90
0.679208
e8848906f6bc41043de3bc83dd1659d04a49be00
903
// swift-tools-version:5.1 // The swift-tools-version declares the minimum version of Swift required to build this package. import PackageDescription let package = Package( name: "RxTimelane", platforms: [ .macOS(.v10_14), .iOS(.v12), .tvOS(.v12), .watchOS(.v5) ], products: [ .library( name: "RxTimelane", targets: ["RxTimelane"]), ], dependencies: [ .package(url: "https://github.com/ReactiveX/RxSwift.git", from: "5.1.0"), .package(url: "https://github.com/icanzilb/TimelaneCore", from: "1.0.1") ], targets: [ .target( name: "RxTimelane", dependencies: ["RxSwift", "TimelaneCore"]), .testTarget( name: "RxTimelaneTests", dependencies: ["RxTimelane", "RxSwift", "TimelaneCoreTestUtils"]), ], swiftLanguageVersions: [.v5] )
27.363636
96
0.568106
5bb5b2ecfc90cbba12c6d916d35cee7a4b42ad22
232
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing { case c, (([Void{ deinit { class Void{ enum A { class case c,
16.571429
87
0.732759
4b95525daa585ef461da9c23eb6853654eafbb14
559
class Solution { func sortArrayByParityII(_ A: [Int]) -> [Int] { var outputArray = A var index2 = 1 for index in stride(from: 0, through: outputArray.count - 1, by: 2) { if outputArray[index] % 2 == 1 { while outputArray[index2] % 2 == 1 { index2 += 2 } var temp = outputArray[index] outputArray[index] = outputArray[index2] outputArray[index2] = temp } } return outputArray } }
31.055556
77
0.468694
48d57a27fdc0b437c00f0ecf42433e4df1100ae3
530
// // HeartRateSampleFetcher.swift // SampleFetchers // // Created by Bryan Nova on 9/6/20. // Copyright © 2020 Bryan Nova. All rights reserved. // import Foundation import DependencyInjection import Queries import Samples public final class HeartRateSampleFetcher: SingleDateHealthKitSampleFetcher { public override var sampleTypePluralName: String { "Heart Rates" } public init() { super.init( { injected(QueryFactory.self).heartRateQuery() }, dateAttribute: CommonSampleAttributes.healthKitTimestamp ) } }
21.2
77
0.762264
489df8920a35e24999c5300c8f6c24a5b8768f24
839
// // ALFileManagerProtocol.swift // AdvancedLogger // // Created by Дмитрий Торопкин on 05.04.2020. // Copyright © 2020 Dmitriy Toropkin. All rights reserved. // import Foundation // MARK: - ALFileManagerProtocol /// Protocol for Manager for write and read file from bundle protocol ALFileDiskManagerProtocol { /// write data to disk /// - Parameters: /// - data: data that need to be writed /// - completion: completion block with optional Error func write(data: Data, completion: (Error?) -> Void) /// Read data from disk /// - Parameter completion: completion block with optional data from storage func read(completion: (Data?) -> Void) /// Remove log file from disk /// - Parameter completion: completion block with optional Error func clean(completion: (Error?) -> Void) }
29.964286
80
0.681764
b9ebe3c67d1a73dd34514617648ccf1760f658e7
1,253
// // ViewController.swift // swift11 // Swift11 - 类的计算属性(使用get和set来间接获取/改变其他属性的值) // Created by Alan on 16/6/17. // Copyright © 2016年 jollycorp. All rights reserved. // import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. //1. let sum = getSum(); print(sum.sum); //2 sum.sum = 5; print(sum.b); //4 } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } } //1.Swift中类可以使用计算属性,即使用get和set来间接获取/改变其他属性的值 class getSum{ var a:Int = 1; var b:Int = 1; var sum:Int{ get { return a + b; } set(val) { b = val - a; } } } //2.对于set有简写方法,简写时,新赋的值默认为newValue class getSum2{ var a:Int = 1; var b:Int = 1; var sum:Int{ get { return a + b; } set { b = newValue - a; } } } //3.如果只要get,不要set方法时可以简写成如下代码 class getSum3{ var a:Int = 1; var b:Int = 1; var sum:Int { return a + b; } }
17.647887
80
0.52913
e839d7d65284099d68843732cb3dda5c0631a689
919
//: [Previous](@previous) import Foundation class Solution { func wordBreak(_ s: String, _ wordDict: [String]) -> Bool { let wordDictSet = Set(wordDict) var dp = [Bool](repeating: false, count: s.count + 1) // 任意空字符串可被分割 dp[0] = true for i in 1...s.count { for j in 0..<i { let startIndex = s.index(s.startIndex, offsetBy: j) let endIndex = s.index(s.startIndex, offsetBy: i) if dp[j] && wordDictSet.contains(String(s[startIndex..<endIndex])) { dp[i] = true break } } } return dp.last ?? false } } // Tests let s = Solution() s.wordBreak("leetcode", ["leet", "code"]) == true s.wordBreak("applepenapple", ["apple", "pen"]) == true s.wordBreak("catsandog", ["cats", "dog", "sand", "adn", "cat"]) == false //: [Next](@next)
27.848485
84
0.509249
38376823c315aa755cf29ef036e8da2cbb8fb979
4,210
// // AppDelegate.swift // BrowserOSX // // Created by Sash Zats on 12/19/15. // Copyright © 2015 Sash Zats. All rights reserved. // import Cocoa import WebKit import MultipeerConnectivity @NSApplicationMain class AppDelegate: NSObject, NSApplicationDelegate { } class WindowController: NSWindowController { private var storage = NSHTTPCookieStorage.sharedHTTPCookieStorage() private var advertiser: MCNearbyServiceAdvertiser! private var connectedSessoins: Set<MCSession> = [] @IBOutlet weak var textField: NSTextField! private var URL: NSURL! override func windowDidLoad() { super.windowDidLoad() window?.titleVisibility = .Hidden let peer = MCPeerID(displayName: NSHost.currentHost().localizedName ?? NSUUID().UUIDString) advertiser = MCNearbyServiceAdvertiser(peer: peer, discoveryInfo: nil, serviceType: "browser-tv") advertiser.delegate = self advertiser.startAdvertisingPeer() } @IBAction func _sendButtonAction(sender: AnyObject) { guard URL != nil else { return } let website = Website(URL: URL, cookies: storage.cookies ?? []) let data = website.data connectedSessoins .filter{ !$0.connectedPeers.isEmpty } .forEach{ session in do { try session.sendData(data, toPeers: session.connectedPeers, withMode: .Reliable) } catch { assertionFailure() } } } @IBAction func textFieldAction(sender: AnyObject) { storage.deleteAllCookies() let controller = window?.contentViewController as! ViewController let URLString = textField.stringValue.hasPrefix("http") || textField.stringValue.hasPrefix("https") ? textField.stringValue : "https://\(textField.stringValue)" textField.stringValue = URLString let URL = NSURL(string: URLString)! self.URL = URL let request = NSURLRequest(URL: URL) controller.webView.mainFrame.loadRequest(request) } } extension WindowController: MCNearbyServiceAdvertiserDelegate { func advertiser(advertiser: MCNearbyServiceAdvertiser, didReceiveInvitationFromPeer peerID: MCPeerID, withContext context: NSData?, invitationHandler: (Bool, MCSession) -> Void) { let peerId = advertiser.myPeerID let session = MCSession(peer: peerId, securityIdentity: nil, encryptionPreference: .None) session.delegate = self connectedSessoins.insert(session) invitationHandler(true, session) } func advertiser(advertiser: MCNearbyServiceAdvertiser, didNotStartAdvertisingPeer error: NSError) { } } extension WindowController: MCSessionDelegate { func session(session: MCSession, peer peerID: MCPeerID, didChangeState state: MCSessionState) { switch state { case .NotConnected: connectedSessoins.remove(session) case .Connected: break case .Connecting: break } } func session(session: MCSession, didReceiveData data: NSData, fromPeer peerID: MCPeerID) { // no-op } func session(session: MCSession, didReceiveStream stream: NSInputStream, withName streamName: String, fromPeer peerID: MCPeerID) { // no-op } func session(session: MCSession, didStartReceivingResourceWithName resourceName: String, fromPeer peerID: MCPeerID, withProgress progress: NSProgress) { // no-op } func session(session: MCSession, didFinishReceivingResourceWithName resourceName: String, fromPeer peerID: MCPeerID, atURL localURL: NSURL, withError error: NSError?) { // no-op } } class ViewController: NSViewController { @IBOutlet weak var webView: WebView! override func viewDidLoad() { super.viewDidLoad() } } private extension NSHTTPCookieStorage { func deleteAllCookies() { if let cookies = cookies { for cookie in cookies { deleteCookie(cookie) } } } }
30.071429
183
0.648931
1c75f1255fc8c623f3d47b9bda02a9a578029188
9,858
#if canImport(Combine) && canImport(SwiftUI) import Combine import CustomDump import SwiftUI /// A structure that transforms a store into an observable view store in order to compute views from /// store state. /// /// Due to a bug in SwiftUI, there are times that use of this view can interfere with some core /// views provided by SwiftUI. The known problematic views are: /// /// * If a `GeometryReader` or `ScrollViewReader` is used inside a ``WithViewStore`` it will not /// receive state updates correctly. To work around you either need to reorder the views so that /// the `GeometryReader` or `ScrollViewReader` wraps ``WithViewStore``, or, if that is not /// possible, then you must hold onto an explicit /// `@ObservedObject var viewStore: ViewStore<State, Action>` in your view in lieu of using this /// helper (see [here](https://gist.github.com/mbrandonw/cc5da3d487bcf7c4f21c27019a440d18)). /// * If you create a `Stepper` via the `Stepper.init(onIncrement:onDecrement:label:)` initializer /// inside a ``WithViewStore`` it will behave erratically. To work around you should use the /// initializer that takes a binding (see /// [here](https://gist.github.com/mbrandonw/dee2ceac2c316a1619cfdf1dc7945f66)). /// /// Due to a bug in SwiftUI, there are times that use of this view can interfere with some core /// views provided by SwiftUI. The known problematic views are: /// /// * If a `GeometryReader` or `ScrollViewReader` is used inside a `WithViewStore` it will not /// receive state updates correctly. To work around you either need to reorder the views so that /// the `GeometryReader` or `ScrollViewReader` wraps `WithViewStore`, or, if that is not possible, /// then you must hold onto an explicit `@ObservedObject var viewStore: ViewStore<State, Action>` /// in your view in lieu of using this helper (see /// [here](https://gist.github.com/mbrandonw/cc5da3d487bcf7c4f21c27019a440d18)). /// * If you create a `Stepper` via the `Stepper.init(onIncrement:onDecrement:label:)` initializer /// inside a `WithViewStore` it will behave erratically. To work around you should use the /// initializer that takes a binding (see /// [here](https://gist.github.com/mbrandonw/dee2ceac2c316a1619cfdf1dc7945f66)). public struct WithViewStore<State, Action, Content> { private let content: (ViewStore<State, Action>) -> Content #if DEBUG private let file: StaticString private let line: UInt private var prefix: String? private var previousState: (State) -> State? #endif @ObservedObject private var viewStore: ViewStore<State, Action> fileprivate init( store: Store<State, Action>, removeDuplicates isDuplicate: @escaping (State, State) -> Bool, file: StaticString = #fileID, line: UInt = #line, content: @escaping (ViewStore<State, Action>) -> Content ) { self.content = content #if DEBUG self.file = file self.line = line var previousState: State? = nil self.previousState = { currentState in defer { previousState = currentState } return previousState } #endif self.viewStore = ViewStore(store, removeDuplicates: isDuplicate) } /// Prints debug information to the console whenever the view is computed. /// /// - Parameter prefix: A string with which to prefix all debug messages. /// - Returns: A structure that prints debug messages for all computations. public func debug(_ prefix: String = "") -> Self { var view = self #if DEBUG view.prefix = prefix #endif return view } fileprivate var _body: Content { #if DEBUG if let prefix = self.prefix { var stateDump = "" customDump(self.viewStore.state, to: &stateDump, indent: 2) let difference = self.previousState(self.viewStore.state) .map { diff($0, self.viewStore.state).map { "(Changed state)\n\($0)" } ?? "(No difference in state detected)" } ?? "(Initial state)\n\(stateDump)" func typeName(_ type: Any.Type) -> String { var name = String(reflecting: type) if let index = name.firstIndex(of: ".") { name.removeSubrange(...index) } return name } print( """ \(prefix.isEmpty ? "" : "\(prefix): ")\ WithViewStore<\(typeName(State.self)), \(typeName(Action.self)), _>\ @\(self.file):\(self.line) \(difference) """ ) } #endif return self.content(self.viewStore) } } extension WithViewStore: View where Content: View { /// Initializes a structure that transforms a store into an observable view store in order to /// compute views from store state. /// /// - Parameters: /// - store: A store. /// - isDuplicate: A function to determine when two `State` values are equal. When values are /// equal, repeat view computations are removed, /// - content: A function that can generate content from a view store. public init( _ store: Store<State, Action>, removeDuplicates isDuplicate: @escaping (State, State) -> Bool, file: StaticString = #fileID, line: UInt = #line, @ViewBuilder content: @escaping (ViewStore<State, Action>) -> Content ) { self.init( store: store, removeDuplicates: isDuplicate, file: file, line: line, content: content ) } public var body: Content { self._body } } extension WithViewStore where State: Equatable, Content: View { /// Initializes a structure that transforms a store into an observable view store in order to /// compute views from equatable store state. /// /// - Parameters: /// - store: A store of equatable state. /// - content: A function that can generate content from a view store. public init( _ store: Store<State, Action>, file: StaticString = #fileID, line: UInt = #line, @ViewBuilder content: @escaping (ViewStore<State, Action>) -> Content ) { self.init(store, removeDuplicates: ==, file: file, line: line, content: content) } } extension WithViewStore where State == Void, Content: View { /// Initializes a structure that transforms a store into an observable view store in order to /// compute views from equatable store state. /// /// - Parameters: /// - store: A store of equatable state. /// - content: A function that can generate content from a view store. public init( _ store: Store<State, Action>, file: StaticString = #fileID, line: UInt = #line, @ViewBuilder content: @escaping (ViewStore<State, Action>) -> Content ) { self.init(store, removeDuplicates: ==, file: file, line: line, content: content) } } extension WithViewStore: DynamicViewContent where State: Collection, Content: DynamicViewContent { public typealias Data = State public var data: State { self.viewStore.state } } #endif #if canImport(Combine) && canImport(SwiftUI) && compiler(>=5.3) import SwiftUI @available(iOS 14, macOS 11, tvOS 14, watchOS 7, *) extension WithViewStore: Scene where Content: Scene { /// Initializes a structure that transforms a store into an observable view store in order to /// compute views from store state. /// /// - Parameters: /// - store: A store. /// - isDuplicate: A function to determine when two `State` values are equal. When values are /// equal, repeat view computations are removed, /// - content: A function that can generate content from a view store. public init( _ store: Store<State, Action>, removeDuplicates isDuplicate: @escaping (State, State) -> Bool, file: StaticString = #fileID, line: UInt = #line, @SceneBuilder content: @escaping (ViewStore<State, Action>) -> Content ) { self.init( store: store, removeDuplicates: isDuplicate, file: file, line: line, content: content ) } public var body: Content { self._body } } @available(iOS 14, macOS 11, tvOS 14, watchOS 7, *) extension WithViewStore where State: Equatable, Content: Scene { /// Initializes a structure that transforms a store into an observable view store in order to /// compute scenes from equatable store state. /// /// - Parameters: /// - store: A store of equatable state. /// - content: A function that can generate content from a view store. public init( _ store: Store<State, Action>, file: StaticString = #fileID, line: UInt = #line, @SceneBuilder content: @escaping (ViewStore<State, Action>) -> Content ) { self.init(store, removeDuplicates: ==, file: file, line: line, content: content) } } @available(iOS 14, macOS 11, tvOS 14, watchOS 7, *) extension WithViewStore where State == Void, Content: Scene { /// Initializes a structure that transforms a store into an observable view store in order to /// compute scenes from equatable store state. /// /// - Parameters: /// - store: A store of equatable state. /// - content: A function that can generate content from a view store. public init( _ store: Store<State, Action>, file: StaticString = #fileID, line: UInt = #line, @SceneBuilder content: @escaping (ViewStore<State, Action>) -> Content ) { self.init(store, removeDuplicates: ==, file: file, line: line, content: content) } } #endif
38.811024
102
0.636336
9cb69566a0dd8819f15e17eb5fe406b8753d64f6
10,284
// // CXTitleView.swift // pageView // // Created by mac on 2016/12/22. // Copyright © 2016年 chuxia. All rights reserved. // import UIKit public protocol CXTitleViewDelegate : class { func titleView(_ titleView : CXTitleView, currentIndex : Int) } public class CXTitleView: UIView { weak var delegate : CXTitleViewDelegate? fileprivate var titles : [String] fileprivate var style : CXPageStyle fileprivate lazy var currentIndex : Int = 0 fileprivate lazy var titleLabels : [UILabel] = [UILabel]() fileprivate lazy var scrollView : UIScrollView = { let scrollView = UIScrollView(frame: self.bounds) scrollView.showsHorizontalScrollIndicator = false scrollView.scrollsToTop = false return scrollView }() fileprivate lazy var splitLineView : UIView = { let splitView = UIView() splitView.backgroundColor = UIColor.lightGray let h : CGFloat = 0.5 splitView.frame = CGRect(x: 0, y: self.frame.height - h, width: self.frame.width, height: h) return splitView }() fileprivate lazy var bottomLine : UIView = { let bottomLine = UIView() bottomLine.backgroundColor = self.style.bottomLineColor return bottomLine }() fileprivate lazy var coverView : UIView = { let coverView = UIView() coverView.backgroundColor = self.style.coverBgColor coverView.alpha = 0.7 return coverView }() fileprivate lazy var normalColorRGB : (r : CGFloat, g : CGFloat, b : CGFloat) = self.getRGBWithColor(self.style.normalColor) fileprivate lazy var selectedColorRGB : (r : CGFloat, g : CGFloat, b : CGFloat) = self.getRGBWithColor(self.style.selectedColor) public init(_ frame: CGRect,_ titles: [String], _ style : CXPageStyle) { self.titles = titles self.style = style super.init(frame: frame) setupUI() } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } extension CXTitleView { fileprivate func setupUI() { addSubview(scrollView) addSubview(splitLineView) addTitleLables() setupTitleLableFrame() if style.isShowBottomLine { setupBottomLine() } if style.isShowCover { setupCoverView() } } fileprivate func addTitleLables() { for (i, title) in titles.enumerated() { let titleLabel = UILabel(); titleLabel.text = title; titleLabel.font = style.titleFont titleLabel.tag = i titleLabel.textAlignment = .center titleLabel.textColor = i == 0 ? style.selectedColor : style.normalColor scrollView.addSubview(titleLabel) titleLabels.append(titleLabel) let tapGes = UITapGestureRecognizer(target: self, action: #selector(tapAction(_:))) titleLabel.addGestureRecognizer(tapGes) titleLabel.isUserInteractionEnabled = true } } fileprivate func setupTitleLableFrame() { var titleX: CGFloat = 0.0 var titleW: CGFloat = 0.0 let titleY: CGFloat = 0.0 let titleH : CGFloat = frame.height let count = titles.count for (index, label) in titleLabels.enumerated() { if style.isScrollEnable { let rect = (label.text! as NSString).boundingRect(with: CGSize(width: CGFloat(MAXFLOAT), height: 0.0), options: .usesLineFragmentOrigin, attributes: [NSAttributedStringKey.font : style.titleFont], context: nil) titleW = rect.width if index == 0 { titleX = style.itemMargin * 0.5 } else { let preLabel = titleLabels[index - 1] titleX = preLabel.frame.maxX + style.itemMargin } } else { titleW = frame.width / CGFloat(count) titleX = titleW * CGFloat(index) } label.frame = CGRect(x: titleX, y: titleY, width: titleW, height: titleH) // 放大的代码 if index == 0 { let scale = style.isNeedScale ? style.scaleRange : 1.0 label.transform = CGAffineTransform(scaleX: scale, y: scale) } } if style.isScrollEnable { scrollView.contentSize = CGSize(width: titleLabels.last!.frame.maxX + style.itemMargin * 0.5, height: 0) } } fileprivate func setupBottomLine() { scrollView.addSubview(bottomLine) bottomLine.frame = titleLabels.first!.frame bottomLine.frame.size.height = style.bottomLineH bottomLine.frame.origin.y = bounds.height - style.bottomLineH } fileprivate func setupCoverView() { scrollView.insertSubview(coverView, at: 0) let firstLabel = titleLabels[0] var coverW = firstLabel.frame.width let coverH = style.coverH var coverX = firstLabel.frame.origin.x let coverY = (bounds.height - coverH) * 0.5 if style.isScrollEnable { coverX -= style.coverMargin coverW += style.coverMargin * 2 } coverView.frame = CGRect(x: coverX, y: coverY, width: coverW, height: coverH) coverView.layer.cornerRadius = style.coverRadius coverView.layer.masksToBounds = true } } extension CXTitleView { @objc fileprivate func tapAction(_ tap: UITapGestureRecognizer) { // 0.获取当前Label guard let currentLabel = tap.view as? UILabel else { return } // 1.如果是重复点击同一个Title,那么直接返回 if currentLabel.tag == currentIndex { return } // 2.获取之前的Label let oldLabel = titleLabels[currentIndex] // 3.切换文字的颜色 currentLabel.textColor = style.selectedColor oldLabel.textColor = style.normalColor // 4.保存最新Label的下标值 currentIndex = currentLabel.tag // 5.通知代理 delegate?.titleView(self, currentIndex: currentIndex) // 6.居中显示 contentViewDidEndScroll() // 7.调整bottomLine if style.isShowBottomLine { UIView.animate(withDuration: 0.15, animations: { self.bottomLine.frame.origin.x = currentLabel.frame.origin.x self.bottomLine.frame.size.width = currentLabel.frame.size.width }) } // 8.调整比例 if style.isNeedScale { oldLabel.transform = CGAffineTransform.identity currentLabel.transform = CGAffineTransform(scaleX: style.scaleRange, y: style.scaleRange) } // 9.遮盖移动 if style.isShowCover { let coverX = style.isScrollEnable ? (currentLabel.frame.origin.x - style.coverMargin) : currentLabel.frame.origin.x let coverW = style.isScrollEnable ? (currentLabel.frame.width + style.coverMargin * 2) : currentLabel.frame.width UIView.animate(withDuration: 0.15, animations: { self.coverView.frame.origin.x = coverX self.coverView.frame.size.width = coverW }) } } } extension CXTitleView { fileprivate func getRGBWithColor(_ color : UIColor) -> (CGFloat, CGFloat, CGFloat) { guard let components = color.cgColor.components else { fatalError("请使用RGB方式给Title赋值颜色") } return (components[0] * 255, components[1] * 255, components[2] * 255) } } public extension CXTitleView { func setTitleWithProgress(_ progress : CGFloat, sourceIndex : Int, targetIndex : Int) { // 1.取出sourceLabel/targetLabel let sourceLabel = titleLabels[sourceIndex] let targetLabel = titleLabels[targetIndex] // 3.颜色的渐变(复杂) // 3.1.取出变化的范围 let colorDelta = (selectedColorRGB.0 - normalColorRGB.0, selectedColorRGB.1 - normalColorRGB.1, selectedColorRGB.2 - normalColorRGB.2) // 3.2.变化sourceLabel sourceLabel.textColor = UIColor(r: selectedColorRGB.0 - colorDelta.0 * progress, g: selectedColorRGB.1 - colorDelta.1 * progress, b: selectedColorRGB.2 - colorDelta.2 * progress) // 3.2.变化targetLabel targetLabel.textColor = UIColor(r: normalColorRGB.0 + colorDelta.0 * progress, g: normalColorRGB.1 + colorDelta.1 * progress, b: normalColorRGB.2 + colorDelta.2 * progress) // 4.记录最新的index currentIndex = targetIndex let moveTotalX = targetLabel.frame.origin.x - sourceLabel.frame.origin.x let moveTotalW = targetLabel.frame.width - sourceLabel.frame.width // 5.计算滚动的范围差值 if style.isShowBottomLine { bottomLine.frame.size.width = sourceLabel.frame.width + moveTotalW * progress bottomLine.frame.origin.x = sourceLabel.frame.origin.x + moveTotalX * progress } // 6.放大的比例 if style.isNeedScale { let scaleDelta = (style.scaleRange - 1.0) * progress sourceLabel.transform = CGAffineTransform(scaleX: style.scaleRange - scaleDelta, y: style.scaleRange - scaleDelta) targetLabel.transform = CGAffineTransform(scaleX: 1.0 + scaleDelta, y: 1.0 + scaleDelta) } // 7.计算cover的滚动 if style.isShowCover { coverView.frame.size.width = style.isScrollEnable ? (sourceLabel.frame.width + 2 * style.coverMargin + moveTotalW * progress) : (sourceLabel.frame.width + moveTotalW * progress) coverView.frame.origin.x = style.isScrollEnable ? (sourceLabel.frame.origin.x - style.coverMargin + moveTotalX * progress) : (sourceLabel.frame.origin.x + moveTotalX * progress) } } func contentViewDidEndScroll() { // 0.如果是不需要滚动,则不需要调整中间位置 guard style.isScrollEnable else { return } // 1.获取获取目标的Label let targetLabel = titleLabels[currentIndex] // 2.计算和中间位置的偏移量 var offSetX = targetLabel.center.x - bounds.width * 0.5 if offSetX < 0 { offSetX = 0 } let maxOffset = scrollView.contentSize.width - bounds.width if offSetX > maxOffset { offSetX = maxOffset } // 3.滚动UIScrollView scrollView.setContentOffset(CGPoint(x: offSetX, y: 0), animated: true) } }
35.462069
226
0.621645
abfd3f4b094f1729b8512176ac48c925b3037014
2,151
import Foundation import Quick import Nimble @testable import Composed final class SectionProviderDelegate_Spec: QuickSpec { override func spec() { super.spec() var global: ComposedSectionProvider! var child: Section! var delegate: MockDelegate! beforeEach { global = ComposedSectionProvider() delegate = MockDelegate() global.updateDelegate = delegate child = ArraySection<String>() global.append(child) } it("should call the delegate method for inserting a section") { expect(delegate.didInsertSections).toNot(beNil()) } it("should be called from the global provider") { expect(delegate.didInsertSections?.provider) === global } it("should contain only 1 new section") { expect(delegate.didInsertSections?.sections.count).to(equal(1)) } it("should be called from child") { expect(delegate.didInsertSections?.sections[0]) === child } it("section should equal 1") { expect(delegate.didInsertSections?.indexes) === IndexSet(integer: 0) } } } final class MockDelegate: SectionProviderUpdateDelegate { func provider(_ provider: SectionProvider, willPerformBatchUpdates updates: () -> Void, forceReloadData: Bool) { updates() } func invalidateAll(_ provider: SectionProvider) { } func providerWillUpdate(_ provider: SectionProvider) { } func providerDidUpdate(_ provider: SectionProvider) { } var didInsertSections: (provider: SectionProvider, sections: [Section], indexes: IndexSet)? var didRemoveSections: (provider: SectionProvider, sections: [Section], indexes: IndexSet)? func provider(_ provider: SectionProvider, didInsertSections sections: [Section], at indexes: IndexSet) { didInsertSections = (provider, sections, indexes) } func provider(_ provider: SectionProvider, didRemoveSections sections: [Section], at indexes: IndexSet) { didRemoveSections = (provider, sections, indexes) } }
27.576923
116
0.65272
61426b22a75f897875bba2a5b21a36ad874d8930
500
// // AppServicesManager+HealthKitInteracting.swift // PluggableAppDelegate // // Created by Mikhail Pchelnikov on 31/07/2018. // Copyright © 2018 Michael Pchelnikov. All rights reserved. // import UIKit extension PluggableApplicationDelegate { @available(iOS 9.0, *) open func applicationShouldRequestHealthAuthorization(_ application: UIApplication) { for service in _services { service.applicationShouldRequestHealthAuthorization?(application) } } }
25
89
0.732
1a3e0973be7ea816791866a2deefdef014fcd302
6,281
// // YoutubeKit.swift // YoutubeKit // // Created by Nguyen Thanh Bình on 8/14/19. // Copyright © 2019 Nguyen Thanh Bình. All rights reserved. // import Foundation extension URL { /** Parses a query string of an URL @return key value dictionary with each parameter as an array */ func componentsForQueryString() -> [String: Any]? { if let query = self.query { return query.componentsFromQueryString() } // Note: find youtube ID in m.youtube.com "https://m.youtube.com/#/watch?v=1hZ98an9wjo" let result = absoluteString.components(separatedBy: "?") if result.count > 1 { return result.last?.componentsFromQueryString() } return nil } } extension String { /** Convenient method for decoding a html encoded string */ func decodingURLFormat() -> String { let result = self.replacingOccurrences(of: "+", with:" ") return result.removingPercentEncoding! } /** Parses a query string @return key value dictionary with each parameter as an array */ func componentsFromQueryString() -> [String: Any] { var parameters = [String: Any]() for keyValue in components(separatedBy: "&") { let keyValueArray = keyValue.components(separatedBy: "=") if keyValueArray.count < 2 { continue } let key = keyValueArray[0].decodingURLFormat() let value = keyValueArray[1].decodingURLFormat() parameters[key] = value } return parameters } } extension URL { var youtubeID: String? { let pathComponents = self.pathComponents guard let host = self.host else { return nil } let absoluteString = self.absoluteString if host == "youtu.be" && pathComponents.count > 1 { return pathComponents[1] } else if absoluteString.range(of: "www.youtube.com/embed") != nil && pathComponents.count > 2 { return pathComponents[2] } else if (host == "youtube.googleapis.com" || self.pathComponents.first == "www.youtube.com") && pathComponents.count > 2 { return pathComponents[2] } return self.query?.componentsFromQueryString()["v"] as? String } } public class YoutubeKit { static let infoURL = "http://www.youtube.com/get_video_info?video_id=" static var userAgent = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_2) AppleWebKit/537.4 (KHTML, like Gecko) Chrome/22.0.1229.79 Safari/537.4" /** Method for retrieving the youtube ID from a youtube URL @param youtubeURL the the complete youtube video url, either youtu.be or youtube.com @return string with desired youtube id */ public static func getYoutubeID(fromURL youtubeURL: URL) -> String? { return youtubeURL.youtubeID } /** Method for retreiving a iOS supported video link @param youtubeURL the the complete youtube video url @return dictionary with the available formats for the selected video */ private static func getVideo(withYoutubeID youtubeID: String) -> [String: Any]? { let urlString = "\(self.infoURL)\(youtubeID)" guard let url = URL(string: urlString) else { return nil } var request = URLRequest(url: url) request.timeoutInterval = 5.0 request.setValue(self.userAgent, forHTTPHeaderField: "User-Agent") request.httpMethod = "GET" var responseData: Data? let session = URLSession(configuration: URLSessionConfiguration.default) let group = DispatchGroup() group.enter() session.dataTask(with: request, completionHandler: { (data, _, _) -> Void in responseData = data group.leave() }).resume() _ = group.wait(timeout: DispatchTime.distantFuture) return self.handleVideoData(responseData) } private static func handleVideoData(_ data: Data?) -> [String: Any]? { guard let data = data, let responseString = String(data: data, encoding: .utf8) else { return nil } let parts = responseString.componentsFromQueryString() if parts.count <= 0 { return nil } let videoTitle: String = parts["title"] as? String ?? "" guard let fmtStreamMap = parts["url_encoded_fmt_stream_map"] as? String else { return nil } // Live Stream if let _ = parts["live_playback"] { if let hlsvp = parts["hlsvp"] as? String { return [ "url": "\(hlsvp)", "title": "\(videoTitle)", "image": "\(parts["iurl"] as? String ?? "")", "isStream": true ] } } else { let fmtStreamMapArray = fmtStreamMap.components(separatedBy: ",") var video: [String: Any] = [ "title": videoTitle, "isStream": false ] let urls: [[String: Any]] = fmtStreamMapArray.compactMap { (str) -> [String: Any]? in return str.componentsFromQueryString() } video["urls"] = urls return video } return nil } /** Block based method for retreiving a iOS supported video link @param url the the complete youtube video url @param completeBlock the block which is called on completion */ public static func getVideo(withURL url: URL, completion: ((_ videoInfo: [String: Any]?, _ error: Error?) -> Void)?) { DispatchQueue(label: "get_video_youtube_queue").async { if let youtubeID = self.getYoutubeID(fromURL: url), let videoInfo = self.getVideo(withYoutubeID: youtubeID) { DispatchQueue.main.async { completion?(videoInfo, nil) } } else { DispatchQueue.main.async { completion?(nil, NSError(domain: "com.player.youtube.backgroundqueue", code: 1001, userInfo: ["error": "Invalid YouTube URL"])) } } } } }
35.6875
147
0.583665
914d1d1ca5cb2d8c10fe79610cfe20b6a07835a4
752
import XCTest import LXFProtocolTool class Tests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // This is an example of a functional test case. XCTAssert(true, "Pass") } func testPerformanceExample() { // This is an example of a performance test case. self.measure() { // Put the code you want to measure the time of here. } } }
25.931034
111
0.603723
91070313da11d154178722135bb35080c2963f06
1,100
// Kevin Li - 5:07 PM - 6/25/20 import SwiftUI struct LightDarkThemePreview<Preview: View>: View { let preview: Preview var body: some View { Group { LightThemePreview { self.preview } DarkThemePreview { self.preview } } } init(@ViewBuilder preview: @escaping () -> Preview) { self.preview = preview() } } struct LightThemePreview<Preview: View>: View { let preview: Preview var body: some View { preview .previewLayout(.sizeThatFits) .colorScheme(.light) } init(@ViewBuilder preview: @escaping () -> Preview) { self.preview = preview() } } struct DarkThemePreview<Preview: View>: View { let preview: Preview var body: some View { preview .previewLayout(.sizeThatFits) .colorScheme(.dark) .background(Color.black.edgesIgnoringSafeArea(.all)) } init(@ViewBuilder preview: @escaping () -> Preview) { self.preview = preview() } }
18.644068
64
0.551818
e4ab993ba152efaacc546eb1af9c11a68b20d376
1,410
// // AppDelegate.swift // swift-sdui // // Created by Jiabin Geng on 10/1/20. // Copyright © 2020 Adobe. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. return true } // MARK: UISceneSession Lifecycle func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration { // Called when a new scene session is being created. // Use this method to select a configuration to create the new scene with. return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role) } func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) { // Called when the user discards a scene session. // If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions. // Use this method to release any resources that were specific to the discarded scenes, as they will not return. } }
37.105263
179
0.746099
289032f35510592c8d390a545bc528b0e9b6619a
425
import Foundation extension Dictionary where Key == AnyHashable { func safeValueWith(keyPath: String) -> Any? { var object: Any? = self var keys = keyPath.split(separator: ".").map(String.init) while keys.count > 0, let currentObject = object { let key = keys.remove(at: 0) object = (currentObject as? NSDictionary)?[key] as Any? } return object } }
26.5625
67
0.595294
612615c695cab9cc8ceac14d9317310e68c19663
2,310
//// SYMKRemainingTimeInfobarItem.swift // // Copyright (c) 2019 - Sygic a.s. // // 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 SygicUIKit /// Item for infobar controller showing time to the end of route public class SYMKRemainingTimeInfobarItem: SYMKInfobarItem { public var type: SYMKInfobarItemType = .remainingTime(0) public let view: UIView = SYUIInfobarLabel() public func update(with valueType: SYMKInfobarItemType) { switch valueType { case .remainingTime(let time): type = valueType guard let label = view as? SYUIInfobarLabel else { return } label.text = formattedValue(time) default: break } } private func formattedValue(_ remainingTime: TimeInterval?) -> String { if let time = remainingTime { if time < 60 { return "\(time)\(LS("sec"))" } else if time < 60*60 { return String(format: "%i%@", Int(time/60), LS("min")) } else { let min = Float(time).truncatingRemainder(dividingBy: 60*60) return String(format: "%i%@%i%@", Int(time/60/60), LS("h"), Int(min/60), LS("min")) } } return "" } }
40.526316
99
0.664502
f7a3316588d5e03df4da031a91e415507f34eb12
32,028
//===----------------------------------------------------------------------===// // // This source file is part of the Swift Distributed Actors open source project // // Copyright (c) 2018-2019 Apple Inc. and the Swift Distributed Actors project authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information // See CONTRIBUTORS.md for the list of Swift Distributed Actors project authors // // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// import Foundation // ==== ---------------------------------------------------------------------------------------------------------------- // MARK: Cluster Membership public extension Cluster { /// `Membership` represents the set of members of this cluster. /// /// Membership changes are driven by nodes joining and leaving the cluster. /// Leaving the cluster may be graceful or triggered by a `FailureDetector`. /// /// ### Replacement (Unique)Nodes /// A node (or member) is referred to as a "replacement" if it shares _the same_ protocol+host+address (i.e. `Node`), /// with another member; It MAY join "over" an existing node and will immediately cause the previous node to be marked `MemberStatus.down` /// upon such transition. Such situations can take place when an actor system node is killed and started on the same host+port immediately, /// and attempts to connect to the same cluster as its previous "incarnation". Such situation is called a replacement, and by the assumption /// of that it should not be possible to run many nodes on exact same host+port the previous node is immediately ejected and marked down. /// /// ### Member state transitions /// Members can only move "forward" along their status lifecycle, refer to `Cluster.MemberStatus` docs for a diagram of legal transitions. struct Membership: ExpressibleByArrayLiteral { public typealias ArrayLiteralElement = Cluster.Member public static var empty: Cluster.Membership { .init(members: []) } /// Members MUST be stored `UniqueNode` rather than plain node, since there may exist "replacements" which we need /// to track gracefully -- in order to tell all other nodes that those nodes are now down/leaving/removed, if a /// node took their place. This makes lookup by `Node` not nice, but realistically, that lookup is quite rare -- only /// when operator issued moves are induced e.g. "> down 1.1.1.1:3333", since operators do not care about `NodeID` most of the time. internal var _members: [UniqueNode: Cluster.Member] public init(members: [Cluster.Member]) { self._members = Dictionary(minimumCapacity: members.count) for member in members { self._members[member.uniqueNode] = member } } public init(arrayLiteral members: Cluster.Member...) { self.init(members: members) } // ==== ------------------------------------------------------------------------------------------------------------ // MARK: Members /// Retrieves a `Member` by its `UniqueNode`. /// /// This operation is guaranteed to return a member if it was added to the membership UNLESS the member has been `.removed` /// and dropped which happens only after an extended period of time. // FIXME: That period of time is not implemented public func uniqueMember(_ node: UniqueNode) -> Cluster.Member? { self._members[node] } /// Picks "first", in terms of least progressed among its lifecycle member in presence of potentially multiple members /// for a non-unique `Node`. In practice, this happens when an existing node is superseded by a "replacement", and the /// previous node becomes immediately down. public func member(_ node: Node) -> Cluster.Member? { self._members.values.sorted(by: Cluster.MemberStatus.lifecycleOrdering).first(where: { $0.uniqueNode.node == node }) } public func youngestMember() -> Cluster.Member? { self.members(atLeast: .joining).max(by: Cluster.Member.ageOrdering) } public func oldestMember() -> Cluster.Member? { self.members(atLeast: .joining).min(by: Cluster.Member.ageOrdering) } /// Count of all members (regardless of their `MemberStatus`) public var count: Int { self._members.count } /// More efficient than using `members(atLeast:)` followed by a `.count` public func count(atLeast status: Cluster.MemberStatus) -> Int { self._members.values .lazy .filter { member in status <= member.status } .count } /// More efficient than using `members(withStatus:)` followed by a `.count` public func count(withStatus status: Cluster.MemberStatus) -> Int { self._members.values .lazy .filter { member in status == member.status } .count } /// Returns all members that are part of this membership, and have the exact `status` and `reachability` status. /// /// /// - Parameters: /// - statuses: statuses for which to check the members for /// - reachability: optional reachability that is the members will be filtered by /// - Returns: array of members matching those checks. Can be empty. public func members(withStatus status: Cluster.MemberStatus, reachability: Cluster.MemberReachability? = nil) -> [Cluster.Member] { self.members(withStatus: [status], reachability: reachability) } /// Returns all members that are part of this membership, and have the any ``Cluster.MemberStatus`` that is part /// of the `statuses` passed in and `reachability` status. /// /// - Parameters: /// - statuses: statuses for which to check the members for /// - reachability: optional reachability that is the members will be filtered by /// - Returns: array of members matching those checks. Can be empty. public func members(withStatus statuses: Set<Cluster.MemberStatus>, reachability: Cluster.MemberReachability? = nil) -> [Cluster.Member] { let reachabilityFilter: (Cluster.Member) -> Bool = { member in reachability == nil || member.reachability == reachability } return self._members.values.filter { statuses.contains($0.status) && reachabilityFilter($0) } } public func members(atLeast status: Cluster.MemberStatus, reachability: Cluster.MemberReachability? = nil) -> [Cluster.Member] { if status == .joining, reachability == nil { return Array(self._members.values) } let reachabilityFilter: (Cluster.Member) -> Bool = { member in reachability == nil || member.reachability == reachability } return self._members.values.filter { status <= $0.status && reachabilityFilter($0) } } public func members(atMost status: Cluster.MemberStatus, reachability: Cluster.MemberReachability? = nil) -> [Cluster.Member] { if status == .removed, reachability == nil { return Array(self._members.values) } let reachabilityFilter: (Cluster.Member) -> Bool = { member in reachability == nil || member.reachability == reachability } return self._members.values.filter { $0.status <= status && reachabilityFilter($0) } } /// Find specific member, identified by its unique node identity. public func member(byUniqueNodeID nid: UniqueNode.ID) -> Cluster.Member? { // TODO: make this O(1) by allowing wrapper type to equality check only on NodeID self._members.first(where: { $0.key.nid == nid })?.value } // ==== ------------------------------------------------------------------------------------------------------------ // MARK: Leaders /// ## Leaders /// A leader is a specific `Member` which was selected to fulfil the leadership role for the time being. /// A leader returning a non-nil value, guarantees that the same Member existing as part of this `Membership` as well (non-members cannot be leaders). /// /// Clustering offered by this project does not really designate any "special" nodes; yet sometimes a leader may be useful to make decisions more efficient or centralized. /// Leaders may be selected using various strategies, the most simple one being sorting members by their addresses and picking the "lowest". /// /// ### Leaders in partitions /// There CAN be multiple leaders in the same cluster, in face of cluster partitions, /// where certain parts of the cluster mark other groups as unreachable. /// /// Certain actions can only be performed by the "leader" of a group. public internal(set) var leader: Cluster.Member? { get { self._leaderNode.flatMap { self.uniqueMember($0) } } set { self._leaderNode = newValue?.uniqueNode } } internal var _leaderNode: UniqueNode? /// Returns a copy of the membership, though without any leaders assigned. public var leaderless: Cluster.Membership { var l = self l.leader = nil return l } /// Checks if passed in node is the leader (given the current view of the cluster state by this Membership). // TODO: this could take into account roles, if we do them public func isLeader(_ node: UniqueNode) -> Bool { self.leader?.uniqueNode == node } /// Checks if passed in node is the leader (given the current view of the cluster state by this Membership). public func isLeader(_ member: Cluster.Member) -> Bool { self.isLeader(member.uniqueNode) } /// Checks if the membership contains a member representing this ``UniqueNode``. func contains(_ uniqueNode: UniqueNode) -> Bool { self._members[uniqueNode] != nil } } } // Implementation notes: Membership/Member equality // Membership equality is special, as it manually DOES take into account the Member's states (status, reachability), // whilst the Member equality by itself does not. This is somewhat ugly, however it allows us to perform automatic // seen table owner version updates whenever "the membership has changed." We may want to move away from this and make // these explicit methods, though for now this seems to be the equality we always want when we use Membership, and the // one we want when we compare members -- as we want to know "does a thing contain this member" rather than "does a thing // contain this full exact state of a member," whereas for Membership we want to know "is the state of the membership exactly the same." extension Cluster.Membership: Hashable { public func hash(into hasher: inout Hasher) { hasher.combine(self._leaderNode) for member in self._members.values { hasher.combine(member.uniqueNode) hasher.combine(member.status) hasher.combine(member.reachability) } } public static func == (lhs: Cluster.Membership, rhs: Cluster.Membership) -> Bool { guard lhs._leaderNode == rhs._leaderNode else { return false } guard lhs._members.count == rhs._members.count else { return false } for (lNode, lMember) in lhs._members { if let rMember = rhs._members[lNode], lMember.uniqueNode != rMember.uniqueNode || lMember.status != rMember.status || lMember.reachability != rMember.reachability { return false } } return true } } extension Cluster.Membership: CustomStringConvertible, CustomDebugStringConvertible, CustomPrettyStringConvertible { /// Pretty multi-line output of a membership, useful for manual inspection public var prettyDescription: String { var res = "leader: \(self.leader, orElse: ".none")" for member in self._members.values.sorted(by: { $0.uniqueNode.node.port < $1.uniqueNode.node.port }) { res += "\n \(reflecting: member.uniqueNode) status [\(member.status.rawValue, leftPadTo: Cluster.MemberStatus.maxStrLen)]" } return res } public var description: String { "Membership(count: \(self.count), leader: \(self.leader, orElse: ".none"), members: \(self._members.values))" } public var debugDescription: String { "Membership(count: \(self.count), leader: \(self.leader, orElse: ".none"), members: \(self._members.values))" } } extension Cluster.Membership: Codable { // Codable: synthesized conformance } // ==== ---------------------------------------------------------------------------------------------------------------- // MARK: Cluster.Membership operations, such as joining, leaving, removing public extension Cluster.Membership { /// Interpret and apply passed in membership change as the appropriate join/leave/down action. /// /// Applying a new node status that becomes a "replacement" of an existing member, returns a `Cluster.MembershipChange` that is a "replacement". /// /// - Returns: the resulting change that was applied to the membership; note that this may be `nil`, /// if the change did not cause any actual change to the membership state (e.g. signaling a join of the same node twice). mutating func applyMembershipChange(_ change: Cluster.MembershipChange) -> Cluster.MembershipChange? { if case .removed = change.status { return self.removeCompletely(change.node) } if let knownUnique = self.uniqueMember(change.node) { // it is known uniquely, so we just update its status return self.mark(knownUnique.uniqueNode, as: change.status) } if change.isAtLeast(.leaving) { // if the *specific node* is not part of membership yet, and we're performing an leaving/down/removal, // there is nothing else to be done here; a replacement potentially already exists, and we should not modify it. return nil } if let previousMember = self.member(change.node.node) { // we are joining "over" an existing incarnation of a node; causing the existing node to become .down immediately _ = self.removeCompletely(previousMember.uniqueNode) // the replacement event will handle the down notifications self._members[change.node] = change.member // emit a replacement membership change, this will cause down cluster events for previous member return .init(replaced: previousMember, by: change.member) } else { // node is normally joining self._members[change.member.uniqueNode] = change.member return change } } /// Applies a leadership change, marking the new leader the passed in member. /// /// If the change causes no change in leadership (e.g. the passed in `leader` already is the `self.leader`), /// this function will return `nil`. It is guaranteed that if a non-nil value is returned, the old leader is different from the new leader. /// /// - Throws: `Cluster.MembershipError` when attempt is made to mark a non-member as leader. First add the leader as member, then promote it. mutating func applyLeadershipChange(to leader: Cluster.Member?) throws -> Cluster.LeadershipChange? { guard let wannabeLeader = leader else { if let oldLeader = self.leader { // no more leader self.leader = nil return Cluster.LeadershipChange(oldLeader: oldLeader, newLeader: self.leader) } else { // old leader was nil, and new one as well: no change return nil } } // for single node "cluster" we allow becoming the leader myself eagerly (e.g. useful in testing) if self._members.count == 0 { _ = self.join(wannabeLeader.uniqueNode) } // we soundness check that the wanna-be leader is already a member guard self._members[wannabeLeader.uniqueNode] != nil else { throw Cluster.MembershipError.nonMemberLeaderSelected(self, wannabeLeader: wannabeLeader) } if self.leader == wannabeLeader { return nil // no change was made } else { // in other cases, nil or not, we change the leader let oldLeader = self.leader self.leader = wannabeLeader return Cluster.LeadershipChange(oldLeader: oldLeader, newLeader: wannabeLeader) } } /// Alias for `applyLeadershipChange(to:)` mutating func applyLeadershipChange(_ change: Cluster.LeadershipChange?) throws -> Cluster.LeadershipChange? { try self.applyLeadershipChange(to: change?.newLeader) } /// - Returns: the changed member if the change was a transition (unreachable -> reachable, or back), /// or `nil` if the reachability is the same as already known by the membership. mutating func applyReachabilityChange(_ change: Cluster.ReachabilityChange) -> Cluster.Member? { self.mark(change.member.uniqueNode, reachability: change.member.reachability) } /// Returns the change; e.g. if we replaced a node the change `from` will be populated and perhaps a connection should /// be closed to that now-replaced node, since we have replaced it with a new node. mutating func join(_ node: UniqueNode) -> Cluster.MembershipChange? { var change = Cluster.MembershipChange(member: Cluster.Member(node: node, status: .joining)) change.previousStatus = nil return self.applyMembershipChange(change) } func joining(_ node: UniqueNode) -> Cluster.Membership { var membership = self _ = membership.join(node) return membership } /// Marks the `Cluster.Member` identified by the `node` with the `status`. /// /// Handles replacement nodes properly, by emitting a "replacement" change, and marking the replaced node as `MemberStatus.down`. /// /// If the membership not aware of this address the update is treated as a no-op. mutating func mark(_ node: UniqueNode, as status: Cluster.MemberStatus) -> Cluster.MembershipChange? { if let existingExactMember = self.uniqueMember(node) { guard existingExactMember.status < status else { // this would be a "move backwards" which we do not do; membership only moves forward return nil } var updatedMember = existingExactMember updatedMember.status = status if status == .up { updatedMember._upNumber = self.youngestMember()?._upNumber ?? 1 } self._members[existingExactMember.uniqueNode] = updatedMember return Cluster.MembershipChange(member: existingExactMember, toStatus: status) } else if let beingReplacedMember = self.member(node.node) { // We did not get a member by exact UniqueNode match, but we got one by Node match... // this means this new node that we are trying to mark is a "replacement" and the `beingReplacedNode` must be .downed! // We do not check the "only move forward rule" as this is a NEW node, and is replacing // the current one, whichever phase it was in -- perhaps it was .up, and we're replacing it with a .joining one. // This still means that the current `.up` one is very likely down already just that we have not noticed _yet_. // replacement: let replacedNode = Cluster.Member(node: beingReplacedMember.uniqueNode, status: .down) let nodeD = Cluster.Member(node: node, status: status) self._members[replacedNode.uniqueNode] = replacedNode self._members[nodeD.uniqueNode] = nodeD return Cluster.MembershipChange(replaced: beingReplacedMember, by: nodeD) } else { // no such member -> no change applied return nil } } /// Returns new membership while marking an existing member with the specified status. /// /// If the membership not aware of this node the update is treated as a no-op. func marking(_ node: UniqueNode, as status: Cluster.MemberStatus) -> Cluster.Membership { var membership = self _ = membership.mark(node, as: status) return membership } /// Mark node with passed in `reachability` /// /// - Returns: the changed member if the reachability was different than the previously stored one. mutating func mark(_ node: UniqueNode, reachability: Cluster.MemberReachability) -> Cluster.Member? { guard var member = self._members.removeValue(forKey: node) else { // no such member return nil } if member.reachability == reachability { // no change self._members[node] = member return nil } else { // change reachability and return it member.reachability = reachability self._members[node] = member return member } } /// REMOVES (as in, completely, without leaving even a tombstone or `.down` marker) a `Member` from the `Membership`. /// If the membership is not aware of this member this is treated as no-op. /// /// - Warning: When removing nodes from cluster one MUST also prune the seen tables (!) of the gossip. /// Rather than calling this function directly, invoke `Cluster.Gossip.removeMember()` which performs all needed cleanups. mutating func removeCompletely(_ node: UniqueNode) -> Cluster.MembershipChange? { if let member = self._members[node] { self._members.removeValue(forKey: node) return .init(member: member, toStatus: .removed) } else { return nil // no member to remove } } /// Returns new membership while removing an existing member, identified by the passed in node. func removingCompletely(_ node: UniqueNode) -> Cluster.Membership { var membership = self _ = membership.removeCompletely(node) return membership } } public extension Cluster.Membership { /// Special merge function that only moves members "forward" however never removes them, as removal MUST ONLY be /// issued specifically by a leader working on the assumption that the `incoming` Membership is KNOWN to be "ahead", /// and e.g. if any nodes are NOT present in the incoming membership, they shall be considered `.removed`. /// /// Otherwise, functions as a normal merge, by moving all members "forward" in their respective lifecycles. /// /// The following table illustrates the possible state transitions of a node during a merge: /// /// ``` /// node's status | "ahead" node's status | resulting node's status /// ---------------+--------------------------------------|------------------------- /// <none> --> [.joining, .up, .leaving] --> <ahead status> /// <none> --> [.down, .removed] --> <none> /// [.joining] --> [.joining, .up, .leaving, .down] --> <ahead status> /// [.up] --> [.up, .leaving, .down] --> <ahead status> /// [.leaving] --> [.leaving, .down] --> <ahead status> /// [.down] --> [.down] --> <ahead status> /// [.down] --> <none> (if some node removed) --> <none> /// [.down] --> <none> (iff myself node removed) --> .removed /// <any status> --> [.removed]** --> <none> /// /// * `.removed` is never stored EXCEPT if the `myself` member has been seen removed by other members of the cluster. /// ** `.removed` should never be gossiped/incoming within the cluster, but if it were to happen it is treated like a removal. /// /// Warning: Leaders are not "merged", they get elected by each node (!). /// /// - Returns: any membership changes that occurred (and have affected the current membership). mutating func mergeFrom(incoming: Cluster.Membership, myself: UniqueNode?) -> [Cluster.MembershipChange] { var changes: [Cluster.MembershipChange] = [] // Set of nodes whose members are currently .down, and not present in the incoming gossip. // // as we apply incoming member statuses, remove members from this set // if any remain in the set, it means they were removed in the incoming membership // since we strongly assume the incoming one is "ahead" (i.e. `self happenedBefore ahead`), // we remove these members and emit .removed changes. var downNodesToRemove: Set<UniqueNode> = Set(self.members(withStatus: .down).map(\.uniqueNode)) // 1) move forward any existing members or new members according to the `ahead` statuses for incomingMember in incoming._members.values { downNodesToRemove.remove(incomingMember.uniqueNode) guard var knownMember = self._members[incomingMember.uniqueNode] else { // member NOT known locally ---------------------------------------------------------------------------- // only proceed if the member isn't already on its way out guard incomingMember.status < Cluster.MemberStatus.down else { // no need to do anything if it is a removal coming in, yet we already do not know this node continue } // it is information about a new member, merge it in self._members[incomingMember.uniqueNode] = incomingMember var change = Cluster.MembershipChange(member: incomingMember) change.previousStatus = nil // since "new" changes.append(change) continue } // it is a known member ------------------------------------------------------------------------------------ if let change = knownMember.moveForward(to: incomingMember.status) { if change.status.isRemoved { self._members.removeValue(forKey: incomingMember.uniqueNode) } else { self._members[incomingMember.uniqueNode] = knownMember } changes.append(change) } } // 2) if any nodes we know about locally, were not included in the `ahead` membership changes.append( contentsOf: downNodesToRemove.compactMap { nodeToRemove in if nodeToRemove == myself { // we do NOT remove ourselves completely from our own membership, we remain .removed however return self.mark(nodeToRemove, as: .removed) } else { // This is safe since we KNOW the node used to be .down before, // and removals are only performed on convergent cluster state. // Thus all members in the cluster have seen the node as down, or already removed it. // Removal also causes the unique node to be tombstoned in cluster and connections severed, // such that it shall never be contacted again. // // Even if received "old" concurrent gossips with the node still present, we know it would be at-least // down, and thus we'd NOT add it to the membership again, due to the `<none> + .down = .<none>` merge rule. return self.removeCompletely(nodeToRemove) } } ) return changes } } // ==== ---------------------------------------------------------------------------------------------------------------- // MARK: Applying Cluster.Event to Membership public extension Cluster.Membership { /// Applies any kind of `Cluster.Event` to the `Membership`, modifying it appropriately. /// This apply does not yield detailed information back about the type of change performed, /// and is useful as a catch-all to keep a `Membership` copy up-to-date, but without reacting on any specific transition. /// /// - SeeAlso: `apply(_:)`, `applyLeadershipChange(to:)`, `applyReachabilityChange(_:)` to receive specific diffs reporting about the effect /// a change had on the membership. mutating func apply(event: Cluster.Event) throws { switch event { case .snapshot(let snapshot): self = snapshot case .membershipChange(let change): _ = self.applyMembershipChange(change) case .leadershipChange(let change): _ = try self.applyLeadershipChange(to: change.newLeader) case .reachabilityChange(let change): _ = self.applyReachabilityChange(change) } } } // ==== ---------------------------------------------------------------------------------------------------------------- // MARK: Cluster.Membership diffing, allowing to notice and react to changes between two membership observations extension Cluster.Membership { /// Compute a diff between two membership states. // TODO: diffing is not super well tested, may lose up numbers static func _diff(from: Cluster.Membership, to: Cluster.Membership) -> MembershipDiff { var entries: [Cluster.MembershipChange] = [] entries.reserveCapacity(max(from._members.count, to._members.count)) // TODO: can likely be optimized more var to = to // iterate over the original member set, and remove from the `to` set any seen members for member in from._members.values { if let toMember = to.uniqueMember(member.uniqueNode) { to._members.removeValue(forKey: member.uniqueNode) if member.status != toMember.status { entries.append(.init(member: member, toStatus: toMember.status)) } } else { // member is not present `to`, thus it was removed entries.append(.init(member: member, toStatus: .removed)) } } // any remaining `to` members, are new members for member in to._members.values { entries.append(.init(node: member.uniqueNode, previousStatus: nil, toStatus: member.status)) } return MembershipDiff(changes: entries) } } // TODO: maybe conform to Sequence? internal struct MembershipDiff { var changes: [Cluster.MembershipChange] = [] } extension MembershipDiff: CustomDebugStringConvertible { var debugDescription: String { var s = "MembershipDiff(\n" for entry in self.changes { s += " \(String(reflecting: entry))\n" } s += ")" return s } } // ==== ---------------------------------------------------------------------------------------------------------------- // MARK: Errors public extension Cluster { enum MembershipError: Error { case nonMemberLeaderSelected(Cluster.Membership, wannabeLeader: Cluster.Member) } }
48.972477
179
0.608405
1e1853f36b63ecadd67bba190ac210ee64577fdb
35,212
// // UIFont+Extension.swift // Copyright (c) 2019 Leonardo Modro // // 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 public extension UIFont { /// Create a UIFont object with a `Fonts` enum convenience init?(font: Fonts, size: CGFloat) { let fontIdentifier: String = font.rawValue self.init(name: fontIdentifier, size: size) } //MARK: - class func academyEngravedLetPlain(ofSize size: CGFloat) -> UIFont? { return UIFont(name: "AcademyEngravedLetPlain", size: size) } class func alNileBold(ofSize size: CGFloat) -> UIFont? { return UIFont(name: "AlNile-Bold", size: size) } class func alNile(ofSize size: CGFloat) -> UIFont? { return UIFont(name: "AlNile", size: size) } class func americanTypewriter(ofSize size: CGFloat) -> UIFont? { return UIFont(name: "AmericanTypewriter", size: size) } class func americanTypewriterBold(ofSize size: CGFloat) -> UIFont? { return UIFont(name: "AmericanTypewriter-Bold", size: size) } class func americanTypewriterCondesend(ofSize size: CGFloat) -> UIFont? { return UIFont(name: "AmericanTypewriter-Condensed", size: size) } class func americanTypewriterCondensedBold(ofSize size: CGFloat) -> UIFont? { return UIFont(name: "AmericanTypewriter-CondensedBold", size: size) } class func americanTypewriterCondensedLight(ofSize size: CGFloat) -> UIFont? { return UIFont(name: "AmericanTypewriter-CondensedLight", size: size) } class func americanTypewriterLight(ofSize size: CGFloat) -> UIFont? { return UIFont(name: "AmericanTypewriter-Light", size: size) } class func americanTypewriterSemibold(ofSize size: CGFloat) -> UIFont? { return UIFont(name: "AmericanTypewriter-Semibold", size: size) } class func appleColorEmoji(ofSize size: CGFloat) -> UIFont? { return UIFont(name: "AppleColorEmoji", size: size) } class func appleSDGothicNeoThin(ofSize size: CGFloat) -> UIFont? { return UIFont(name: "AppleSDGothicNeo-Thin", size: size) } class func appleSDGothicNeoUltraLight(ofSize size: CGFloat) -> UIFont? { return UIFont(name: "AppleSDGothicNeo-UltraLight", size: size) } class func appleSDGothicNeoLight(ofSize size: CGFloat) -> UIFont? { return UIFont(name: "AppleSDGothicNeo-Light", size: size) } class func appleSDGothicNeoRegular(ofSize size: CGFloat) -> UIFont? { return UIFont(name: "AppleSDGothicNeo-Regular", size: size) } class func appleSDGothicNeoMedium(ofSize size: CGFloat) -> UIFont? { return UIFont(name: "AppleSDGothicNeo-Medium", size: size) } class func appleSDGothicNeoSemiBold(ofSize size: CGFloat) -> UIFont? { return UIFont(name: "AppleSDGothicNeo-SemiBold", size: size) } class func appleSDGothicNeoBold(ofSize size: CGFloat) -> UIFont? { return UIFont(name: "AppleSDGothicNeo-Bold", size: size) } class func arialMT(ofSize size: CGFloat) -> UIFont? { return UIFont(name: "ArialMT", size: size) } class func arialBoldItalicMT(ofSize size: CGFloat) -> UIFont? { return UIFont(name: "Arial-BoldItalicMT", size: size) } class func arialBoldMT(ofSize size: CGFloat) -> UIFont? { return UIFont(name: "Arial-BoldMT", size: size) } class func arialItalicMT(ofSize size: CGFloat) -> UIFont? { return UIFont(name: "Arial-ItalicMT", size: size) } class func arialHebrew(ofSize size: CGFloat) -> UIFont? { return UIFont(name: "ArialHebrew", size: size) } class func arialHebrewBold(ofSize size: CGFloat) -> UIFont? { return UIFont(name: "ArialHebrew-Bold", size: size) } class func arialHebrewLight(ofSize size: CGFloat) -> UIFont? { return UIFont(name: "ArialHebrew-Light", size: size) } class func arialRoundedMTBold(ofSize size: CGFloat) -> UIFont? { return UIFont(name: "ArialRoundedMTBold", size: size) } class func avenirBlack(ofSize size: CGFloat) -> UIFont? { return UIFont(name: "Avenir-Black", size: size) } class func avenirBlackOblique(ofSize size: CGFloat) -> UIFont? { return UIFont(name: "Avenir-BlackOblique", size: size) } class func avenirBook(ofSize size: CGFloat) -> UIFont? { return UIFont(name: "Avenir-Book", size: size) } class func avenirBookOblique(ofSize size: CGFloat) -> UIFont? { return UIFont(name: "Avenir-BookOblique", size: size) } class func avenirHeavy(ofSize size: CGFloat) -> UIFont? { return UIFont(name: "Avenir-Heavy", size: size) } class func avenirHeavyOblique(ofSize size: CGFloat) -> UIFont? { return UIFont(name: "Avenir-HeavyOblique", size: size) } class func avenirLight(ofSize size: CGFloat) -> UIFont? { return UIFont(name: "Avenir-Light", size: size) } class func avenirLightOblique(ofSize size: CGFloat) -> UIFont? { return UIFont(name: "Avenir-LightOblique", size: size) } class func avenirMedium(ofSize size: CGFloat) -> UIFont? { return UIFont(name: "Avenir-Medium", size: size) } class func avenirMediumOblique(ofSize size: CGFloat) -> UIFont? { return UIFont(name: "Avenir-MediumOblique", size: size) } class func avenirOblique(ofSize size: CGFloat) -> UIFont? { return UIFont(name: "Avenir-Oblique", size: size) } class func avenirRoman(ofSize size: CGFloat) -> UIFont? { return UIFont(name: "Avenir-Roman", size: size) } class func avenirNextBold(ofSize size: CGFloat) -> UIFont? { return UIFont(name: "AvenirNext-Bold", size: size) } class func avenirNextBoldItalic(ofSize size: CGFloat) -> UIFont? { return UIFont(name: "AvenirNext-BoldItalic", size: size) } class func avenirNextDemiBold(ofSize size: CGFloat) -> UIFont? { return UIFont(name: "AvenirNext-DemiBold", size: size) } class func avenirNextDemiBoldItalic(ofSize size: CGFloat) -> UIFont? { return UIFont(name: "AvenirNext-DemiBoldItalic", size: size) } class func avenirNextHeavy(ofSize size: CGFloat) -> UIFont? { return UIFont(name: "AvenirNext-Heavy", size: size) } class func avenirNextHeavyItalic(ofSize size: CGFloat) -> UIFont? { return UIFont(name: "AvenirNext-HeavyItalic", size: size) } class func avenirNextItalic(ofSize size: CGFloat) -> UIFont? { return UIFont(name: "AvenirNext-Italic", size: size) } class func avenirNextMedium(ofSize size: CGFloat) -> UIFont? { return UIFont(name: "AvenirNext-Medium", size: size) } class func avenirNextMediumItalic(ofSize size: CGFloat) -> UIFont? { return UIFont(name: "AvenirNext-MediumItalic", size: size) } class func avenirNextRegular(ofSize size: CGFloat) -> UIFont? { return UIFont(name: "AvenirNext-Regular", size: size) } class func avenirNextUltraLight(ofSize size: CGFloat) -> UIFont? { return UIFont(name: "AvenirNext-UltraLight", size: size) } class func avenirNextUltraLightItalic(ofSize size: CGFloat) -> UIFont? { return UIFont(name: "AvenirNext-UltraLightItalic", size: size) } class func avenirNextCondensedBold(ofSize size: CGFloat) -> UIFont? { return UIFont(name: "AvenirNextCondensed-Bold", size: size) } class func avenirNextCondensedBoldItalic(ofSize size: CGFloat) -> UIFont? { return UIFont(name: "AvenirNextCondensed-BoldItalic", size: size) } class func avenirNextCondensedDemiBold(ofSize size: CGFloat) -> UIFont? { return UIFont(name: "AvenirNextCondensed-DemiBold", size: size) } class func avenirNextCondensedDemiBoldItalic(ofSize size: CGFloat) -> UIFont? { return UIFont(name: "AvenirNextCondensed-DemiBoldItalic", size: size) } class func avenirNextCondensedHeavy(ofSize size: CGFloat) -> UIFont? { return UIFont(name: "AvenirNextCondensed-Heavy", size: size) } class func avenirNextCondensedHeavyItalic(ofSize size: CGFloat) -> UIFont? { return UIFont(name: "AvenirNextCondensed-HeavyItalic", size: size) } class func avenirNextCondensedItalic(ofSize size: CGFloat) -> UIFont? { return UIFont(name: "AvenirNextCondensed-Italic", size: size) } class func avenirNextCondensedMedium(ofSize size: CGFloat) -> UIFont? { return UIFont(name: "AvenirNextCondensed-Medium", size: size) } class func avenirNextCondensedMediumItalic(ofSize size: CGFloat) -> UIFont? { return UIFont(name: "AvenirNextCondensed-MediumItalic", size: size) } class func avenirNextCondensedRegular(ofSize size: CGFloat) -> UIFont? { return UIFont(name: "AvenirNextCondensed-Regular", size: size) } class func avenirNextCondensedUltraLight(ofSize size: CGFloat) -> UIFont? { return UIFont(name: "AvenirNextCondensed-UltraLight", size: size) } class func avenirNextCondensedUltraLightItalic(ofSize size: CGFloat) -> UIFont? { return UIFont(name: "AvenirNextCondensed-UltraLightItalic", size: size) } class func banglaSangamMN(ofSize size: CGFloat) -> UIFont? { return UIFont(name: "Bangla Sangam MN", size: size) } class func banglaSangamMNBold(ofSize size: CGFloat) -> UIFont? { return UIFont(name: "Bangla Sangam MN-Bold", size: size) } class func baskerville(ofSize size: CGFloat) -> UIFont? { return UIFont(name: "Baskerville", size: size) } class func baskervilleBold(ofSize size: CGFloat) -> UIFont? { return UIFont(name: "Baskerville-Bold", size: size) } class func baskervilleBoldItalic(ofSize size: CGFloat) -> UIFont? { return UIFont(name: "Baskerville-BoldItalic", size: size) } class func baskervilleItalic(ofSize size: CGFloat) -> UIFont? { return UIFont(name: "Baskerville-Italic", size: size) } class func baskervilleSemiBold(ofSize size: CGFloat) -> UIFont? { return UIFont(name: "Baskerville-SemiBold", size: size) } class func baskervilleSemiBoldItalic(ofSize size: CGFloat) -> UIFont? { return UIFont(name: "Baskerville-SemiBoldItalic", size: size) } class func bodoniSvtyTwoITCTTBold(ofSize size: CGFloat) -> UIFont? { return UIFont(name: "BodoniSvtyTwoITCTT-Bold", size: size) } class func bodoniSvtyTwoITCTTBook(ofSize size: CGFloat) -> UIFont? { return UIFont(name: "BodoniSvtyTwoITCTT-Book", size: size) } class func bodoniSvtyTwoITCTTBookIta(ofSize size: CGFloat) -> UIFont? { return UIFont(name: "BodoniSvtyTwoITCTT-BookIta", size: size) } class func bodoniSvtyTwoOSITCTTBold(ofSize size: CGFloat) -> UIFont? { return UIFont(name: "BodoniSvtyTwoOSITCTT-Bold", size: size) } class func bodoniSvtyTwoOSITCTTBook(ofSize size: CGFloat) -> UIFont? { return UIFont(name: "BodoniSvtyTwoOSITCTT-Book", size: size) } class func bodoniSvtyTwoOSITCTTBookIt(ofSize size: CGFloat) -> UIFont? { return UIFont(name: "BodoniSvtyTwoOSITCTT-BookIt", size: size) } class func bodoniSvtyTwoSCITCTTBook(ofSize size: CGFloat) -> UIFont? { return UIFont(name: "BodoniSvtyTwoSCITCTT-Book", size: size) } class func bodoniOrnamentsITCTT(ofSize size: CGFloat) -> UIFont? { return UIFont(name: "BodoniOrnamentsITCTT", size: size) } class func bradleyHandITCTTBold(ofSize size: CGFloat) -> UIFont? { return UIFont(name: "BradleyHandITCTT-Bold", size: size) } class func chalkboardSEBold(ofSize size: CGFloat) -> UIFont? { return UIFont(name: "ChalkboardSE-Bold", size: size) } class func chalkboardSELight(ofSize size: CGFloat) -> UIFont? { return UIFont(name: "ChalkboardSE-Light", size: size) } class func chalkboardSERegular(ofSize size: CGFloat) -> UIFont? { return UIFont(name: "ChalkboardSE-Regular", size: size) } class func chalkduster(ofSize size: CGFloat) -> UIFont? { return UIFont(name: "Chalkduster", size: size) } class func cochin(ofSize size: CGFloat) -> UIFont? { return UIFont(name: "Cochin", size: size) } class func cochinBold(ofSize size: CGFloat) -> UIFont? { return UIFont(name: "Cochin-Bold", size: size) } class func cochinBoldItalic(ofSize size: CGFloat) -> UIFont? { return UIFont(name: "Cochin-BoldItalic", size: size) } class func cochinItalic(ofSize size: CGFloat) -> UIFont? { return UIFont(name: "Cochin-Italic", size: size) } class func copperplate(ofSize size: CGFloat) -> UIFont? { return UIFont(name: "Copperplate", size: size) } class func copperplateBold(ofSize size: CGFloat) -> UIFont? { return UIFont(name: "Copperplate-Bold", size: size) } class func copperplateLight(ofSize size: CGFloat) -> UIFont? { return UIFont(name: "Copperplate-Light", size: size) } class func courier(ofSize size: CGFloat) -> UIFont? { return UIFont(name: "Courier", size: size) } class func courierBold(ofSize size: CGFloat) -> UIFont? { return UIFont(name: "Courier-Bold", size: size) } class func courierBoldOblique(ofSize size: CGFloat) -> UIFont? { return UIFont(name: "Courier-BoldOblique", size: size) } class func courierOblique(ofSize size: CGFloat) -> UIFont? { return UIFont(name: "Courier-Oblique", size: size) } class func courierNewPSMT(ofSize size: CGFloat) -> UIFont? { return UIFont(name: "CourierNewPSMT", size: size) } class func courierNewPSBoldMT(ofSize size: CGFloat) -> UIFont? { return UIFont(name: "CourierNewPS-BoldMT", size: size) } class func courierNewPSBoldItalicMT(ofSize size: CGFloat) -> UIFont? { return UIFont(name: "CourierNewPS-BoldItalicMT", size: size) } class func courierNewPSItalicMT(ofSize size: CGFloat) -> UIFont? { return UIFont(name: "CourierNewPS-ItalicMT", size: size) } class func damascus(ofSize size: CGFloat) -> UIFont? { return UIFont(name: "Damascus", size: size) } class func damascusBold(ofSize size: CGFloat) -> UIFont? { return UIFont(name: "DamascusBold", size: size) } class func damascusLight(ofSize size: CGFloat) -> UIFont? { return UIFont(name: "DamascusLight", size: size) } class func damascusMedium(ofSize size: CGFloat) -> UIFont? { return UIFont(name: "DamascusMedium", size: size) } class func damascusSemiBold(ofSize size: CGFloat) -> UIFont? { return UIFont(name: "DamascusSemiBold", size: size) } class func devanagariSangamMN(ofSize size: CGFloat) -> UIFont? { return UIFont(name: "DevanagariSangamMN", size: size) } class func devanagariSangamMNBold(ofSize size: CGFloat) -> UIFont? { return UIFont(name: "DevanagariSangamMN-Bold", size: size) } class func didot(ofSize size: CGFloat) -> UIFont? { return UIFont(name: "Didot", size: size) } class func didotBold(ofSize size: CGFloat) -> UIFont? { return UIFont(name: "Didot-Bold", size: size) } class func didotItalic(ofSize size: CGFloat) -> UIFont? { return UIFont(name: "Didot-Italic", size: size) } class func diwanMishafi(ofSize size: CGFloat) -> UIFont? { return UIFont(name: "DiwanMishafi", size: size) } class func euphemiaUCAS(ofSize size: CGFloat) -> UIFont? { return UIFont(name: "EuphemiaUCAS", size: size) } class func euphemiaUCASBold(ofSize size: CGFloat) -> UIFont? { return UIFont(name: "EuphemiaUCAS-Bold", size: size) } class func euphemiaUCASItalic(ofSize size: CGFloat) -> UIFont? { return UIFont(name: "EuphemiaUCAS-Italic", size: size) } class func farah(ofSize size: CGFloat) -> UIFont? { return UIFont(name: "Farah", size: size) } class func futuraBold(ofSize size: CGFloat) -> UIFont? { return UIFont(name: "Futura-Bold", size: size) } class func futuraCondensedExtraBold(ofSize size: CGFloat) -> UIFont? { return UIFont(name: "Futura-CondensedExtraBold", size: size) } class func futuraCondensedMedium(ofSize size: CGFloat) -> UIFont? { return UIFont(name: "Futura-CondensedMedium", size: size) } class func futuraMedium(ofSize size: CGFloat) -> UIFont? { return UIFont(name: "Futura-Medium", size: size) } class func futuraMediumItalic(ofSize size: CGFloat) -> UIFont? { return UIFont(name: "Futura-MediumItalic", size: size) } class func geezaPro(ofSize size: CGFloat) -> UIFont? { return UIFont(name: "GeezaPro", size: size) } class func geezaProBold(ofSize size: CGFloat) -> UIFont? { return UIFont(name: "GeezaPro-Bold", size: size) } class func georgia(ofSize size: CGFloat) -> UIFont? { return UIFont(name: "Georgia", size: size) } class func georgiaBold(ofSize size: CGFloat) -> UIFont? { return UIFont(name: "Georgia-Bold", size: size) } class func georgiaBoldItalic(ofSize size: CGFloat) -> UIFont? { return UIFont(name: "Georgia-BoldItalic", size: size) } class func georgiaItalic(ofSize size: CGFloat) -> UIFont? { return UIFont(name: "Georgia-Italic", size: size) } class func gillSans(ofSize size: CGFloat) -> UIFont? { return UIFont(name: "GillSans", size: size) } class func gillSansBold(ofSize size: CGFloat) -> UIFont? { return UIFont(name: "GillSans-Bold", size: size) } class func gillSansBoldItalic(ofSize size: CGFloat) -> UIFont? { return UIFont(name: "GillSans-BoldItalic", size: size) } class func gillSansItalic(ofSize size: CGFloat) -> UIFont? { return UIFont(name: "GillSans-Italic", size: size) } class func gillSansLight(ofSize size: CGFloat) -> UIFont? { return UIFont(name: "GillSans-Light", size: size) } class func gillSansLightItalic(ofSize size: CGFloat) -> UIFont? { return UIFont(name: "GillSans-LightItalic", size: size) } class func gillSansSemiBold(ofSize size: CGFloat) -> UIFont? { return UIFont(name: "GillSans-SemiBold", size: size) } class func gillSansSemiBoldItalic(ofSize size: CGFloat) -> UIFont? { return UIFont(name: "GillSans-SemiBoldItalic", size: size) } class func gillSansUltraBold(ofSize size: CGFloat) -> UIFont? { return UIFont(name: "GillSans-UltraBold", size: size) } class func gujaratiSangamMN(ofSize size: CGFloat) -> UIFont? { return UIFont(name: "GujaratiSangamMN", size: size) } class func gujaratiSangamMNBold(ofSize size: CGFloat) -> UIFont? { return UIFont(name: "GujaratiSangamMN-Bold", size: size) } class func gurmukhiMN(ofSize size: CGFloat) -> UIFont? { return UIFont(name: "GurmukhiMN", size: size) } class func gurmukhiMNBold(ofSize size: CGFloat) -> UIFont? { return UIFont(name: "GurmukhiMN-Bold", size: size) } class func helvetica(ofSize size: CGFloat) -> UIFont? { return UIFont(name: "Helvetica", size: size) } class func helveticaBold(ofSize size: CGFloat) -> UIFont? { return UIFont(name: "Helvetica-Bold", size: size) } class func helveticaBoldOblique(ofSize size: CGFloat) -> UIFont? { return UIFont(name: "Helvetica-BoldOblique", size: size) } class func helveticaLight(ofSize size: CGFloat) -> UIFont? { return UIFont(name: "Helvetica-Light", size: size) } class func helveticaLightOblique(ofSize size: CGFloat) -> UIFont? { return UIFont(name: "Helvetica-LightOblique", size: size) } class func helveticaOblique(ofSize size: CGFloat) -> UIFont? { return UIFont(name: "Helvetica-Oblique", size: size) } class func helveticaNeue(ofSize size: CGFloat) -> UIFont? { return UIFont(name: "HelveticaNeue", size: size) } class func helveticaNeueCondensedBlack(ofSize size: CGFloat) -> UIFont? { return UIFont(name: "HelveticaNeue-CondensedBlack", size: size) } class func helveticaNeueCondensedBold(ofSize size: CGFloat) -> UIFont? { return UIFont(name: "HelveticaNeue-CondensedBold", size: size) } class func helveticaNeueBold(ofSize size: CGFloat) -> UIFont? { return UIFont(name: "HelveticaNeue-Bold", size: size) } class func helveticaNeueBoldItalic(ofSize size: CGFloat) -> UIFont? { return UIFont(name: "HelveticaNeue-BoldItalic", size: size) } class func helveticaNeueItalic(ofSize size: CGFloat) -> UIFont? { return UIFont(name: "HelveticaNeue-Italic", size: size) } class func helveticaNeueLight(ofSize size: CGFloat) -> UIFont? { return UIFont(name: "HelveticaNeue-Light", size: size) } class func helveticaNeueLightItalic(ofSize size: CGFloat) -> UIFont? { return UIFont(name: "HelveticaNeue-LightItalic", size: size) } class func helveticaNeueMedium(ofSize size: CGFloat) -> UIFont? { return UIFont(name: "HelveticaNeue-Medium", size: size) } class func helveticaNeueMediumItalic(ofSize size: CGFloat) -> UIFont? { return UIFont(name: "HelveticaNeue-MediumItalic", size: size) } class func helveticaNeueThin(ofSize size: CGFloat) -> UIFont? { return UIFont(name: "HelveticaNeue-Thin", size: size) } class func helveticaNeueThinItalic(ofSize size: CGFloat) -> UIFont? { return UIFont(name: "HelveticaNeue-ThinItalic", size: size) } class func helveticaNeueUltraLight(ofSize size: CGFloat) -> UIFont? { return UIFont(name: "HelveticaNeue-UltraLight", size: size) } class func helveticaNeueUltraLightItalic(ofSize size: CGFloat) -> UIFont? { return UIFont(name: "HelveticaNeue-UltraLightItalic", size: size) } class func hiraMinProNW3(ofSize size: CGFloat) -> UIFont? { return UIFont(name: "HiraMinProN-W3", size: size) } class func hiraMinProNW6(ofSize size: CGFloat) -> UIFont? { return UIFont(name: "HiraMinProN-W6", size: size) } class func hiraginoSansW3(ofSize size: CGFloat) -> UIFont? { return UIFont(name: "HiraginoSans-W3", size: size) } class func hiraginoSansW6(ofSize size: CGFloat) -> UIFont? { return UIFont(name: "HiraginoSans-W6", size: size) } class func hoeflerTextBlack(ofSize size: CGFloat) -> UIFont? { return UIFont(name: "HoeflerText-Black", size: size) } class func hoeflerTextBlackItalic(ofSize size: CGFloat) -> UIFont? { return UIFont(name: "HoeflerText-BlackItalic", size: size) } class func hoeflerTextItalic(ofSize size: CGFloat) -> UIFont? { return UIFont(name: "HoeflerText-Italic", size: size) } class func hoeflerTextRegular(ofSize size: CGFloat) -> UIFont? { return UIFont(name: "HoeflerText-Regular", size: size) } class func kailasa(ofSize size: CGFloat) -> UIFont? { return UIFont(name: "Kailasa", size: size) } class func kailasaBold(ofSize size: CGFloat) -> UIFont? { return UIFont(name: "Kailasa-Bold", size: size) } class func kannadaSangamMN(ofSize size: CGFloat) -> UIFont? { return UIFont(name: "KannadaSangamMN", size: size) } class func kannadaSangamMNBold(ofSize size: CGFloat) -> UIFont? { return UIFont(name: "KannadaSangamMN-Bold", size: size) } class func kefaRegular(ofSize size: CGFloat) -> UIFont? { return UIFont(name: "Kefa-Regular", size: size) } class func khmerSangamMN(ofSize size: CGFloat) -> UIFont? { return UIFont(name: "KhmerSangamMN", size: size) } class func kohinoorBanglaLight(ofSize size: CGFloat) -> UIFont? { return UIFont(name: "KohinoorBangla-Light", size: size) } class func kohinoorBanglaRegular(ofSize size: CGFloat) -> UIFont? { return UIFont(name: "KohinoorBangla-Regular", size: size) } class func kohinoorBanglaSemibold(ofSize size: CGFloat) -> UIFont? { return UIFont(name: "KohinoorBangla-Semibold", size: size) } class func kohinoorDevanagariLight(ofSize size: CGFloat) -> UIFont? { return UIFont(name: "KohinoorDevanagari-Light", size: size) } class func kohinoorDevanagariRegular(ofSize size: CGFloat) -> UIFont? { return UIFont(name: "KohinoorDevanagari-Regular", size: size) } class func kohinoorDevanagariSemibold(ofSize size: CGFloat) -> UIFont? { return UIFont(name: "KohinoorDevanagari-Semibold", size: size) } class func kohinoorTeluguLight(ofSize size: CGFloat) -> UIFont? { return UIFont(name: "KohinoorTelugu-Light", size: size) } class func kohinoorTeluguMedium(ofSize size: CGFloat) -> UIFont? { return UIFont(name: "KohinoorTelugu-Medium", size: size) } class func kohinoorTeluguRegular(ofSize size: CGFloat) -> UIFont? { return UIFont(name: "KohinoorTelugu-Regular", size: size) } class func laoSangamMN(ofSize size: CGFloat) -> UIFont? { return UIFont(name: "LaoSangamMN", size: size) } class func malayalamSangamMN(ofSize size: CGFloat) -> UIFont? { return UIFont(name: "MalayalamSangamMN", size: size) } class func malayalamSangamMNBold(ofSize size: CGFloat) -> UIFont? { return UIFont(name: "MalayalamSangamMN-Bold", size: size) } class func markerFeltThin(ofSize size: CGFloat) -> UIFont? { return UIFont(name: "MarkerFelt-Thin", size: size) } class func markerFeltWide(ofSize size: CGFloat) -> UIFont? { return UIFont(name: "MarkerFelt-Wide", size: size) } class func menloBold(ofSize size: CGFloat) -> UIFont? { return UIFont(name: "Menlo-Bold", size: size) } class func menloBoldItalic(ofSize size: CGFloat) -> UIFont? { return UIFont(name: "Menlo-BoldItalic", size: size) } class func menloItalic(ofSize size: CGFloat) -> UIFont? { return UIFont(name: "Menlo-Italic", size: size) } class func menloRegular(ofSize size: CGFloat) -> UIFont? { return UIFont(name: "Menlo-Regular", size: size) } class func noteworthyBold(ofSize size: CGFloat) -> UIFont? { return UIFont(name: "Noteworthy-Bold", size: size) } class func noteworthyLight(ofSize size: CGFloat) -> UIFont? { return UIFont(name: "Noteworthy-Light", size: size) } class func optimaBold(ofSize size: CGFloat) -> UIFont? { return UIFont(name: "Optima-Bold", size: size) } class func optimaBoldItalic(ofSize size: CGFloat) -> UIFont? { return UIFont(name: "Optima-BoldItalic", size: size) } class func optimaExtraBlack(ofSize size: CGFloat) -> UIFont? { return UIFont(name: "Optima-ExtraBlack", size: size) } class func optimaItalic(ofSize size: CGFloat) -> UIFont? { return UIFont(name: "Optima-Italic", size: size) } class func optimaRegular(ofSize size: CGFloat) -> UIFont? { return UIFont(name: "Optima-Regular", size: size) } class func oriyaSangamMN(ofSize size: CGFloat) -> UIFont? { return UIFont(name: "OriyaSangamMN", size: size) } class func oriyaSangamMNBold(ofSize size: CGFloat) -> UIFont? { return UIFont(name: "OriyaSangamMN-Bold", size: size) } class func palatinoBold(ofSize size: CGFloat) -> UIFont? { return UIFont(name: "Palatino-Bold", size: size) } class func palatinoBoldItalic(ofSize size: CGFloat) -> UIFont? { return UIFont(name: "Palatino-BoldItalic", size: size) } class func palatinoItalic(ofSize size: CGFloat) -> UIFont? { return UIFont(name: "Palatino-Italic", size: size) } class func palatinoRoman(ofSize size: CGFloat) -> UIFont? { return UIFont(name: "Palatino-Roman", size: size) } class func papyrus(ofSize size: CGFloat) -> UIFont? { return UIFont(name: "Papyrus", size: size) } class func papyrusCondensed(ofSize size: CGFloat) -> UIFont? { return UIFont(name: "Papyrus-Condensed", size: size) } class func partyLetPlain(ofSize size: CGFloat) -> UIFont? { return UIFont(name: "PartyLetPlain", size: size) } class func pingFangHKLight(ofSize size: CGFloat) -> UIFont? { return UIFont(name: "PingFangHK-Light", size: size) } class func pingFangHKMedium(ofSize size: CGFloat) -> UIFont? { return UIFont(name: "PingFangHK-Medium", size: size) } class func pingFangHKRegular(ofSize size: CGFloat) -> UIFont? { return UIFont(name: "PingFangHK-Regular", size: size) } class func pingFangHKSemibold(ofSize size: CGFloat) -> UIFont? { return UIFont(name: "PingFangHK-Semibold", size: size) } class func pingFangHKThin(ofSize size: CGFloat) -> UIFont? { return UIFont(name: "PingFangHK-Thin", size: size) } class func pingFangHKUltralight(ofSize size: CGFloat) -> UIFont? { return UIFont(name: "PingFangHK-Ultralight", size: size) } class func pingFangSCLight(ofSize size: CGFloat) -> UIFont? { return UIFont(name: "PingFangSC-Light", size: size) } class func pingFangSCMedium(ofSize size: CGFloat) -> UIFont? { return UIFont(name: "PingFangSC-Medium", size: size) } class func pingFangSCRegular(ofSize size: CGFloat) -> UIFont? { return UIFont(name: "PingFangSC-Regular", size: size) } class func pingFangSCSemibold(ofSize size: CGFloat) -> UIFont? { return UIFont(name: "PingFangSC-Semibold", size: size) } class func pingFangSCThin(ofSize size: CGFloat) -> UIFont? { return UIFont(name: "PingFangSC-Thin", size: size) } class func pingFangSCUltralight(ofSize size: CGFloat) -> UIFont? { return UIFont(name: "PingFangSC-Ultralight", size: size) } class func pingFangTCLight(ofSize size: CGFloat) -> UIFont? { return UIFont(name: "PingFangTC-Light", size: size) } class func pingFangTCMedium(ofSize size: CGFloat) -> UIFont? { return UIFont(name: "PingFangTC-Medium", size: size) } class func pingFangTCRegular(ofSize size: CGFloat) -> UIFont? { return UIFont(name: "PingFangTC-Regular", size: size) } class func pingFangTCSemibold(ofSize size: CGFloat) -> UIFont? { return UIFont(name: "PingFangTC-Semibold", size: size) } class func pingFangTCThin(ofSize size: CGFloat) -> UIFont? { return UIFont(name: "PingFangTC-Thin", size: size) } class func pingFangTCUltralight(ofSize size: CGFloat) -> UIFont? { return UIFont(name: "PingFangTC-Ultralight", size: size) } class func savoyeLetPlain(ofSize size: CGFloat) -> UIFont? { return UIFont(name: "SavoyeLetPlain", size: size) } class func sinhalaSangamMN(ofSize size: CGFloat) -> UIFont? { return UIFont(name: "SinhalaSangamMN", size: size) } class func sinhalaSangamMNBold(ofSize size: CGFloat) -> UIFont? { return UIFont(name: "SinhalaSangamMN-Bold", size: size) } class func snellRoundhand(ofSize size: CGFloat) -> UIFont? { return UIFont(name: "SnellRoundhand", size: size) } class func snellRoundhandBlack(ofSize size: CGFloat) -> UIFont? { return UIFont(name: "SnellRoundhand-Black", size: size) } class func snellRoundhandBold(ofSize size: CGFloat) -> UIFont? { return UIFont(name: "SnellRoundhand-Bold", size: size) } class func symbol(ofSize size: CGFloat) -> UIFont? { return UIFont(name: "Symbol", size: size) } class func tamilSangamMN(ofSize size: CGFloat) -> UIFont? { return UIFont(name: "TamilSangamMN", size: size) } class func tamilSangamMNBold(ofSize size: CGFloat) -> UIFont? { return UIFont(name: "TamilSangamMN-Bold", size: size) } class func thonburi(ofSize size: CGFloat) -> UIFont? { return UIFont(name: "Thonburi", size: size) } class func thonburiBold(ofSize size: CGFloat) -> UIFont? { return UIFont(name: "Thonburi-Bold", size: size) } class func thonburiLight(ofSize size: CGFloat) -> UIFont? { return UIFont(name: "Thonburi-Light", size: size) } class func timesNewRomanPSBoldMT(ofSize size: CGFloat) -> UIFont? { return UIFont(name: "TimesNewRomanPS-BoldMT", size: size) } class func timesNewRomanPSBoldItalicMT(ofSize size: CGFloat) -> UIFont? { return UIFont(name: "TimesNewRomanPS-BoldItalicMT", size: size) } class func timesNewRomanPSItalicMT(ofSize size: CGFloat) -> UIFont? { return UIFont(name: "TimesNewRomanPS-ItalicMT", size: size) } class func timesNewRomanPSMT(ofSize size: CGFloat) -> UIFont? { return UIFont(name: "TimesNewRomanPSMT", size: size) } class func trebuchetMS(ofSize size: CGFloat) -> UIFont? { return UIFont(name: "TrebuchetMS", size: size) } class func trebuchetMSBold(ofSize size: CGFloat) -> UIFont? { return UIFont(name: "TrebuchetMS-Bold", size: size) } class func trebuchetBoldItalic(ofSize size: CGFloat) -> UIFont? { return UIFont(name: "Trebuchet-BoldItalic", size: size) } class func trebuchetMSItalic(ofSize size: CGFloat) -> UIFont? { return UIFont(name: "TrebuchetMS-Italic", size: size) } class func verdana(ofSize size: CGFloat) -> UIFont? { return UIFont(name: "Verdana", size: size) } class func verdanaBold(ofSize size: CGFloat) -> UIFont? { return UIFont(name: "Verdana-Bold", size: size) } class func verdanaBoldItalic(ofSize size: CGFloat) -> UIFont? { return UIFont(name: "Verdana-BoldItalic", size: size) } class func verdanaItalic(ofSize size: CGFloat) -> UIFont? { return UIFont(name: "Verdana-Italic", size: size) } class func zapfDingbatsITC(ofSize size: CGFloat) -> UIFont? { return UIFont(name: "ZapfDingbatsITC", size: size) } class func zapfino(ofSize size: CGFloat) -> UIFont? { return UIFont(name: "Zapfino", size: size) } }
45.085787
85
0.665569
69b6a031ed34a4caf17565b59ccc063c22da04fa
4,714
// // AorKDemoVC.swift // ZYBase // // Created by Mzywx on 2017/2/24. // Copyright © 2017年 Mzywx. All rights reserved. // import UIKit private let url = "http://112.74.176.225/a/location/location/andriod_zy" private let animaleUrl = "http://img.qq1234.org/uploads/allimg/150709/8_150709170804_7.jpg" class UnitModel: ZYDataModel { var isNewRecord:String! var locName:String! var locAddress:String! required init(fromJson json: JSON!) { super .init(fromJson: json) isNewRecord = json["isNewRecord"].stringValue locName = json["locName"].stringValue locAddress = json["locAddress"].stringValue } } class AorKDemoVC: BaseTabVC , UITableViewDelegate , UITableViewDataSource,UIScrollViewDelegate,DZNEmptyDataSetSource,DZNEmptyDataSetDelegate{ var dataArr:Array<UnitModel> = [] lazy var unitTab:UITableView = { let tab = UITableView(frame: .zero, style: .grouped) tab.backgroundColor = .clear tab.delegate = self tab.dataSource = self tab.emptyDataSetSource = self tab.emptyDataSetDelegate = self return tab }() override func viewDidLoad() { super.viewDidLoad() self.view.addSubview(unitTab) unitTab.snp.makeConstraints { (make) in make.left.right.bottom.top.equalToSuperview() } unowned let weakSelf = self setRefresh(refreshView: unitTab, refreshType: .headerAndFooter, headerRefresh: { weakSelf.requestServes() }, footerRefresh: { weakSelf.perform(#selector(weakSelf.endFootRefresh), with: nil, afterDelay: 3) }) setSearch(searchView: unitTab, location: .tabHeader, resultVC: nil) requestServes() } func endHeadRefresh() { stopRefresh(refreshType: .header) } func endFootRefresh() { stopRefresh(refreshType: .footer) } func requestServes() { let netModel = ZYNetModel.init(para: nil, data: UnitModel.self, map: nil, urlString: url, header: nil) showProgress(title: "正在加载...", superView: self.view, hudMode: .indeterminate, delay: -1) ZYNetWork.ZYPOST(netModel: netModel, success: { (isSuccess, model) in dismissProgress() self.endHeadRefresh() let rootModel = model as! ZYRootModel let modelArr = rootModel.data as! Array<UnitModel> self.dataArr = modelArr self.unitTab.reloadData() }) { (isFail, res) in } } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return dataArr.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cellID = "cellId" var cell = tableView.dequeueReusableCell(withIdentifier: cellID) if cell==nil { cell = UITableViewCell.init(style: .subtitle, reuseIdentifier: cellID) } cell?.imageView?.kf.setImage(with: URL(string: animaleUrl), placeholder: #imageLiteral(resourceName: "moji_logo")) cell?.textLabel?.text = dataArr[indexPath.row].locName cell?.detailTextLabel?.text = dataArr[indexPath.row].locAddress return cell! } func scrollViewWillBeginDragging(_ scrollView: UIScrollView) { if let bgview = unitTab.value(forKey: "_tableHeaderBackgroundView") { (bgview as? UIView)?.backgroundColor = .clear } } //MARK: DZNEmptyDataSetDelegate /** * 返回标题文字 */ func title(forEmptyDataSet scrollView: UIScrollView) -> NSAttributedString? { let title = "暂无数据" return NSAttributedString(string: title, attributes: [NSFontAttributeName:getFont(16)]) } /** * 返回详情文字 */ func description(forEmptyDataSet scrollView: UIScrollView) -> NSAttributedString? { let description = "请稍后重试" return NSAttributedString(string: description, attributes: [NSFontAttributeName:getFont(14)]) } /** * 返回图片 */ func image(forEmptyDataSet scrollView: UIScrollView) -> UIImage? { return nil } //MARK: DZNEmptyDataSetSource func emptyDataSetShouldDisplay(_ scrollView: UIScrollView) -> Bool { return true } func emptyDataSetShouldAllowScroll(_ scrollView: UIScrollView) -> Bool { return true } func emptyDataSet(_ scrollView: UIScrollView, didTap view: UIView) { } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
31.013158
141
0.637039
4a056a8808ba78f5987dbe61d26bfa19dc5a0f88
287
// // ViewModelType.swift // Frames-App // // Created by Tyler Zhao on 11/20/18. // Copyright © 2018 Tyler Zhao. All rights reserved. // import Foundation protocol ViewModelType { associatedtype Input associatedtype Output func transform(input: Input) -> Output }
16.882353
53
0.686411
7af6c2848dde474f87fef08ea70dcd3ed76f5cb2
1,414
// // AppDelegate.swift // VCamera // // Created by VassilyChi on 2019/12/15. // Copyright © 2019 VassilyChi. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. return true } // MARK: UISceneSession Lifecycle func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration { // Called when a new scene session is being created. // Use this method to select a configuration to create the new scene with. return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role) } func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) { // Called when the user discards a scene session. // If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions. // Use this method to release any resources that were specific to the discarded scenes, as they will not return. } }
37.210526
179
0.748232
8a9a9fa8716c35a3b23502bafa151ec0cbeeb761
407
// // ProfileController.swift // SideBarMenuLikeAPro // // Created by Paolo Prodossimo Lopes on 21/09/21. // import UIKit class ProfileController: UIViewController { //MARK: - Properties: //MARK: - Lifecycle: override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = .darkGray } //MARK: - Helpers: //MARK: - Selectors: }
15.653846
50
0.599509
03630c166a70a2f3971ca607c63143504ca21666
367
// -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- // Created by Sam Deane on 10/04/2020. // All code (c) 2020 - present day, Elegant Chaos Limited. // -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- #if !os(Linux) import Logger public let applicationChannel = Channel("Application", handlers: [OSLogHandler()]) #endif
33.363636
82
0.433243
2216b8c7307a04ec6e6f8b04fd6c949487c2a603
1,259
// // String+Data.swift // HTTPRequest // // Created by Ben Shutt on 18/10/2020. // import Foundation // MARK: - StringError /// An `Error` converting from `String` to `Data` or vice versa public enum StringDataError: Error { /// Failed to create a `String` from the given `Data` and `String.Encoding` case data(Data, encoding: String.Encoding) /// Failed to create `Data` from the given `String` and `String.Encoding` case string(String, encoding: String.Encoding) } // MARK: - String + Data public extension String { /// `String` instance to `Data` or `throw` /// - Parameter encoding: `String.Encoding` func dataOrThrow(encoding: String.Encoding) throws -> Data { guard let data = data(using: encoding) else { throw StringDataError.string(self, encoding: encoding) } return data } } // MARK: - Data + String public extension Data { /// `Data` instance to `String` or `throw` /// - Parameter encoding: `String.Encoding` func stringOrThrow(encoding: String.Encoding) throws -> String { guard let string = String(data: self, encoding: encoding) else { throw StringDataError.data(self, encoding: encoding) } return string } }
25.693878
79
0.644956
29af197b09c6f6de34ece9bf31bea641fda6659f
324
// // SwifQLable+No.swift // SwifQL // // Created by Mihael Isaev on 29.01.2020. // import Foundation //MARK: NO extension SwifQLable { public var no: SwifQLable { var parts = self.parts parts.appendSpaceIfNeeded() parts.append(o: .no) return SwifQLableParts(parts: parts) } }
15.428571
44
0.62037
502486d7ec845c00c5822952681eea674e2396cd
1,823
// // MockHealthKitDataSource.swift // AnyRing // // Created by Dmitriy Loktev on 20.12.2020. // import Foundation import Combine import HealthKit class MockHealthKitDataSource: HealthKitDataSource { func isAvailable() -> Bool { return true } func requestPermissions(permissions: Set<HKObjectType>) -> Future<Bool, Error> { return Future() { promise in promise(.success(true)) } } func fetchStatistics(withStart startDate: Date, to endDate: Date, ofType sampleType: HKSampleType, unit: HKUnit, aggregation: Aggregation) -> Future<Double, Error> { return Future() { promise in if (sampleType == HKQuantityType.quantityType(forIdentifier: .heartRate)!) { promise(.success(55)) return } if (sampleType == HKQuantityType.quantityType(forIdentifier: .heartRateVariabilitySDNN)!) { promise(.success(110)) return } if (sampleType == HKQuantityType.quantityType(forIdentifier: .appleStandTime)!) { promise(.success(8)) return } if (sampleType == HKObjectType.quantityType(forIdentifier: .activeEnergyBurned)!) { promise(.success(1100)) return } if (sampleType == HKObjectType.quantityType(forIdentifier: .appleExerciseTime)!) { promise(.success(110)) return } if (sampleType == HKObjectType.quantityType(forIdentifier: .stepCount)!) { promise(.success(5100)) return } promise(.success(0)) } } }
29.403226
169
0.53977
46d6c5bd5eb48337b6a423d5083a6aaa5147e758
1,607
// // ViewController.swift // desafio01 // // Created by Mizia Lima on 9/19/20. // import UIKit class ViewController: UIViewController { //MARK: Variables var arrayItens = [PesquisarObjetoProtocol] () //MARK: Outlets @IBOutlet weak var searchBarPesquisa: UISearchBar! @IBOutlet weak var labelPesquisa: UILabel! override func viewDidLoad() { super.viewDidLoad() searchBarPesquisa.delegate = self //testes arrayItens.append(Aviao(modelo: "A380", cidade: "Guarulhos")) arrayItens.append(PessoaJuridica(nome: "Digital House", cnpj: "111111")) arrayItens.append(PessoaFisica(nome: "Ana", cpf: "222.222.222 - 22")) arrayItens.append(Cachorro(nome: "Mel", raca: "Akita")) arrayItens.append(Caneta(marca: "BIC")) } //MARK: Funcoes func filtrar(textoPesquisa: String){ var arrayFiltrar = [PesquisarObjetoProtocol] () for item in arrayItens { if item.getBusca().lowercased().contains(textoPesquisa.lowercased()){ arrayFiltrar.append(item) } } var saida = "" for item in arrayFiltrar { saida = "\(saida)\n\(item.getFormatadoParaUsuario())" } print(saida) labelPesquisa.text = saida } } //MARK: Extensions extension ViewController: UISearchBarDelegate { func searchBarSearchButtonClicked(_ searchBar: UISearchBar){ if let texto = searchBarPesquisa.text { filtrar(textoPesquisa: texto) } } }
26.344262
81
0.604231
647a7cc96b4ff894f9b2e2aa8837cbc8cca80eb4
341
// // SearchWordTableViewCellAttributes.swift // SkyEng_Task // // Created by Vitalii Lavreniuk on 8/2/20. // Copyright © 2020 Vitalii Lavreniuk. All rights reserved. // import Foundation final class SearchWordTableViewCellAttributes { var id:Int! var index: Int = 0 var translatedWord: String = "" var notes: String = "" }
18.944444
60
0.709677
625a46f13489e9059600c6321205f2ed69415d72
26,358
#if !canImport(ObjectiveC) import XCTest extension AccessorTests { // DO NOT MODIFY: This is autogenerated, use: // `swift test --generate-linuxmain` // to regenerate. static let __allTests__AccessorTests = [ ("testBasicAccessors", testBasicAccessors), ("testEmptyAccessorBody", testEmptyAccessorBody), ("testEmptyAccessorBodyWithComment", testEmptyAccessorBodyWithComment), ("testEmptyAccessorList", testEmptyAccessorList), ("testSetModifier", testSetModifier), ] } extension ArrayDeclTests { // DO NOT MODIFY: This is autogenerated, use: // `swift test --generate-linuxmain` // to regenerate. static let __allTests__ArrayDeclTests = [ ("testArrayOfFunctions", testArrayOfFunctions), ("testBasicArrays", testBasicArrays), ] } extension AsExprTests { // DO NOT MODIFY: This is autogenerated, use: // `swift test --generate-linuxmain` // to regenerate. static let __allTests__AsExprTests = [ ("testWithoutPunctuation", testWithoutPunctuation), ("testWithPunctuation", testWithPunctuation), ] } extension AttributeTests { // DO NOT MODIFY: This is autogenerated, use: // `swift test --generate-linuxmain` // to regenerate. static let __allTests__AttributeTests = [ ("testAttributArgumentPerLineBreaking", testAttributArgumentPerLineBreaking), ("testAttributeArgumentPerLineWrapping", testAttributeArgumentPerLineWrapping), ("testAttributeBinPackedWrapping", testAttributeBinPackedWrapping), ("testAttributeFormattingRespectsDiscretionaryLineBreaks", testAttributeFormattingRespectsDiscretionaryLineBreaks), ("testAttributeInterArgumentBinPackedLineBreaking", testAttributeInterArgumentBinPackedLineBreaking), ("testAttributeParamSpacing", testAttributeParamSpacing), ("testObjCAttributesDiscretionaryLineBreaking", testObjCAttributesDiscretionaryLineBreaking), ("testObjCAttributesPerLineBreaking", testObjCAttributesPerLineBreaking), ("testObjCBinPackedAttributes", testObjCBinPackedAttributes), ] } extension AvailabilityConditionTests { // DO NOT MODIFY: This is autogenerated, use: // `swift test --generate-linuxmain` // to regenerate. static let __allTests__AvailabilityConditionTests = [ ("testAvailabilityCondition", testAvailabilityCondition), ("testAvailabilityConditionWithTrailingComment", testAvailabilityConditionWithTrailingComment), ] } extension BacktickTests { // DO NOT MODIFY: This is autogenerated, use: // `swift test --generate-linuxmain` // to regenerate. static let __allTests__BacktickTests = [ ("testBackticks", testBackticks), ] } extension ClassDeclTests { // DO NOT MODIFY: This is autogenerated, use: // `swift test --generate-linuxmain` // to regenerate. static let __allTests__ClassDeclTests = [ ("testBasicClassDeclarations", testBasicClassDeclarations), ("testClassAttributes", testClassAttributes), ("testClassFullWrap", testClassFullWrap), ("testClassInheritence", testClassInheritence), ("testClassWhereClause", testClassWhereClause), ("testClassWhereClauseWithInheritence", testClassWhereClauseWithInheritence), ("testEmptyClass", testEmptyClass), ("testEmptyClassWithComment", testEmptyClassWithComment), ("testGenericClassDeclarations_noPackArguments", testGenericClassDeclarations_noPackArguments), ("testGenericClassDeclarations_packArguments", testGenericClassDeclarations_packArguments), ("testOneMemberClass", testOneMemberClass), ] } extension ClosureExprTests { // DO NOT MODIFY: This is autogenerated, use: // `swift test --generate-linuxmain` // to regenerate. static let __allTests__ClosureExprTests = [ ("testArrayClosures", testArrayClosures), ("testBasicFunctionClosures_noPackArguments", testBasicFunctionClosures_noPackArguments), ("testBasicFunctionClosures_packArguments", testBasicFunctionClosures_packArguments), ("testBodilessClosure", testBodilessClosure), ("testClosureArgumentsWithTrailingClosure", testClosureArgumentsWithTrailingClosure), ("testClosureCapture", testClosureCapture), ("testClosureCaptureWithoutArguments", testClosureCaptureWithoutArguments), ("testClosuresWithIfs", testClosuresWithIfs), ("testClosureVariables", testClosureVariables), ("testTrailingClosure", testTrailingClosure), ] } extension CommentTests { // DO NOT MODIFY: This is autogenerated, use: // `swift test --generate-linuxmain` // to regenerate. static let __allTests__CommentTests = [ ("testBlockComments", testBlockComments), ("testCommentOnContinuationLine", testCommentOnContinuationLine), ("testContainerLineComments", testContainerLineComments), ("testDocumentationBlockComments", testDocumentationBlockComments), ("testDocumentationComments", testDocumentationComments), ("testDoesNotInsertExtraNewlinesAfterTrailingComments", testDoesNotInsertExtraNewlinesAfterTrailingComments), ("testLineCommentAtEndOfMemberDeclList", testLineCommentAtEndOfMemberDeclList), ("testLineComments", testLineComments), ] } extension DeinitializerDeclTests { // DO NOT MODIFY: This is autogenerated, use: // `swift test --generate-linuxmain` // to regenerate. static let __allTests__DeinitializerDeclTests = [ ("testBasicDeinitializerDeclarations", testBasicDeinitializerDeclarations), ("testDeinitializerAttributes", testDeinitializerAttributes), ("testEmptyDeinitializer", testEmptyDeinitializer), ] } extension DictionaryDeclTests { // DO NOT MODIFY: This is autogenerated, use: // `swift test --generate-linuxmain` // to regenerate. static let __allTests__DictionaryDeclTests = [ ("testBasicDictionaries", testBasicDictionaries), ] } extension EnumDeclTests { // DO NOT MODIFY: This is autogenerated, use: // `swift test --generate-linuxmain` // to regenerate. static let __allTests__EnumDeclTests = [ ("testBasicEnumDeclarations", testBasicEnumDeclarations), ("testEmptyEnum", testEmptyEnum), ("testEmptyEnumWithComment", testEmptyEnumWithComment), ("testEnumAttributes", testEnumAttributes), ("testEnumFullWrap", testEnumFullWrap), ("testEnumInheritence", testEnumInheritence), ("testEnumWhereClause", testEnumWhereClause), ("testEnumWhereClauseWithInheritence", testEnumWhereClauseWithInheritence), ("testGenericEnumDeclarations", testGenericEnumDeclarations), ("testIndirectEnum", testIndirectEnum), ("testMixedEnumCaseStyles_noPackArguments", testMixedEnumCaseStyles_noPackArguments), ("testMixedEnumCaseStyles_packArguments", testMixedEnumCaseStyles_packArguments), ("testOneMemberEnum", testOneMemberEnum), ] } extension ExtensionDeclTests { // DO NOT MODIFY: This is autogenerated, use: // `swift test --generate-linuxmain` // to regenerate. static let __allTests__ExtensionDeclTests = [ ("testBasicExtensionDeclarations", testBasicExtensionDeclarations), ("testEmptyExtension", testEmptyExtension), ("testEmptyExtensionWithComment", testEmptyExtensionWithComment), ("testExtensionAttributes", testExtensionAttributes), ("testExtensionFullWrap", testExtensionFullWrap), ("testExtensionInheritence", testExtensionInheritence), ("testExtensionWhereClause", testExtensionWhereClause), ("testExtensionWhereClauseWithInheritence", testExtensionWhereClauseWithInheritence), ("testOneMemberExtension", testOneMemberExtension), ] } extension ForInStmtTests { // DO NOT MODIFY: This is autogenerated, use: // `swift test --generate-linuxmain` // to regenerate. static let __allTests__ForInStmtTests = [ ("testBasicForLoop", testBasicForLoop), ("testForCase", testForCase), ("testForLabels", testForLabels), ("testForLoopFullWrap", testForLoopFullWrap), ("testForWhereLoop", testForWhereLoop), ("testForWithRanges", testForWithRanges), ] } extension FunctionCallTests { // DO NOT MODIFY: This is autogenerated, use: // `swift test --generate-linuxmain` // to regenerate. static let __allTests__FunctionCallTests = [ ("testArgumentStartsWithOpenDelimiter", testArgumentStartsWithOpenDelimiter), ("testBasicFunctionCalls_noPackArguments", testBasicFunctionCalls_noPackArguments), ("testBasicFunctionCalls_packArguments", testBasicFunctionCalls_packArguments), ("testDiscretionaryLineBreakBeforeClosingParenthesis", testDiscretionaryLineBreakBeforeClosingParenthesis), ("testDiscretionaryLineBreaksAreSelfCorrecting", testDiscretionaryLineBreaksAreSelfCorrecting), ("testSingleUnlabeledArgumentWithDelimiters", testSingleUnlabeledArgumentWithDelimiters), ] } extension FunctionDeclTests { // DO NOT MODIFY: This is autogenerated, use: // `swift test --generate-linuxmain` // to regenerate. static let __allTests__FunctionDeclTests = [ ("testAttributedTypes", testAttributedTypes), ("testBasicFunctionDeclarations_noPackArguments", testBasicFunctionDeclarations_noPackArguments), ("testBasicFunctionDeclarations_packArguments", testBasicFunctionDeclarations_packArguments), ("testBodilessFunctionDecl", testBodilessFunctionDecl), ("testBreaksBeforeOrInsideOutput", testBreaksBeforeOrInsideOutput), ("testBreaksBeforeOrInsideOutputWithAttributes", testBreaksBeforeOrInsideOutputWithAttributes), ("testBreaksBeforeOrInsideOutputWithWhereClause", testBreaksBeforeOrInsideOutputWithWhereClause), ("testEmptyFunction", testEmptyFunction), ("testFunctionAttributes", testFunctionAttributes), ("testFunctionDeclReturns", testFunctionDeclReturns), ("testFunctionDeclThrows", testFunctionDeclThrows), ("testFunctionFullWrap", testFunctionFullWrap), ("testFunctionGenericParameters_noPackArguments", testFunctionGenericParameters_noPackArguments), ("testFunctionGenericParameters_packArguments", testFunctionGenericParameters_packArguments), ("testFunctionWhereClause", testFunctionWhereClause), ("testFunctionWithDefer", testFunctionWithDefer), ("testOperatorOverloads", testOperatorOverloads), ("testRemovesLineBreakBeforeOpenBraceUnlessAbsolutelyNecessary", testRemovesLineBreakBeforeOpenBraceUnlessAbsolutelyNecessary), ] } extension FunctionTypeTests { // DO NOT MODIFY: This is autogenerated, use: // `swift test --generate-linuxmain` // to regenerate. static let __allTests__FunctionTypeTests = [ ("testFunctionType", testFunctionType), ("testFunctionTypeThrows", testFunctionTypeThrows), ] } extension GuardStmtTests { // DO NOT MODIFY: This is autogenerated, use: // `swift test --generate-linuxmain` // to regenerate. static let __allTests__GuardStmtTests = [ ("testContinuationLineBreaking", testContinuationLineBreaking), ("testGuardStatement", testGuardStatement), ("testGuardWithFuncCall", testGuardWithFuncCall), ("testOpenBraceIsGluedToElseKeyword", testOpenBraceIsGluedToElseKeyword), ] } extension IfConfigTests { // DO NOT MODIFY: This is autogenerated, use: // `swift test --generate-linuxmain` // to regenerate. static let __allTests__IfConfigTests = [ ("testBasicIfConfig", testBasicIfConfig), ("testIfConfigNoIndentation", testIfConfigNoIndentation), ("testPoundIfAroundMembers", testPoundIfAroundMembers), ] } extension IfStmtTests { // DO NOT MODIFY: This is autogenerated, use: // `swift test --generate-linuxmain` // to regenerate. static let __allTests__IfStmtTests = [ ("testContinuationLineBreakIndentation", testContinuationLineBreakIndentation), ("testHangingOpenBreakIsTreatedLikeContinuation", testHangingOpenBreakIsTreatedLikeContinuation), ("testIfElseStatement_breakBeforeElse", testIfElseStatement_breakBeforeElse), ("testIfElseStatement_noBreakBeforeElse", testIfElseStatement_noBreakBeforeElse), ("testIfLetStatements", testIfLetStatements), ("testIfStatement", testIfStatement), ("testMatchingPatternConditions", testMatchingPatternConditions), ] } extension ImportTests { // DO NOT MODIFY: This is autogenerated, use: // `swift test --generate-linuxmain` // to regenerate. static let __allTests__ImportTests = [ ("testImports", testImports), ] } extension InitializerDeclTests { // DO NOT MODIFY: This is autogenerated, use: // `swift test --generate-linuxmain` // to regenerate. static let __allTests__InitializerDeclTests = [ ("testBasicInitializerDeclarations_noPackArguments", testBasicInitializerDeclarations_noPackArguments), ("testBasicInitializerDeclarations_packArguments", testBasicInitializerDeclarations_packArguments), ("testEmptyInitializer", testEmptyInitializer), ("testInitializerAttributes", testInitializerAttributes), ("testInitializerDeclThrows", testInitializerDeclThrows), ("testInitializerFullWrap", testInitializerFullWrap), ("testInitializerGenericParameters", testInitializerGenericParameters), ("testInitializerOptionality", testInitializerOptionality), ("testInitializerWhereClause", testInitializerWhereClause), ] } extension MemberAccessExprTests { // DO NOT MODIFY: This is autogenerated, use: // `swift test --generate-linuxmain` // to regenerate. static let __allTests__MemberAccessExprTests = [ ("testContinuationRestorationAfterGroup", testContinuationRestorationAfterGroup), ("testImplicitMemberAccess", testImplicitMemberAccess), ("testMemberAccess", testMemberAccess), ("testMethodChainingWithClosures", testMethodChainingWithClosures), ("testMethodChainingWithClosuresFullWrap", testMethodChainingWithClosuresFullWrap), ] } extension MemberTypeIdentifierTests { // DO NOT MODIFY: This is autogenerated, use: // `swift test --generate-linuxmain` // to regenerate. static let __allTests__MemberTypeIdentifierTests = [ ("testMemberTypes", testMemberTypes), ] } extension NewlineTests { // DO NOT MODIFY: This is autogenerated, use: // `swift test --generate-linuxmain` // to regenerate. static let __allTests__NewlineTests = [ ("testLeadingNewlines", testLeadingNewlines), ("testLeadingNewlinesWithComments", testLeadingNewlinesWithComments), ("testTrailingNewlines", testTrailingNewlines), ("testTrailingNewlinesWithComments", testTrailingNewlinesWithComments), ] } extension OperatorDeclTests { // DO NOT MODIFY: This is autogenerated, use: // `swift test --generate-linuxmain` // to regenerate. static let __allTests__OperatorDeclTests = [ ("testOperatorDecl", testOperatorDecl), ("testPrecedenceGroups", testPrecedenceGroups), ] } extension ProtocolDeclTests { // DO NOT MODIFY: This is autogenerated, use: // `swift test --generate-linuxmain` // to regenerate. static let __allTests__ProtocolDeclTests = [ ("testBasicProtocolDeclarations", testBasicProtocolDeclarations), ("testEmptyProtocol", testEmptyProtocol), ("testEmptyProtocolWithComment", testEmptyProtocolWithComment), ("testOneMemberProtocol", testOneMemberProtocol), ("testProtocolAttributes", testProtocolAttributes), ("testProtocolInheritence", testProtocolInheritence), ("testProtocolWithAssociatedtype", testProtocolWithAssociatedtype), ("testProtocolWithFunctions", testProtocolWithFunctions), ("testProtocolWithInitializers", testProtocolWithInitializers), ] } extension RepeatStmtTests { // DO NOT MODIFY: This is autogenerated, use: // `swift test --generate-linuxmain` // to regenerate. static let __allTests__RepeatStmtTests = [ ("testBasicRepeatTests_breakBeforeWhile", testBasicRepeatTests_breakBeforeWhile), ("testBasicRepeatTests_noBreakBeforeWhile", testBasicRepeatTests_noBreakBeforeWhile), ("testNestedRepeat", testNestedRepeat), ] } extension SemiColonTypeTests { // DO NOT MODIFY: This is autogenerated, use: // `swift test --generate-linuxmain` // to regenerate. static let __allTests__SemiColonTypeTests = [ ("testNoSemicolon", testNoSemicolon), ("testSemicolon", testSemicolon), ] } extension SomeTypeTests { // DO NOT MODIFY: This is autogenerated, use: // `swift test --generate-linuxmain` // to regenerate. static let __allTests__SomeTypeTests = [ ("testSomeTypes", testSomeTypes), ] } extension StringTests { // DO NOT MODIFY: This is autogenerated, use: // `swift test --generate-linuxmain` // to regenerate. static let __allTests__StringTests = [ ("testMultilineRawString", testMultilineRawString), ("testMultilineRawStringOpenQuotesWrap", testMultilineRawStringOpenQuotesWrap), ("testMultilineStringAutocorrectMisalignedLines", testMultilineStringAutocorrectMisalignedLines), ("testMultilineStringInterpolations", testMultilineStringInterpolations), ("testMultilineStringIsReindentedCorrectly", testMultilineStringIsReindentedCorrectly), ("testMultilineStringKeepsBlankLines", testMultilineStringKeepsBlankLines), ("testMultilineStringOpenQuotesDoNotWrapIfStringIsVeryLong", testMultilineStringOpenQuotesDoNotWrapIfStringIsVeryLong), ("testStrings", testStrings), ] } extension StructDeclTests { // DO NOT MODIFY: This is autogenerated, use: // `swift test --generate-linuxmain` // to regenerate. static let __allTests__StructDeclTests = [ ("testBasicStructDeclarations", testBasicStructDeclarations), ("testEmptyStruct", testEmptyStruct), ("testEmptyStructWithComment", testEmptyStructWithComment), ("testGenericStructDeclarations_noPackArguments", testGenericStructDeclarations_noPackArguments), ("testGenericStructDeclarations_packArguments", testGenericStructDeclarations_packArguments), ("testOneMemberStruct", testOneMemberStruct), ("testStructAttributes", testStructAttributes), ("testStructFullWrap", testStructFullWrap), ("testStructInheritence", testStructInheritence), ("testStructWhereClause", testStructWhereClause), ("testStructWhereClauseWithInheritence", testStructWhereClauseWithInheritence), ] } extension SubscriptDeclTests { // DO NOT MODIFY: This is autogenerated, use: // `swift test --generate-linuxmain` // to regenerate. static let __allTests__SubscriptDeclTests = [ ("testBasicSubscriptDeclarations", testBasicSubscriptDeclarations), ("testEmptySubscript", testEmptySubscript), ("testSubscriptAttributes", testSubscriptAttributes), ("testSubscriptFullWrap", testSubscriptFullWrap), ("testSubscriptGenerics_noPackArguments", testSubscriptGenerics_noPackArguments), ("testSubscriptGenerics_packArguments", testSubscriptGenerics_packArguments), ("testSubscriptGenericWhere", testSubscriptGenericWhere), ] } extension SubscriptExprTests { // DO NOT MODIFY: This is autogenerated, use: // `swift test --generate-linuxmain` // to regenerate. static let __allTests__SubscriptExprTests = [ ("testBasicSubscriptGetters", testBasicSubscriptGetters), ("testBasicSubscriptSetters", testBasicSubscriptSetters), ("testSubscriptGettersWithTrailingClosures", testSubscriptGettersWithTrailingClosures), ("testSubscriptSettersWithTrailingClosures", testSubscriptSettersWithTrailingClosures), ] } extension SwitchStmtTests { // DO NOT MODIFY: This is autogenerated, use: // `swift test --generate-linuxmain` // to regenerate. static let __allTests__SwitchStmtTests = [ ("testBasicSwitch", testBasicSwitch), ("testNestedSwitch", testNestedSwitch), ("testSwitchCases", testSwitchCases), ("testSwitchCompoundCases", testSwitchCompoundCases), ("testSwitchValueBinding", testSwitchValueBinding), ("testUnknownDefault", testUnknownDefault), ] } extension TernaryExprTests { // DO NOT MODIFY: This is autogenerated, use: // `swift test --generate-linuxmain` // to regenerate. static let __allTests__TernaryExprTests = [ ("testTernaryExprs", testTernaryExprs), ] } extension TryCatchTests { // DO NOT MODIFY: This is autogenerated, use: // `swift test --generate-linuxmain` // to regenerate. static let __allTests__TryCatchTests = [ ("testBasicTries", testBasicTries), ("testCatchWhere_breakBeforeCatch", testCatchWhere_breakBeforeCatch), ("testCatchWhere_noBreakBeforeCatch", testCatchWhere_noBreakBeforeCatch), ("testDoTryCatch_breakBeforeCatch", testDoTryCatch_breakBeforeCatch), ("testDoTryCatch_noBreakBeforeCatch", testDoTryCatch_noBreakBeforeCatch), ("testNestedDo", testNestedDo), ] } extension TupleDeclTests { // DO NOT MODIFY: This is autogenerated, use: // `swift test --generate-linuxmain` // to regenerate. static let __allTests__TupleDeclTests = [ ("testBasicTuples", testBasicTuples), ("testLabeledTuples", testLabeledTuples), ] } extension TypeAliasTests { // DO NOT MODIFY: This is autogenerated, use: // `swift test --generate-linuxmain` // to regenerate. static let __allTests__TypeAliasTests = [ ("testTypealias", testTypealias), ("testTypealiasAttributes", testTypealiasAttributes), ("testTypealiasGenericTests", testTypealiasGenericTests), ] } extension UnknownDeclTests { // DO NOT MODIFY: This is autogenerated, use: // `swift test --generate-linuxmain` // to regenerate. static let __allTests__UnknownDeclTests = [ ("testUnknownDecl", testUnknownDecl), ] } extension VariableDeclarationTests { // DO NOT MODIFY: This is autogenerated, use: // `swift test --generate-linuxmain` // to regenerate. static let __allTests__VariableDeclarationTests = [ ("testBasicVariableDecl", testBasicVariableDecl), ("testMultipleBindings", testMultipleBindings), ("testMultipleBindingsWithTypeAnnotations", testMultipleBindingsWithTypeAnnotations), ("testVariableDeclWithAttributes", testVariableDeclWithAttributes), ] } extension WhileStmtTests { // DO NOT MODIFY: This is autogenerated, use: // `swift test --generate-linuxmain` // to regenerate. static let __allTests__WhileStmtTests = [ ("testBasicWhileLoops", testBasicWhileLoops), ("testLabeledWhileLoops", testLabeledWhileLoops), ] } extension YieldStmtTests { // DO NOT MODIFY: This is autogenerated, use: // `swift test --generate-linuxmain` // to regenerate. static let __allTests__YieldStmtTests = [ ("testBasic", testBasic), ] } public func __allTests() -> [XCTestCaseEntry] { return [ testCase(AccessorTests.__allTests__AccessorTests), testCase(ArrayDeclTests.__allTests__ArrayDeclTests), testCase(AsExprTests.__allTests__AsExprTests), testCase(AttributeTests.__allTests__AttributeTests), testCase(AvailabilityConditionTests.__allTests__AvailabilityConditionTests), testCase(BacktickTests.__allTests__BacktickTests), testCase(ClassDeclTests.__allTests__ClassDeclTests), testCase(ClosureExprTests.__allTests__ClosureExprTests), testCase(CommentTests.__allTests__CommentTests), testCase(DeinitializerDeclTests.__allTests__DeinitializerDeclTests), testCase(DictionaryDeclTests.__allTests__DictionaryDeclTests), testCase(EnumDeclTests.__allTests__EnumDeclTests), testCase(ExtensionDeclTests.__allTests__ExtensionDeclTests), testCase(ForInStmtTests.__allTests__ForInStmtTests), testCase(FunctionCallTests.__allTests__FunctionCallTests), testCase(FunctionDeclTests.__allTests__FunctionDeclTests), testCase(FunctionTypeTests.__allTests__FunctionTypeTests), testCase(GuardStmtTests.__allTests__GuardStmtTests), testCase(IfConfigTests.__allTests__IfConfigTests), testCase(IfStmtTests.__allTests__IfStmtTests), testCase(ImportTests.__allTests__ImportTests), testCase(InitializerDeclTests.__allTests__InitializerDeclTests), testCase(MemberAccessExprTests.__allTests__MemberAccessExprTests), testCase(MemberTypeIdentifierTests.__allTests__MemberTypeIdentifierTests), testCase(NewlineTests.__allTests__NewlineTests), testCase(OperatorDeclTests.__allTests__OperatorDeclTests), testCase(ProtocolDeclTests.__allTests__ProtocolDeclTests), testCase(RepeatStmtTests.__allTests__RepeatStmtTests), testCase(SemiColonTypeTests.__allTests__SemiColonTypeTests), testCase(SomeTypeTests.__allTests__SomeTypeTests), testCase(StringTests.__allTests__StringTests), testCase(StructDeclTests.__allTests__StructDeclTests), testCase(SubscriptDeclTests.__allTests__SubscriptDeclTests), testCase(SubscriptExprTests.__allTests__SubscriptExprTests), testCase(SwitchStmtTests.__allTests__SwitchStmtTests), testCase(TernaryExprTests.__allTests__TernaryExprTests), testCase(TryCatchTests.__allTests__TryCatchTests), testCase(TupleDeclTests.__allTests__TupleDeclTests), testCase(TypeAliasTests.__allTests__TypeAliasTests), testCase(UnknownDeclTests.__allTests__UnknownDeclTests), testCase(VariableDeclarationTests.__allTests__VariableDeclarationTests), testCase(WhileStmtTests.__allTests__WhileStmtTests), testCase(YieldStmtTests.__allTests__YieldStmtTests), ] } #endif
43.139116
135
0.735868
eb0f62489ce72db9b7991dc707afb1ed77f6ed83
774
// // PAYJP.swift // RNPayjpIOS // // Created by sunao on 2018/11/22. // Copyright © 2018 sunao. All rights reserved. // import Foundation let PAYErrorDomain = "PAYErrorDomain"; let PAYErrorInvalidApplePayToken = 0; let PAYErrorSystemError = 1; let PAYErrorInvalidResponse = 2; let PAYErrorInvalidResponseBody = 3; let PAYErrorServiceError = 4; let PAYErrorInvalidJSON = 5; let PAYErrorInvalidApplePayTokenObject = "PAYErrorInvalidApplePayToken"; let PAYErrorSystemErrorObject = "PAYErrorSystemErrorObject"; let PAYErrorInvalidResponseObject = "PAYErrorInvalidResponseObject"; let PAYErrorInvalidResponseData = "PAYErrorInvalidResponseData"; let PAYErrorServiceErrorObject = "PAYErrorServiceErrorObject"; let PAYErrorInvalidJSONObject = "PAYErrorInvalidJSONObject";
29.769231
72
0.813953
de8938d73708e45b96ebf045f640315c7e8236d5
573
// // MambaNetworkingClosingError.swift // mamba // // Created by Armand Kamffer on 2020/07/19. // Copyright © 2020 Armand Kamffer. All rights reserved. // import Foundation public enum NetworkCloseError: Error { case failure(Error?) public var errorCode: String { switch self { case .failure: return "3000" } } public var errorDescription: String { switch self { case .failure(let error): return error?.localizedDescription ?? "Something went wrong with the connection" } } }
21.222222
92
0.623037
64c9c0ed127b10ca09c6b30315e7d1e020e14b5b
2,809
// // BaseViewController.swift // SportDemo // // Created by Binea Xu on 8/8/15. // Copyright (c) 2015 Binea Xu. All rights reserved. // import UIKit class BaseViewController: UIViewController, UIViewControllerTransitioningDelegate { // static func instanceFromStoryboard(storyBoardName: String, viewControllerName: String)->UIViewController{ // let storyboard = UIStoryboard(name: storyBoardName, bundle: nil) // return storyboard.instantiateViewControllerWithIdentifier(viewControllerName) as! UIViewController // } // // static func instanceNavigationControllerFromStoryboard(storyBoardName: String, viewControllerName: String) -> UINavigationController{ // let storyboard = UIStoryboard(name: storyBoardName, bundle: nil) // return storyboard.instantiateViewControllerWithIdentifier(viewControllerName) as! UINavigationController // } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func presentViewController(viewControllerToPresent: UIViewController, animated: Bool, completion: (() -> Void)?){ viewControllerToPresent.transitioningDelegate = self super.presentViewController(viewControllerToPresent, animated: animated, completion: completion) } } extension UIViewController { func closeAnimated() { if self.navigationController != nil && self.navigationController?.viewControllers.count > 1 { self.navigationController?.popViewControllerAnimated(true) } else if self.presentingViewController != nil { dismissViewControllerAnimated(true, completion: nil) } } func closeAnimatedWithCompleteAction(completion: (() -> Void)?) { if self.navigationController != nil && self.navigationController?.viewControllers.count > 1 { self.navigationController?.popViewControllerAnimated(true) }else if((self.presentingViewController) != nil) { if self.navigationController != nil { self.navigationController?.resignFirstResponder() } let isFromSheet = ZEPP.IPAD_REGULAR && self.navigationController != nil && navigationController?.modalPresentationStyle == UIModalPresentationStyle.FormSheet dismissViewControllerAnimated(true){ completion!() if isFromSheet { ZPControl.topViewController().viewWillAppear(true) ZPControl.topViewController().viewDidAppear(true) } } } } }
38.479452
169
0.678177
7a524e7e6b08203be1ccbe1e7e332cf1c21c1c38
15,304
// // JSON.swift // Html5iOS // // Created by 刘小杰 on 16/5/13. // Copyright © 2016年 刘小杰. All rights reserved. // import Foundation /// init public class JSON { private let _value:AnyObject /// unwraps the JSON object public class func unwrap(obj:AnyObject) -> AnyObject { switch obj { case let json as JSON: return json._value case let ary as NSArray: var ret = [AnyObject]() for v in ary { ret.append(unwrap(v)) } return ret case let dict as NSDictionary: var ret = [String:AnyObject]() for (ko, v) in dict { if let k = ko as? String { ret[k] = unwrap(v) } } return ret default: return obj } } /// pass the object that was returned from /// NSJSONSerialization public init(_ obj:AnyObject) { self._value = JSON.unwrap(obj) } /// pass the JSON object for another instance public init(_ json:JSON){ self._value = json._value } } /// class properties extension JSON { public typealias NSNull = Foundation.NSNull public typealias NSError = Foundation.NSError public class var null:NSNull { return NSNull() } /// constructs JSON object from data public convenience init(data:NSData) { var err:NSError? var obj:AnyObject? do { obj = try NSJSONSerialization.JSONObjectWithData( data, options:[]) } catch let error as NSError { err = error obj = nil } self.init(err != nil ? err! : obj!) } /// constructs JSON object from string public convenience init(string:String) { let enc:NSStringEncoding = NSUTF8StringEncoding self.init(data: string.dataUsingEncoding(enc)!) } /// parses string to the JSON object /// same as JSON(string:String) public class func parse(string:String)->JSON { return JSON(string:string) } /// constructs JSON object from the content of NSURL public convenience init(nsurl:NSURL) { var enc:NSStringEncoding = NSUTF8StringEncoding do { let str = try NSString(contentsOfURL:nsurl, usedEncoding:&enc) self.init(string:str as String) } catch let err as NSError { self.init(err) } } /// fetch the JSON string from NSURL and parse it /// same as JSON(nsurl:NSURL) public class func fromNSURL(nsurl:NSURL) -> JSON { return JSON(nsurl:nsurl) } /// constructs JSON object from the content of URL public convenience init(url:String) { if let nsurl = NSURL(string:url) as NSURL? { self.init(nsurl:nsurl) } else { self.init(NSError( domain:"JSONErrorDomain", code:400, userInfo:[NSLocalizedDescriptionKey: "malformed URL"] ) ) } } /// fetch the JSON string from URL in the string public class func fromURL(url:String) -> JSON { return JSON(url:url) } /// does what JSON.stringify in ES5 does. /// when the 2nd argument is set to true it pretty prints public class func stringify(obj:AnyObject, pretty:Bool=false) -> String! { if !NSJSONSerialization.isValidJSONObject(obj) { let error = JSON(NSError( domain:"JSONErrorDomain", code:422, userInfo:[NSLocalizedDescriptionKey: "not an JSON object"] )) return JSON(error).toString(pretty) } return JSON(obj).toString(pretty) } } /// instance properties extension JSON { /// access the element like array public subscript(idx:Int) -> JSON { switch _value { case _ as NSError: return self case let ary as NSArray: if 0 <= idx && idx < ary.count { return JSON(ary[idx]) } return JSON(NSError( domain:"JSONErrorDomain", code:404, userInfo:[ NSLocalizedDescriptionKey: "[\(idx)] is out of range" ])) default: return JSON(NSError( domain:"JSONErrorDomain", code:500, userInfo:[ NSLocalizedDescriptionKey: "not an array" ])) } } /// access the element like dictionary public subscript(key:String)->JSON { switch _value { case _ as NSError: return self case let dic as NSDictionary: if let val:AnyObject = dic[key] { return JSON(val) } return JSON(NSError( domain:"JSONErrorDomain", code:404, userInfo:[ NSLocalizedDescriptionKey: "[\"\(key)\"] not found" ])) default: return JSON(NSError( domain:"JSONErrorDomain", code:500, userInfo:[ NSLocalizedDescriptionKey: "not an object" ])) } } /// access json data object public var data:AnyObject? { return self.isError ? nil : self._value } /// Gives the type name as string. /// e.g. if it returns "Double" /// .asDouble returns Double public var type:String { switch _value { case is NSError: return "NSError" case is NSNull: return "NSNull" case let o as NSNumber: switch String.fromCString(o.objCType)! { case "c", "C": return "Bool" case "q", "l", "i", "s": return "Int" case "Q", "L", "I", "S": return "UInt" default: return "Double" } case is NSString: return "String" case is NSArray: return "Array" case is NSDictionary: return "Dictionary" default: return "NSError" } } /// check if self is NSError public var isError: Bool { return _value is NSError } /// check if self is NSNull public var isNull: Bool { return _value is NSNull } /// check if self is Bool public var isBool: Bool { return type == "Bool" } /// check if self is Int public var isInt: Bool { return type == "Int" } /// check if self is UInt public var isUInt: Bool { return type == "UInt" } /// check if self is Double public var isDouble: Bool { return type == "Double" } /// check if self is any type of number public var isNumber: Bool { if let o = _value as? NSNumber { let t = String.fromCString(o.objCType)! return t != "c" && t != "C" } return false } /// check if self is String public var isString: Bool { return _value is NSString } /// check if self is Array public var isArray: Bool { return _value is NSArray } /// check if self is Dictionary public var isDictionary: Bool { return _value is NSDictionary } /// check if self is a valid leaf node. public var isLeaf: Bool { return !(isArray || isDictionary || isError) } /// gives NSError if it holds the error. nil otherwise public var asError:NSError? { return _value as? NSError } /// gives NSNull if self holds it. nil otherwise public var asNull:NSNull? { return _value is NSNull ? JSON.null : nil } /// gives Bool if self holds it. nil otherwise public var asBool:Bool? { switch _value { case let o as NSNumber: switch String.fromCString(o.objCType)! { case "c", "C": return Bool(o.boolValue) default: return nil } default: return nil } } /// gives Int if self holds it. nil otherwise public var asInt:Int? { switch _value { case let o as NSNumber: switch String.fromCString(o.objCType)! { case "c", "C": return nil default: return Int(o.longLongValue) } default: return nil } } /// gives Int32 if self holds it. nil otherwise public var asInt32:Int32? { switch _value { case let o as NSNumber: switch String.fromCString(o.objCType)! { case "c", "C": return nil default: return Int32(o.longLongValue) } default: return nil } } /// gives Int64 if self holds it. nil otherwise public var asInt64:Int64? { switch _value { case let o as NSNumber: switch String.fromCString(o.objCType)! { case "c", "C": return nil default: return Int64(o.longLongValue) } default: return nil } } /// gives Float if self holds it. nil otherwise public var asFloat:Float? { switch _value { case let o as NSNumber: switch String.fromCString(o.objCType)! { case "c", "C": return nil default: return Float(o.floatValue) } default: return nil } } /// gives Double if self holds it. nil otherwise public var asDouble:Double? { switch _value { case let o as NSNumber: switch String.fromCString(o.objCType)! { case "c", "C": return nil default: return Double(o.doubleValue) } default: return nil } } // an alias to asDouble public var asNumber:Double? { return asDouble } /// gives String if self holds it. nil otherwise public var asString:String? { switch _value { case let o as NSString: return o as String default: return nil } } /// if self holds NSArray, gives a [JSON] /// with elements therein. nil otherwise public var asArray:[JSON]? { switch _value { case let o as NSArray: var result = [JSON]() for v:AnyObject in o { result.append(JSON(v)) } return result default: return nil } } /// if self holds NSDictionary, gives a [String:JSON] /// with elements therein. nil otherwise public var asDictionary:[String:JSON]? { switch _value { case let o as NSDictionary: var result = [String:JSON]() for (ko, v): (AnyObject, AnyObject) in o { if let k = ko as? String { result[k] = JSON(v) } } return result default: return nil } } /// Yields date from string public var asDate:NSDate? { if let dateString = _value as? String { let dateFormatter = NSDateFormatter() dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZZZZ" return dateFormatter.dateFromString(dateString) } return nil } /// gives the number of elements if an array or a dictionary. /// you can use this to check if you can iterate. public var count:Int { switch _value { case let o as NSArray: return o.count case let o as NSDictionary: return o.count default: return 0 } } public var length:Int { return self.count } // gives all values content in JSON object. public var allValues:JSON{ if(self._value.allValues == nil) { return JSON([]) } return JSON(self._value.allValues) } // gives all keys content in JSON object. public var allKeys:JSON{ if(self._value.allKeys == nil) { return JSON([]) } return JSON(self._value.allKeys) } } extension JSON : SequenceType { public func generate()->AnyGenerator<(AnyObject,JSON)> { switch _value { case let o as NSArray: var i = -1 return AnyGenerator { i += 1 if i == o.count { return nil } return (i, JSON(o[i])) } case let o as NSDictionary: var ks = Array(o.allKeys.reverse()) return AnyGenerator { if ks.isEmpty { return nil } if let k = ks.removeLast() as? String { return (k, JSON(o.valueForKey(k)!)) } else { return nil } } default: return AnyGenerator{ nil } } } public func mutableCopyOfTheObject() -> AnyObject { return _value.mutableCopy() } } extension JSON : CustomStringConvertible { /// stringifies self. /// if pretty:true it pretty prints public func toString(pretty:Bool=false)->String { switch _value { case is NSError: return "\(_value)" case is NSNull: return "null" case let o as NSNumber: switch String.fromCString(o.objCType)! { case "c", "C": return o.boolValue.description case "q", "l", "i", "s": return o.longLongValue.description case "Q", "L", "I", "S": return o.unsignedLongLongValue.description default: switch o.doubleValue { case 0.0/0.0: return "0.0/0.0" // NaN case -1.0/0.0: return "-1.0/0.0" // -infinity case +1.0/0.0: return "+1.0/0.0" // infinity default: return o.doubleValue.description } } case let o as NSString: return o.debugDescription default: let opts = pretty ? NSJSONWritingOptions.PrettyPrinted : NSJSONWritingOptions() if let data = (try? NSJSONSerialization.dataWithJSONObject( _value, options:opts)) as NSData? { if let result = NSString( data:data, encoding:NSUTF8StringEncoding ) as? String { return result } } return "YOU ARE NOT SUPPOSED TO SEE THIS!" } } public var description:String { return toString() } } extension JSON : Equatable {} public func ==(lhs:JSON, rhs:JSON)->Bool { // print("lhs:\(lhs), rhs:\(rhs)") if lhs.isError || rhs.isError { return false } else if lhs.isLeaf { if lhs.isNull { return lhs.asNull == rhs.asNull } if lhs.isBool { return lhs.asBool == rhs.asBool } if lhs.isNumber { return lhs.asNumber == rhs.asNumber } if lhs.isString { return lhs.asString == rhs.asString } } else if lhs.isArray { for i in 0..<lhs.count { if lhs[i] != rhs[i] { return false } } return true } else if lhs.isDictionary { for (k, v) in lhs.asDictionary! { if v != rhs[k] { return false } } return true } fatalError("JSON == JSON failed!") }
33.125541
91
0.52862
bb3ebda96c21f567e7f58ae44188c1d84f2d0b3c
2,412
// // Created by Tom Baranes on 30/03/16. // Copyright © 2016 IBAnimatable. All rights reserved. // import UIKit public class SystemCameraIrisAnimator: NSObject, AnimatedTransitioning { // MARK: - AnimatorProtocol public var transitionAnimationType: TransitionAnimationType public var transitionDuration: Duration = defaultTransitionDuration public var reverseAnimationType: TransitionAnimationType? public var interactiveGestureType: InteractiveGestureType? // MARK: - private fileprivate var hollowState: TransitionAnimationType.HollowState public init(hollowState: TransitionAnimationType.HollowState, transitionDuration: Duration) { self.transitionDuration = transitionDuration self.hollowState = hollowState switch hollowState { case .open: self.transitionAnimationType = .systemCameraIris(hollowState: .open) self.reverseAnimationType = .systemCameraIris(hollowState: .close) self.interactiveGestureType = .pinch(direction: .close) case .close: self.transitionAnimationType = .systemCameraIris(hollowState: .close) self.reverseAnimationType = .systemCameraIris(hollowState: .open) self.interactiveGestureType = .pinch(direction: .open) case .none: self.transitionAnimationType = .systemCameraIris(hollowState: .none) self.reverseAnimationType = .systemCameraIris(hollowState: .none) self.interactiveGestureType = .pinch(direction: .close) } super.init() } } extension SystemCameraIrisAnimator: UIViewControllerAnimatedTransitioning { public func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval { return retrieveTransitionDuration(transitionContext: transitionContext) } public func animateTransition(using transitionContext: UIViewControllerContextTransitioning) { switch self.hollowState { case .open: animateWithCATransition(transitionContext: transitionContext, type: TransitionAnimationType.SystemTransitionType.cameraIrisHollowOpen, subtype: nil) case .close: animateWithCATransition(transitionContext: transitionContext, type: TransitionAnimationType.SystemTransitionType.cameraIrisHollowClose, subtype: nil) case .none: animateWithCATransition(transitionContext: transitionContext, type: TransitionAnimationType.SystemTransitionType.cameraIris, subtype: nil) } } }
41.586207
155
0.781509
1c731b15c2a5742da88ade8f90f45268927ab6da
4,359
// // LoadSentences.swift // MyUnimol // // Created by Giovanni Grano on 05/05/16. // Copyright © 2016 Giovanni Grano. All rights reserved. // import Foundation class LoadSentences { static let sentences: [String] = [ "L'equinozio? Un cavallo fannullone?", "Ma la lana di vetro si fa con le pecore di Murano???", "San Remo? Il protettore dei fratelli Abbagnale?", "Le guardie forestali quando muoiono vanno al Gran Paradiso?", "La storia di Adamo ed Eva fu il primo melo-dramma?", "L'insalata russa e il pomodoro non dorme...", "\"Ieri ho vomitato tutto il giorno\". \"Vedi di rimetterti.\"", "Perché i Kamikaze portano un casco???", "Cosa faceva uno sputo su una scala? Saliva.", "\"Non so se mi spiego...\" disse il paracadute.", "\"Non so se mi spiedo...\" disse un pollo sul girarrosto.", "Il marinaio spiegò le vele al vento, ma il vento non capì", "Misticismodi uno Streptococcus termophilus: \"Ecce Yomo.\"", "Ragazzo scoppia di salute: 9 morti e 3 feriti.", "\"Mi hanno messo in cinta!\", disse una fibbia.", "La mela al verme: \"Non parlare, bacami !\".", "Arrestato un concorso che era stato bandito...", "Perché le tende piangono? Perché sono da sole.", "\"Che vitaccia!\" disse il cacciavite...", "\"Wonder Woman sei spacciata!\";\"Lo so, sono un'eroina...\"", "Come si prende un pollo per amazzarlo? Vivo.", "Perché in America fa freddo? Perché è stata scoperta.", "Papa Leone visse anni ruggenti?", "No: il contrario di \"melodia\" non è \"Se-lo-tenga\"...", "Aperta a Cattolica chiesa protestante...", "Nuova lavatrice lanciata sul mercato: 10 morti e 6 feriti...", "Elettricista impazzito dà alla luce un figlio...", "Bimbo scoppia di salute: i genitori in prognosi riservata...", "Disegnatore fa cadere mina per terra: 22 morti...", "Cosa nasce tra un elettricista ed una domestica? Un elettrodomestico...", "Catastrofi del secolo scorso: Hiroshima 45, Cernobyl 86, Windows 95...", "Le uniche cose che girano sotto Windows 95 sono le palle.", "Lo stitico quando muore va in purgatorio?", "\"Gestante\": participio presente o preservativo imperfetto?" ] static let HIGH: Double = 27 static let LOW: Double = 23 static let high: [String : String] = ["Hai una media invidiabile" : "wtf", "Ottima carriera universitaria" : "swag", "Palà e che voti!" : "wtf", "Fai brutto!" : "swag", "Ué che secchio!":"sad", "Palà che media!": "wtf"] static let medium: [String : String] = ["Continua così..." : "swag", "Keep on pushin'" : "swag", "Vai alla grande!":"swag"] static let low: [String: String] = ["Impegnati di più" : "sad", "Che fai stasera?" : "swag", "Eh jamm ja!":"sad"] /// Returns a random loading sentence static func getSentence() -> String { return self.sentences.randomItem() } /// Gets a random home greating and an icon to display, based on the average static func getRandomHomeSentence(_ average: Double) -> [String : String] { switch average { case _ where average > HIGH: return self.high.randomItem() case _ where average > LOW && average < HIGH: return self.medium.randomItem() case _ where average < LOW: return self.low.randomItem() default: return ["Ma che razzi di voti hai?!": "wtf"] } } } extension Array { func randomItem() -> Element { let index = Int(arc4random_uniform(UInt32(self.count))) return self[index] } } extension Dictionary { func randomItem() -> Dictionary { let index = Int(arc4random_uniform(UInt32(self.count))) let key = Array(self.keys)[index] let value = self[key] return [key : value!] } }
42.320388
83
0.557926
67ad47439aecc00e4850d1fb8018d95752b7eb0c
2,379
// // ASActivityIndicatorViewNode.swift // ASComponents // // Created by Majid Hatami Aghdam on 4/15/19. // Copyright © 2019 Majid Hatami Aghdam. All rights reserved. // import UIKit import AsyncDisplayKit public final class ASActivityIndicatorViewNode: ASDisplayNode2 { var activityIndicatorView:UIActivityIndicatorView { return view as! UIActivityIndicatorView } public override init() { super.init() setViewBlock { () -> UIView in return UIActivityIndicatorView() } self.activityIndicatorView.startAnimating() } public func startAnimating(){ SWKQueue.mainQueue().async { [weak self] in guard let strongSelf = self else { return } strongSelf.activityIndicatorView.startAnimating() } } public func stopAnimating(){ SWKQueue.mainQueue().async { [weak self] in guard let strongSelf = self else { return } strongSelf.activityIndicatorView.stopAnimating() } } public var color: UIColor?{ get{ assert(Thread.isMainThread, "This method must be called on MainThread only") return self.activityIndicatorView.color } set{ SWKQueue.mainQueue().async { [weak self] in guard let strongSelf = self else { return } strongSelf.activityIndicatorView.color = newValue } } } public override var tintColor: UIColor?{ get{ assert(Thread.isMainThread, "This method must be called on MainThread only") return self.activityIndicatorView.tintColor } set{ SWKQueue.mainQueue().async { [weak self] in guard let strongSelf = self else { return } strongSelf.activityIndicatorView.tintColor = newValue } } } public override var backgroundColor: UIColor? { get{ assert(Thread.isMainThread, "This method must be called on MainThread only") return self.activityIndicatorView.backgroundColor } set{ SWKQueue.mainQueue().async { [weak self] in guard let strongSelf = self else { return } strongSelf.activityIndicatorView.backgroundColor = newValue } } } }
30.896104
97
0.601513
f507f9e2a2e956e22406e6dfa654667e75442cc2
195
/// RequestHeader.swift /// iCombineNetwork /// /// - author: Leon Nguyen /// - date: 28/8/21 /// /// The header sent alogn with a HTTP request public typealias RequestHeader = [String: String]
19.5
49
0.676923
b9158d6cdc651cc0ec6921ff8bfd87cf1d7cd89b
3,788
// // CurrentWeatherView.swift // Pretty Weather // // Created by Bart Chrzaszcz on 2017-12-31. // Copyright © 2017 Bart Chrzaszcz. All rights reserved. // import UIKit import Cartography import LatoFont import WeatherIconsKit class CurrentWeatherView: UIView { static var HEIGHT: CGFloat { get { return 160 } } private var didSetupConstraints = false private let cityLbl = UILabel() private let maxTempLbl = UILabel() private let minTempLbl = UILabel() private let iconLbl = UILabel() private let weatherLbl = UILabel() private let currentTempLbl = UILabel() override init(frame: CGRect) { super.init(frame: frame) setup() style() } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // This method is called by the framework when all other constraints are set and the view needs to be laid out override func updateConstraints() { if didSetupConstraints { super.updateConstraints() return } layoutView() super.updateConstraints() didSetupConstraints = true } } // MARK: - Setup private extension CurrentWeatherView { func setup() { addSubview(cityLbl) addSubview(currentTempLbl) addSubview(maxTempLbl) addSubview(minTempLbl) addSubview(iconLbl) addSubview(weatherLbl) } } // MARK: - Layout private extension CurrentWeatherView { func layoutView() { constrain(self) { $0.height == CurrentWeatherView.HEIGHT } constrain(iconLbl) { $0.top == $0.superview!.top $0.left == $0.superview!.left + 20 $0.width == 30 $0.width == $0.height } constrain(weatherLbl, iconLbl) { $0.top == $1.top $0.left == $1.right + 10 $0.height == $1.height $0.width == 200 } constrain(currentTempLbl, iconLbl) { $0.top == $1.bottom $0.left == $1.left } constrain(currentTempLbl, minTempLbl) { $0.bottom == $1.top $0.left == $1.left } constrain(minTempLbl) { $0.bottom == $0.superview!.bottom $0.height == 30 } constrain(maxTempLbl, minTempLbl) { $0.top == $1.top $0.height == $1.height $0.left == $1.right + 10 } constrain(cityLbl) { $0.bottom == $0.superview!.bottom $0.right == $0.superview!.right - 10 $0.height == 30 $0.width == 200 } } } // MARK: - Style private extension CurrentWeatherView { func style() { iconLbl.textColor = UIColor.white weatherLbl.font = UIFont.latoLightFont(ofSize: 20) weatherLbl.textColor = UIColor.white currentTempLbl.font = UIFont.latoLightFont(ofSize: 96) currentTempLbl.textColor = UIColor.white maxTempLbl.font = UIFont.latoLightFont(ofSize: 18) maxTempLbl.textColor = UIColor.white minTempLbl.font = UIFont.latoLightFont(ofSize: 18) minTempLbl.textColor = UIColor.white cityLbl.font = UIFont.latoLightFont(ofSize: 18) cityLbl.textColor = UIColor.white cityLbl.textAlignment = .right } } // MARK: Render extension CurrentWeatherView{ func render(){ iconLbl.attributedText = WIKFontIcon.wiDaySunnyIcon(withSize: 20).attributedString() weatherLbl.text = "Sunny" minTempLbl.text = "4°" maxTempLbl.text = "10°" currentTempLbl.text = "6°" cityLbl.text = "London" } }
26.676056
114
0.571278
086d78e72c407abb64bdec99ff34cbcca9abebed
1,173
// // ViewController.swift // Tip Calc // // Created by Roberto Bradley on 8/29/18. // Copyright © 2018 Roberto Bradley. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var tipLabel: UILabel! @IBOutlet weak var totalLabel: UILabel! @IBOutlet weak var billField: UITextField! @IBOutlet weak var tipControl: UISegmentedControl! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func onTap(_ sender: Any) { view.endEditing(true) } @IBAction func calculateTip(_ sender: Any) { let bill = Double(billField.text!) ?? 0 let tipPercentages = [0.18,0.20,0.25] let tip = bill * tipPercentages[tipControl.selectedSegmentIndex] let total = bill + tip tipLabel.text = String(format: "$%.2f", tip) totalLabel.text = String(format: "$%.2f", total) } }
26.066667
80
0.635976
8af38e99f7e0496d089f67f28d380fe9d5d92496
232
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing struct D{var f=""[1)let a{{}class B{{}class B<T where h:B{let:a
46.4
87
0.737069
bbf2ef7d81b5ca7c29b2ee673e12ec40173c53e6
9,386
// // CJHttpServer1.swift // libSwerve // // Created by Curtis Jones on 2016.03.15. // Copyright © 2016 Symphonic Systems, Inc. All rights reserved. // import Foundation private protocol Handler { var waitForData: Bool { get } func matches(connection: CJHttpConnection, _ request: CJHttpServerRequest, _ response: CJHttpServerResponse) -> CJHttpServerHandlerMatch? } private struct PathEqualsHandler: Handler { let method: CJHttpMethod let path: String let waitForData: Bool let handler: CJHttpServerRequestHandler func matches(connection: CJHttpConnection, _ request: CJHttpServerRequest, _ response: CJHttpServerResponse) -> CJHttpServerHandlerMatch? { if request.path == path { return CJHttpServerHandlerMatch(handler: handler, request: request, response: response, values: nil) } else { return nil } } func runHandler(match: CJHttpServerHandlerMatch) { handler(match) } } private struct PathLikeHandler: Handler { let method: CJHttpMethod let regex: NSRegularExpression let waitForData: Bool let handler: CJHttpServerRequestHandler func matches(connection: CJHttpConnection, _ request: CJHttpServerRequest, _ response: CJHttpServerResponse) -> CJHttpServerHandlerMatch? { let path = request.path var values = [String]() guard let result = regex.firstMatchInString(path, options: NSMatchingOptions(rawValue: 0), range: NSMakeRange(0, request.path.characters.count)) else { return nil } for index in 0..<result.numberOfRanges { guard let range = path.rangeFromNSRange(result.rangeAtIndex(index)) else { continue } values.append(path.substringWithRange(range)) } return CJHttpServerHandlerMatch(handler: handler, request: request, response: response, values: values) } } internal class CJHttpServerImpl: CJHttpServer { private var handlers = [Handler]() private var server: CJServer! required init(server: CJServer) { self.server = server } func start(completionHandler: (Bool, NSError?) -> Void) { CJDispatchBackground() { var success = false var nserror: NSError? // called after starting (or attempting to start) the server / listener to let the caller // know whether we succeeded or not. defer { CJDispatchMain() { completionHandler(success, nserror) } } // wrap the underlying socket connection in an http connection object. the http connection // object takes a handler that is called when an http request is received. self.server.acceptHandler = { [weak self] connection in var c = connection c.context = CJSwerve.httpConnectionType.init(connection: connection) { connection, request in self?.handleRequest(connection, request) } } // start the server or die trying do { try self.server.start() success = true } catch let e as NSError { nserror = e } catch { nserror = NSError(description: "Start failed for an unknown reason.") } } } func stop(completionHandler: (Bool, NSError?) -> Void) { CJDispatchBackground() { var success = false var nserror: NSError? defer { self.server = nil CJDispatchMain() { completionHandler(success, nserror) } } do { try self.server.stop() success = true } catch let e as NSError { nserror = e } catch { nserror = NSError(description: "Failed for an unknown reason!") } } } func addHandler(method: CJHttpMethod, pathEquals path: String, waitForData: Bool = false, handler: CJHttpServerRequestHandler) { handlers.append(PathEqualsHandler(method: method, path: path, waitForData: waitForData, handler: handler)) } func addHandler(method: CJHttpMethod, pathLike pattern: String, waitForData: Bool = false, handler: CJHttpServerRequestHandler) { do { let regex = try NSRegularExpression(pattern: pattern, options: NSRegularExpressionOptions(rawValue: 0)) handlers.append(PathLikeHandler(method: method, regex: regex, waitForData: waitForData, handler: handler)) } catch { DLog("Failed to install handler because of invalid regex pattern: \(pattern)") } } func addFileModule(localPath _lp: String, webPath _wp: String, recurses: Bool) { let localPath = _lp.hasSuffix("/") ? _lp : (_lp + "/") let webPath = _wp.hasSuffix("/") ? _wp.substringToIndex(_wp.endIndex.predecessor()) : _wp let fileManager = NSFileManager() self.addHandler(.Get, pathLike: "^\(webPath)/(.*)$", waitForData: false) { match in // let request = match.request var response = match.response // if the match was the base path with no additional subpaths, the match count will be 1 let path = match.values?.count == 2 ? match.values![1] : "" // prevent the user from escaping the base directory if path.rangeOfString("..") != nil { response.finish() response.close() return } CJDispatchBackground() { // assemble the file path let fileName = path.stringByRemovingPercentEncoding ?? "" let fileType = (fileName as NSString).pathExtension.lowercaseString let filePath = localPath + fileName var isdir: ObjCBool = false let exists = fileManager.fileExistsAtPath(filePath, isDirectory: &isdir) if exists == false { response.finish() response.close() return } if Bool(isdir) == true { do { var page = "<html><body>" for fileName in try fileManager.contentsOfDirectoryAtPath(filePath) { if fileName.hasPrefix(".") == false { if fileManager.isDirectory(filePath + "/" + fileName) { page += "<a href=\"\(fileName.stringByAddingPercentEncodingWithAllowedCharacters(.URLHostAllowedCharacterSet()) ?? "")/\">\(fileName)/</a><br>" } else { page += "<a href=\"\(fileName.stringByAddingPercentEncodingWithAllowedCharacters(.URLHostAllowedCharacterSet()) ?? "")\">\(fileName)</a><br>" } } } page += "</body></html>" guard let fileData = page.dataUsingEncoding(NSUTF8StringEncoding) else { response.finish() response.close() return } // configure and send the response response.addHeader("Content-Type", value: "text/html") response.addHeader("Content-Length", value: fileData.length) response.addHeader("Connection", value: "keep-alive") response.write(fileData) } catch { DLog("Failed to read directory contents [filePath = \(filePath)]") } } else { // close the connection if the target file's data isn't accessible (permissions?) guard let fileData = NSData(contentsOfFile: filePath) else { response.finish() response.close() return } // configure and send the response response.addHeader("Content-Type", value: CJMimeTypeForExtension(fileType) ?? "content/octet-stream") response.addHeader("Content-Length", value: fileData.length) response.addHeader("Connection", value: "keep-alive") response.write(fileData) } response.finish() } } } private final func handleRequest(connection: CJHttpConnection, _ request: CJHttpServerRequest) { var match: CJHttpServerHandlerMatch? var handler: Handler? let response = CJSwerve.httpResponseType.init(connection: connection, request: request) for _handler in handlers { if let _match = _handler.matches(connection, request, response) { match = _match handler = _handler break } } if let handler = handler, var match = match { if request.method != .Get && handler.waitForData == true { if let contentType = request.contentType { if contentType == CJHttpContentType.UrlForm.rawValue { match.request.contentHandler = { [weak self] value, done in self?.handleUrlFormData(match, request, value, done) } } else if contentType == CJHttpContentType.MultipartForm.rawValue { match.request.contentHandler = { [weak self] value, done in self?.handleMultipartFormData(request, value, done) } } else { match.request.contentHandler = { [weak self] value, done in self?.handleRawData(request, value, done) } } } else { match.request.contentHandler = { [weak self] value, done in self?.handleRawData(request, value, done) } } match.request.resume() } else { match.handler(match) } } else { DLog("No handler match found; closing connection [\(request)]") connection.close() } } /// /// URL encoded form data. /// private final func handleUrlFormData(match: CJHttpServerHandlerMatch, _ request: CJHttpServerRequest, _ value: AnyObject?, _ done: Bool) { var request = request if let values = value as? [String: AnyObject] { if request.values != nil { request.values! += values } else { request.values = values } } if done == true { request.contentHandler = nil match.handler(match) } } /// /// Multipart form data. /// private final func handleMultipartFormData(request: CJHttpServerRequest, _ value: AnyObject?, _ done: Bool) { // if let value = value as? FormData { // // } // // if done == true { // // } } /// /// Raw data. /// private final func handleRawData(request: CJHttpServerRequest, _ value: AnyObject?, _ done: Bool) { // if let value = value as? dispatch_data_t { // // } // // if done == true { // // } } }
29.149068
166
0.675474
76207f1f37da34ca882fff6f6565d8790dea8cc4
1,016
// // ResultTransactionPresenter.swift // TransactionsLogs // // Created by Mihail Martyniuk on 21.01.2021. // import Foundation import UIKit class ResultTransactionPresenter: PresenterType { // MARK: Public properties weak var view: ResultTransactionViewInterface! // MARK: Public methods init(view: ResultTransactionViewInterface, provider: API) { self.view = view super.init(provider: provider) } } extension ResultTransactionPresenter: ResultTransactionPresentation { func getCreditCheck(id: Int) { self.view.activityIndicatorChange(true) self.provider.creditCheck(id: id, handler: {[weak self] result in guard let self = self else { return } self.view.activityIndicatorChange(false) switch result { case let .success(data): self.view.showResult(data: data) case let .failure(err): print("Error: \(err)") } }) } }
25.4
73
0.625984
e0b7d7835217da45598ba407cb092ae73a61e86a
6,454
// // Copyright © 2019 Essential Developer. All rights reserved. // import XCTest import FeedStoreChallenge extension FeedStoreSpecs where Self: XCTestCase { func assertThatRetrieveDeliversEmptyOnEmptyCache(on sut: FeedStore, file: StaticString = #file, line: UInt = #line) { expect(sut, toRetrieve: .empty, file: file, line: line) } func assertThatRetrieveHasNoSideEffectsOnEmptyCache(on sut: FeedStore, file: StaticString = #file, line: UInt = #line) { expect(sut, toRetrieveTwice: .empty, file: file, line: line) } func assertThatRetrieveDeliversFoundValuesOnNonEmptyCache(on sut: FeedStore, file: StaticString = #file, line: UInt = #line) { let feed = uniqueImageFeed() let timestamp = Date() insert((feed, timestamp), to: sut) expect(sut, toRetrieve: .found(feed: feed, timestamp: timestamp), file: file, line: line) } func assertThatRetrieveHasNoSideEffectsOnNonEmptyCache(on sut: FeedStore, file: StaticString = #file, line: UInt = #line) { let feed = uniqueImageFeed() let timestamp = Date() insert((feed, timestamp), to: sut) expect(sut, toRetrieveTwice: .found(feed: feed, timestamp: timestamp), file: file, line: line) } func assertThatInsertDeliversNoErrorOnEmptyCache(on sut: FeedStore, file: StaticString = #file, line: UInt = #line) { let insertionError = insert((uniqueImageFeed(), Date()), to: sut) XCTAssertNil(insertionError, "Expected to insert cache successfully", file: file, line: line) } func assertThatInsertDeliversNoErrorOnNonEmptyCache(on sut: FeedStore, file: StaticString = #file, line: UInt = #line) { insert((uniqueImageFeed(), Date()), to: sut) let insertionError = insert((uniqueImageFeed(), Date()), to: sut) XCTAssertNil(insertionError, "Expected to override cache successfully", file: file, line: line) } func assertThatInsertOverridesPreviouslyInsertedCacheValues(on sut: FeedStore, file: StaticString = #file, line: UInt = #line) { insert((uniqueImageFeed(), Date()), to: sut) let latestFeed = uniqueImageFeed() let latestTimestamp = Date() insert((latestFeed, latestTimestamp), to: sut) expect(sut, toRetrieve: .found(feed: latestFeed, timestamp: latestTimestamp), file: file, line: line) } func assertThatDeleteDeliversNoErrorOnEmptyCache(on sut: FeedStore, file: StaticString = #file, line: UInt = #line) { let deletionError = deleteCache(from: sut) XCTAssertNil(deletionError, "Expected empty cache deletion to succeed", file: file, line: line) } func assertThatDeleteHasNoSideEffectsOnEmptyCache(on sut: FeedStore, file: StaticString = #file, line: UInt = #line) { deleteCache(from: sut) expect(sut, toRetrieve: .empty, file: file, line: line) } func assertThatDeleteDeliversNoErrorOnNonEmptyCache(on sut: FeedStore, file: StaticString = #file, line: UInt = #line) { insert((uniqueImageFeed(), Date()), to: sut) let deletionError = deleteCache(from: sut) XCTAssertNil(deletionError, "Expected non-empty cache deletion to succeed", file: file, line: line) } func assertThatDeleteEmptiesPreviouslyInsertedCache(on sut: FeedStore, file: StaticString = #file, line: UInt = #line) { insert((uniqueImageFeed(), Date()), to: sut) deleteCache(from: sut) expect(sut, toRetrieve: .empty, file: file, line: line) } func assertThatSideEffectsRunSerially(on sut: FeedStore, file: StaticString = #file, line: UInt = #line) { var completedOperationsInOrder = [XCTestExpectation]() let op1 = expectation(description: "Operation 1") sut.insert(uniqueImageFeed(), timestamp: Date()) { _ in completedOperationsInOrder.append(op1) op1.fulfill() } let op2 = expectation(description: "Operation 2") sut.deleteCachedFeed { _ in completedOperationsInOrder.append(op2) op2.fulfill() } let op3 = expectation(description: "Operation 3") sut.insert(uniqueImageFeed(), timestamp: Date()) { _ in completedOperationsInOrder.append(op3) op3.fulfill() } waitForExpectations(timeout: 5.0) XCTAssertEqual(completedOperationsInOrder, [op1, op2, op3], "Expected side-effects to run serially but operations finished in the wrong order", file: file, line: line) } } extension FeedStoreSpecs where Self: XCTestCase { func uniqueImageFeed() -> [LocalFeedImage] { return [uniqueImage(), uniqueImage()] } func uniqueImage() -> LocalFeedImage { return LocalFeedImage(id: UUID(), description: "any", location: "any", url: anyURL()) } func anyURL() -> URL { return URL(string: "http://any-url.com")! } func anyNSError() -> NSError { return NSError(domain: "any error", code: 0) } @discardableResult func insert(_ cache: (feed: [LocalFeedImage], timestamp: Date), to sut: FeedStore) -> Error? { let exp = expectation(description: "Wait for cache insertion") var insertionError: Error? sut.insert(cache.feed, timestamp: cache.timestamp) { receivedInsertionError in insertionError = receivedInsertionError exp.fulfill() } wait(for: [exp], timeout: 1.0) return insertionError } @discardableResult func deleteCache(from sut: FeedStore) -> Error? { let exp = expectation(description: "Wait for cache deletion") var deletionError: Error? sut.deleteCachedFeed { receivedDeletionError in deletionError = receivedDeletionError exp.fulfill() } wait(for: [exp], timeout: 1.0) return deletionError } func expect(_ sut: FeedStore, toRetrieveTwice expectedResult: RetrieveCachedFeedResult, file: StaticString = #file, line: UInt = #line) { expect(sut, toRetrieve: expectedResult, file: file, line: line) expect(sut, toRetrieve: expectedResult, file: file, line: line) } func expect(_ sut: FeedStore, toRetrieve expectedResult: RetrieveCachedFeedResult, file: StaticString = #file, line: UInt = #line) { let exp = expectation(description: "Wait for cache retrieval") sut.retrieve { retrievedResult in switch (expectedResult, retrievedResult) { case (.empty, .empty), (.failure, .failure): break case let (.found(expectedFeed, expectedTimestamp), .found(retrievedFeed, retrievedTimestamp)): XCTAssertEqual(retrievedFeed, expectedFeed, file: file, line: line) XCTAssertEqual(retrievedTimestamp, expectedTimestamp, file: file, line: line) default: XCTFail("Expected to retrieve \(expectedResult), got \(retrievedResult) instead", file: file, line: line) } exp.fulfill() } wait(for: [exp], timeout: 1.0) } }
34.886486
169
0.719864
4a54c8d16de4abf0f41e420aa8b647b07ba45d32
849
// // RingShape.swift // SwiftUIProgressRingExample // // Created by Edgar Adrián on 31/08/20. // import SwiftUI struct RingShape: Shape { var progress: Double = 0.0 var thickness: CGFloat = 30.0 var startAngle: Double = -90.0 var animatableData: Double { get { progress } set { progress = newValue } } func path(in rect: CGRect) -> Path { var path = Path() path.addArc(center: CGPoint(x: rect.width / 2.0, y: rect.height / 2.0), radius: min(rect.width, rect.height) / 2.0, startAngle: .degrees(startAngle), endAngle: .degrees(360 * progress), clockwise: false) return path.strokedPath(.init(lineWidth: thickness, lineCap: .round)) }//path }//RingShape
24.257143
79
0.547703
e9f9f783446151640e42a0efc30f0307a902e37a
404
// // MusicProvidersViewModel.swift // RxSonosLib // // Created by Stefan Renne on 30/04/2018. // Copyright © 2018 Uberweb. All rights reserved. // import UIKit import RxSwift import RxSonosLib class MusicProviderViewModel { private let service: MusicProvider init(service: MusicProvider) { self.service = service } var name: String { return service.name } }
17.565217
50
0.678218
29d1f91cb001a2d087198f7d4a91103255cbb747
1,401
// // DNACapsuleCVCell.swift // DNAKit // // Created by Shivani on 22/01/20. // Copyright © 2020 designSystem. All rights reserved. // import UIKit public class DNACapsuleCVCell: UICollectionViewCell { public var title: String? { get { return titleLabel.text } set { titleLabel.text = newValue } } override public var isSelected: Bool { didSet { containerView.backgroundColor = isSelected ? .systemBlue : .systemTeal // setNeedsDisplay() } } fileprivate let containerView: UIView = { let view = UIView() view.backgroundColor = .systemTeal view.layer.cornerRadius = 5.0 return view }() fileprivate let titleLabel: DNALabel = { let label = DNALabel(withType: Typography.h3(.product), text: "") label.textColor = Color.appWhite return label }() //MARK: - Initialize override public init(frame: CGRect) { super.init(frame: frame) setup() } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } //MARK: - Setup private func setup() { addSubview(containerView) containerView.fillSuperview() containerView.addSubview(titleLabel) titleLabel.centerInSuperview() } }
22.238095
82
0.584582
726f4e0d89b4b023dd6d12569f6a28559ca8b848
854
// // TimetableHeaderViewCell.swift // HTWDD // // Created by Mustafa Karademir on 01.10.19. // Copyright © 2019 HTW Dresden. All rights reserved. // import UIKit class TimetableHeaderViewCell: UITableViewCell { // MARK: - Outlets @IBOutlet weak var lblHeader: UILabel! @IBOutlet weak var lblSubheader: UILabel! override func awakeFromNib() { super.awakeFromNib() lblHeader.apply { $0.textColor = UIColor.htw.Label.primary } lblSubheader.apply { $0.textColor = UIColor.htw.Label.secondary } } } // MARK: - Loadable extension TimetableHeaderViewCell: FromNibLoadable { func setup(with model: TimetableHeader) { lblHeader.text = model.headerLocalized lblSubheader.text = model.subheaderLocalized } }
21.897436
54
0.629977
674fd1e6881e7b5e1d8d01b2135d1ef55b5e52b9
3,112
// // BackgroundRender.swift // TelegramContestBG // // Created by Alexander Graschenkov on 16.01.2021. // import UIKit import MetalKit class BGRenderView: MTKView { private var commandQueue: MTLCommandQueue! = nil private var display: BGDisplay! private let mutex = GAMutex() override init(frame frameRect: CGRect, device: MTLDevice?) { let d = device ?? MTLCreateSystemDefaultDevice()! super.init(frame: frameRect, device: d) configureWithDevice(d) setup() } required init(coder: NSCoder) { super.init(coder: coder) configureWithDevice(MTLCreateSystemDefaultDevice()!) setup() } private func configureWithDevice(_ device : MTLDevice) { clearColor = MTLClearColor.init(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0) framebufferOnly = true colorPixelFormat = .bgra8Unorm depthStencilPixelFormat = .invalid // Run with 4rx MSAA: sampleCount = 4 preferredFramesPerSecond = 60 isPaused = true enableSetNeedsDisplay = true self.device = device display = BGDisplay(view: self, device: device) delegate = self } override var device: MTLDevice! { didSet { super.device = device commandQueue = (self.device?.makeCommandQueue())! } } override func draw(_ rect: CGRect) { drawAll() } open func setup() { } func drawAll() { display.prepareDisplay() mutex.lock() guard let commandBuffer = commandQueue!.makeCommandBuffer(), let renderPassDescriptor = self.currentRenderPassDescriptor, let renderEncoder = commandBuffer.makeRenderCommandEncoder(descriptor: renderPassDescriptor) else { mutex.unlock() return } commandBuffer.addCompletedHandler { (_) in self.mutex.unlock() } display.display(renderEncoder: renderEncoder) renderEncoder.endEncoding() commandBuffer.present(self.currentDrawable!) commandBuffer.commit() } func update(metaballs: [Metaball]) { mutex.lock() defer { mutex.unlock() } display.update(metaballs: metaballs) setNeedsDisplay() } func update(gradient: Float? = nil, scale: Float? = nil) { mutex.lock() defer { mutex.unlock() } if let g = gradient { display.globalParams.gradient = g } if let s = scale { display.globalParams.scale = s } setNeedsDisplay() } } extension BGRenderView: MTKViewDelegate { func mtkView(_ view: MTKView, drawableSizeWillChange size: CGSize) { mutex.lock() defer { mutex.unlock() } (view as? BGRenderView)?.display.update(drawableSize: size) } func draw(in view: MTKView) { (view as? BGRenderView)?.drawAll() } }
25.096774
111
0.576478
0edb3f5f330f66f62fd8f96fd73ea0b88477e24a
390
// // MovieCell.swift // movieViewer // // Created by Jennifer Kwan on 1/18/16. // Copyright © 2016 Jennifer Kwan. All rights reserved. // import UIKit class MovieCell: UITableViewCell { @IBOutlet weak var titleLabel: UILabel! @IBOutlet weak var overviewLabel: UILabel! @IBOutlet weak var posterImage: UIImageView! @IBOutlet weak var posterView: UIView! }
18.571429
56
0.692308
feaba626e9bfb40511e51dc23af2eb4773138d70
773
// // RepoResultsViewCell.swift // GithubDemo // // Created by Zhipeng Mei on 2/4/16. // Copyright © 2016 codepath. All rights reserved. // import UIKit class RepoResultsViewCell: UITableViewCell { @IBOutlet weak var nameLabel: UILabel! @IBOutlet weak var descriptionLabel: UILabel! @IBOutlet weak var ownerAvatar: UIImageView! @IBOutlet weak var ownerHandleLabel: UILabel! @IBOutlet weak var starLabel: UILabel! @IBOutlet weak var forkCount: UILabel! override func awakeFromNib() { super.awakeFromNib() // Initialization code } override func setSelected(selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } }
24.15625
63
0.690815
1e25ed2405cd7dff701c64e7f0899a62e4c7f7df
288
// // Review.swift // MovieSwift // // Created by Thomas Ricouard on 16/06/2019. // Copyright © 2019 Thomas Ricouard. All rights reserved. // import Foundation import SwiftUI struct Review: Codable, Identifiable { let id: String let author: String let content: String }
16.941176
58
0.694444
385a40832509d8a2cae6ecf80c00a40ea7c460fc
33,371
// // QConversationCollectionView.swift // Qiscus // // Created by Ahmad Athaullah on 06/12/17. // Copyright © 2017 Ahmad Athaullah. All rights reserved. // import UIKit import MobileCoreServices import AVFoundation public class QConversationCollectionView: UICollectionView { public var room:QRoom? { didSet { var oldRoomId = "0" if let oldRoom = oldValue { // oldRoom.delegate = nil oldRoomId = oldRoom.id } if let r = room { self.comments = QComment.comments(onRoom: r.id) let rid = r.id if rid != oldRoomId { Qiscus.chatRooms[r.id] = r r.delegate = self r.subscribeRealtimeStatus() self.registerCell() if oldRoomId != "0" { self.unsubscribeEvent(roomId: oldRoomId) } self.subscribeEvent(roomId: rid) self.delegate = self self.dataSource = self var hardDelete = false if let softDelete = self.viewDelegate?.viewDelegate?(usingSoftDeleteOnView: self){ hardDelete = !softDelete } var predicate:NSPredicate? if hardDelete { predicate = NSPredicate(format: "statusRaw != %d AND statusRaw != %d", QCommentStatus.deleted.rawValue, QCommentStatus.deleting.rawValue) } QiscusBackgroundThread.async { if let rts = QRoom.threadSaveRoom(withId: rid){ var messages = rts.grouppedCommentsUID(filter: predicate) messages = self.checkHiddenMessage(messages: messages) DispatchQueue.main.async { self.messagesId = messages self.reloadData() } rts.resendPendingMessage() rts.redeletePendingDeletedMessage() rts.sync() } } } else { var hardDelete = false if let softDelete = self.viewDelegate?.viewDelegate?(usingSoftDeleteOnView: self){ hardDelete = !softDelete } var predicate:NSPredicate? if hardDelete { predicate = NSPredicate(format: "statusRaw != %d AND statusRaw != %d", QCommentStatus.deleted.rawValue, QCommentStatus.deleting.rawValue) } QiscusBackgroundThread.async { if let rts = QRoom.threadSaveRoom(withId: rid){ var messages = rts.grouppedCommentsUID(filter: predicate) messages = self.checkHiddenMessage(messages: messages) DispatchQueue.main.async { self.messagesId = messages self.reloadData() } rts.resendPendingMessage() rts.redeletePendingDeletedMessage() rts.sync() } } } }else{ self.messagesId = [[String]]() if oldRoomId != "0" { self.unsubscribeEvent(roomId: oldRoomId) } self.delegate = self self.dataSource = self self.reloadData() } } } public var comments: [QComment] = [] public var typingUsers = [String:QUser]() public var viewDelegate:QConversationViewDelegate? public var roomDelegate:QConversationViewRoomDelegate? public var cellDelegate:QConversationViewCellDelegate? public var configDelegate:QConversationViewConfigurationDelegate? public var typingUserTimer = [String:Timer]() public var processingTyping = false public var previewedTypingUsers = [String]() public var isPresence = false public var messagesId = [[String]](){ didSet{ DispatchQueue.main.async { if let r = self.room { self.comments = QComment.comments(onRoom: r.id) } if oldValue.count == 0 { self.layoutIfNeeded() self.scrollToBottom() } self.viewDelegate?.viewDelegate?(view: self, didLoadData: self.messagesId) } } } internal var loadingMore = false internal var targetIndexPath:IndexPath? internal var userTypingEmail: String = "" internal var isTyping: Bool = false internal var cacheCellSize: [String: CGSize] = [:] var isLastRowVisible: Bool = false // MARK: Audio Variable var audioPlayer: AVAudioPlayer? var audioTimer: Timer? var activeAudioCell: QCellAudio? var needToReload = false var onScrolling = false // Overrided method @objc public var registerCustomCell:(()->Void)? = nil var loadMoreControl = UIRefreshControl() public var targetComment:QComment? override public func draw(_ rect: CGRect) { self.scrollsToTop = false if self.viewWithTag(1721) == nil { self.loadMoreControl.addTarget(self, action: #selector(self.loadMore), for: UIControlEvents.valueChanged) self.loadMoreControl.tag = 1721 self.addSubview(self.loadMoreControl) } let layout = self.collectionViewLayout as? UICollectionViewFlowLayout layout?.sectionHeadersPinToVisibleBounds = true layout?.sectionFootersPinToVisibleBounds = true self.decelerationRate = UIScrollViewDecelerationRateNormal } open func registerCell(){ self.register(UINib(nibName: "QCellDeletedLeft",bundle: Qiscus.bundle), forCellWithReuseIdentifier: "cellDeletedLeft") self.register(UINib(nibName: "QCellDeletedRight",bundle: Qiscus.bundle), forCellWithReuseIdentifier: "cellDeletedRight") self.register(UINib(nibName: "QCellTypingLeft",bundle: Qiscus.bundle), forCellWithReuseIdentifier: "cellTypingLeft") self.register(UINib(nibName: "QChatEmptyFooter",bundle: Qiscus.bundle), forSupplementaryViewOfKind: UICollectionElementKindSectionFooter, withReuseIdentifier: "emptyFooter") self.register(UINib(nibName: "QChatEmptyHeaderCell",bundle: Qiscus.bundle), forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: "emptyHeader") self.register(UINib(nibName: "QChatHeaderCell",bundle: Qiscus.bundle), forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: "cellHeader") self.register(UINib(nibName: "QChatFooterLeft",bundle: Qiscus.bundle), forSupplementaryViewOfKind: UICollectionElementKindSectionFooter, withReuseIdentifier: "cellFooterLeft") self.register(UINib(nibName: "QChatFooterRight",bundle: Qiscus.bundle), forSupplementaryViewOfKind: UICollectionElementKindSectionFooter, withReuseIdentifier: "cellFooterRight") self.register(UINib(nibName: "QCellSystem",bundle: Qiscus.bundle), forCellWithReuseIdentifier: "cellSystem") self.register(UINib(nibName: "QCellDocLeft",bundle: Qiscus.bundle), forCellWithReuseIdentifier: "cellDocLeft") self.register(UINib(nibName: "QCellDocRight",bundle: Qiscus.bundle), forCellWithReuseIdentifier: "cellDocRight") self.register(UINib(nibName: "QCellCardLeft",bundle: Qiscus.bundle), forCellWithReuseIdentifier: "cellCardLeft") self.register(UINib(nibName: "QCellCardRight",bundle: Qiscus.bundle), forCellWithReuseIdentifier: "cellCardRight") self.register(UINib(nibName: "QCellTextLeft",bundle: Qiscus.bundle), forCellWithReuseIdentifier: "cellTextLeft") self.register(UINib(nibName: "QCellPostbackLeft",bundle: Qiscus.bundle), forCellWithReuseIdentifier: "cellPostbackLeft") self.register(UINib(nibName: "QCellTextRight",bundle: Qiscus.bundle), forCellWithReuseIdentifier: "cellTextRight") self.register(UINib(nibName: "QCellMediaLeft",bundle: Qiscus.bundle), forCellWithReuseIdentifier: "cellMediaLeft") self.register(UINib(nibName: "QCellMediaRight",bundle: Qiscus.bundle), forCellWithReuseIdentifier: "cellMediaRight") self.register(UINib(nibName: "QCellAudioLeft",bundle: Qiscus.bundle), forCellWithReuseIdentifier: "cellAudioLeft") self.register(UINib(nibName: "QCellAudioRight",bundle: Qiscus.bundle), forCellWithReuseIdentifier: "cellAudioRight") self.register(UINib(nibName: "QCellFileLeft",bundle: Qiscus.bundle), forCellWithReuseIdentifier: "cellFileLeft") self.register(UINib(nibName: "QCellFileRight",bundle: Qiscus.bundle), forCellWithReuseIdentifier: "cellFileRight") self.register(UINib(nibName: "QCellContactRight",bundle: Qiscus.bundle), forCellWithReuseIdentifier: "cellContactRight") self.register(UINib(nibName: "QCellContactLeft",bundle: Qiscus.bundle), forCellWithReuseIdentifier: "cellContactLeft") self.register(UINib(nibName: "QCellLocationRight",bundle: Qiscus.bundle), forCellWithReuseIdentifier: "cellLocationRight") self.register(UINib(nibName: "QCellLocationLeft",bundle: Qiscus.bundle), forCellWithReuseIdentifier: "cellLocationLeft") self.register(UINib(nibName: "QCellCarousel",bundle: Qiscus.bundle), forCellWithReuseIdentifier: "cellCarousel") self.registerCustomCell?() } public func subscribeEvent(roomId: String){ let center: NotificationCenter = NotificationCenter.default var usingTypingCell = false if let config = self.configDelegate?.configDelegate?(usingTpingCellIndicator: self){ usingTypingCell = config } if usingTypingCell { center.addObserver(self, selector: #selector(QConversationCollectionView.userTyping(_:)), name: QiscusNotification.USER_TYPING(onRoom: roomId), object: nil) } center.addObserver(self, selector: #selector(QConversationCollectionView.newCommentNotif(_:)), name: QiscusNotification.ROOM_CHANGE(onRoom: roomId), object: nil) center.addObserver(self, selector: #selector(QConversationCollectionView.messageCleared(_:)), name: QiscusNotification.ROOM_CLEARMESSAGES(onRoom: roomId), object: nil) center.addObserver(self, selector: #selector(QConversationCollectionView.commentDeleted(_:)), name: QiscusNotification.COMMENT_DELETE(onRoom: roomId), object: nil) } public func unsubscribeEvent(roomId:String){ let center: NotificationCenter = NotificationCenter.default var usingTypingCell = false if let config = self.configDelegate?.configDelegate?(usingTpingCellIndicator: self){ usingTypingCell = config } if usingTypingCell { center.removeObserver(self, name: QiscusNotification.USER_TYPING(onRoom: roomId), object: nil) } center.removeObserver(self, name: QiscusNotification.ROOM_CHANGE(onRoom: roomId), object: nil) center.removeObserver(self, name: QiscusNotification.ROOM_CLEARMESSAGES(onRoom: roomId), object: nil) center.removeObserver(self, name: QiscusNotification.COMMENT_DELETE(onRoom: roomId), object: nil) } // MARK: - Event handler open func onDeleteComment(room: QRoom){ let rid = room.id var hardDelete = false if let softDelete = self.viewDelegate?.viewDelegate?(usingSoftDeleteOnView: self){ hardDelete = !softDelete } var predicate:NSPredicate? if hardDelete { predicate = NSPredicate(format: "statusRaw != %d AND statusRaw != %d", QCommentStatus.deleted.rawValue, QCommentStatus.deleting.rawValue) } QiscusBackgroundThread.async { if let rts = QRoom.threadSaveRoom(withId: rid){ var messages = rts.grouppedCommentsUID(filter: predicate) messages = self.checkHiddenMessage(messages: messages) DispatchQueue.main.async { self.messagesId = messages self.reloadData() } } } } open func gotNewComment(comment: QComment, room:QRoom) { let rid = room.id var hardDelete = false if let softDelete = self.viewDelegate?.viewDelegate?(usingSoftDeleteOnView: self){ hardDelete = !softDelete } var predicate:NSPredicate? if hardDelete { predicate = NSPredicate(format: "statusRaw != %d AND statusRaw != %d", QCommentStatus.deleted.rawValue, QCommentStatus.deleting.rawValue) } QiscusBackgroundThread.async { if let rts = QRoom.threadSaveRoom(withId: rid){ var messages = rts.grouppedCommentsUID(filter: predicate) messages = self.checkHiddenMessage(messages: messages) var section = 0 var changed = false if messages.count != self.messagesId.count { changed = true }else{ var i = 0 for group in messages { if group.count != self.messagesId[i].count { changed = true break } i += 1 } } if changed { DispatchQueue.main.async { if comment.isInvalidated {return} if comment.senderEmail == Qiscus.client.email || !self.isLastRowVisible { self.layoutIfNeeded() self.scrollToBottom(true) } else { self.messagesId = messages self.reloadData() if self.isLastRowVisible {self.scrollToBottom(true)} } } } } } } open func userTypingChanged(userEmail: String, typing:Bool){ self.processingTyping = true self.userTypingEmail = userEmail self.isTyping = typing if self.messagesId.count <= 0 { return } NSObject.cancelPreviousPerformRequests(withTarget: self, selector: #selector(self.proccessTyping), object: nil) self.perform(#selector(self.proccessTyping), with: nil, afterDelay: 0.5) } @objc private func proccessTyping() { let section = self.messagesId.count - 1 QiscusBackgroundThread.sync { if !isTyping { if self.typingUsers[self.userTypingEmail] != nil { self.typingUsers[self.userTypingEmail] = nil if self.typingUsers.count > 0 { let typingIndexPath = IndexPath(item: 0, section: section + 1) DispatchQueue.main.async { self.reloadItems(at: [typingIndexPath]) } }else{ DispatchQueue.main.async { if !self.isHidden { self.performBatchUpdates({ let indexSet = IndexSet(integer: section + 1) if self.numberOfSections > (section + 1) { self.deleteSections(indexSet) } }, completion: { (_) in if self.isLastRowVisible{ self.scrollToBottom() } }) } } } if let timer = self.typingUserTimer[self.userTypingEmail] { timer.invalidate() self.typingUserTimer[self.userTypingEmail] = nil } } }else{ let typingIndexPath = IndexPath(item: 0, section: section + 1) if self.typingUsers[self.userTypingEmail] == nil { if self.typingUsers.count > 0 { DispatchQueue.main.async { if let user = QUser.user(withEmail: self.userTypingEmail) { self.typingUsers[self.userTypingEmail] = user self.reloadItems(at: [typingIndexPath]) } } }else{ DispatchQueue.main.async { if let user = QUser.user(withEmail: self.userTypingEmail) { self.typingUsers[self.userTypingEmail] = user if !self.isHidden { let indexSet = IndexSet(integer: section + 1) self.performBatchUpdates({ self.insertSections(indexSet) self.insertItems(at: [typingIndexPath]) }, completion: { (_) in if self.isLastRowVisible{ self.scrollToBottom() } }) } } } } } if let timer = self.typingUserTimer[self.userTypingEmail] { timer.invalidate() } DispatchQueue.main.async { if let user = QUser.user(withEmail: self.userTypingEmail) { self.typingUserTimer[self.userTypingEmail] = Timer.scheduledTimer(timeInterval: 3.0, target: self, selector: #selector(QConversationCollectionView.publishStopTyping(timer:)), userInfo: user, repeats: false) } } } } self.processingTyping = false } // MARK: - Notification Listener @objc private func userTyping(_ notification: Notification){ var usingCellTyping = false if let config = self.configDelegate?.configDelegate?(usingTpingCellIndicator: self){ usingCellTyping = config } if !usingCellTyping { return } if let userInfo = notification.userInfo { guard let user = userInfo["user"] as? QUser else { return } guard let typing = userInfo["typing"] as? Bool else { return } guard let room = userInfo["room"] as? QRoom else {return} guard let currentRoom = self.room else {return} if room.isInvalidated || user.isInvalidated || currentRoom.isInvalidated{ return } let userEmail = user.email let roomId = room.id if currentRoom.id != roomId { return } if self.processingTyping { return } self.userTypingChanged(userEmail: userEmail, typing: typing) } } @objc private func newCommentNotif(_ notification: Notification){ if let userInfo = notification.userInfo { guard let property = userInfo["property"] as? QRoomProperty else {return} if property == .lastComment { guard let room = userInfo["room"] as? QRoom else {return} guard let comment = room.lastComment else { if room.isInvalidated { return } self.roomDelegate?.roomDelegate?(gotFirstComment: room) return } if room.isInvalidated { return } self.gotNewComment(comment: comment, room: room) } } } @objc private func messageCleared(_ notification: Notification){ if let userInfo = notification.userInfo { let room = userInfo["room"] as! QRoom if room.isInvalidated { return } if let currentRoom = self.room { if !currentRoom.isInvalidated { if currentRoom.id == room.id { self.messagesId = [[String]]() self.reloadData() } } } } } @objc private func commentDeleted(_ notification: Notification) { if let userInfo = notification.userInfo { let room = userInfo["room"] as! QRoom if let currentRoom = self.room { if !currentRoom.isInvalidated && !room.isInvalidated{ if currentRoom.id == room.id { self.onDeleteComment(room: room) } } } } } // MARK: - Internal Method @objc private func publishStopTyping(timer:Timer){ if let user = timer.userInfo as? QUser { if let room = self.room { QiscusNotification.publish(userTyping: user, room: room, typing: false ) } } } // MARK: public Method func scrollToBottom(_ animated:Bool = false){ if self.room != nil { if self.messagesId.count > 0 { let lastSection = self.numberOfSections - 1 let lastItem = self.numberOfItems(inSection: lastSection) - 1 if lastSection >= 0 && lastItem >= 0 { let indexPath = IndexPath(item: lastItem, section: lastSection) self.layoutIfNeeded() self.scrollToItem(at: indexPath, at: .bottom, animated: animated) } } } } open func cellHeightForComment (comment:QComment, defaultHeight height:CGFloat, firstInSection first:Bool)->CGFloat{ var retHeight = height if comment.status == .deleted { var text = "" let isSelf = comment.senderEmail == Qiscus.client.email if let config = self.configDelegate?.configDelegate?(deletedMessageText: self, selfMessage: isSelf){ text = config }else if isSelf { text = "🚫 You deleted this message." }else{ text = "🚫 This message was deleted." } let attributedText = NSMutableAttributedString(string: text) let foregroundColorAttributeName = QiscusColorConfiguration.sharedInstance.leftBaloonTextColor let textAttribute:[NSAttributedStringKey: Any] = [ NSAttributedStringKey.foregroundColor: foregroundColorAttributeName, NSAttributedStringKey.font: Qiscus.style.chatFont.italic() ] let allRange = (text as NSString).range(of: text) attributedText.addAttributes(textAttribute, range: allRange) let maxWidth = (QiscusHelper.screenWidth() * 0.70) - 8 let textView = UITextView() textView.attributedText = attributedText let size = textView.sizeThatFits(CGSize(width: maxWidth, height: CGFloat.greatestFiniteMagnitude)) retHeight = size.height + 14 }else{ switch comment.type { case .card, .contact : break case .carousel : retHeight += 4 break case .video, .image : if retHeight > 0 { retHeight += 151 ; }else{ retHeight = 140 } break case .audio : retHeight = 83 ; break case .file : retHeight = 67 ; break case .reply : retHeight += 88 ; break case .system : retHeight += 5 ; break case .text : retHeight += 15 ; break case .document : retHeight += 7; break default : retHeight += 20 ; break } } if (comment.type != .system && first) { var showUserName = true if let user = comment.sender { if let hidden = self.configDelegate?.configDelegate?(hideUserNameLabel: self, forUser: user){ showUserName = !hidden } } if showUserName { retHeight += 20 } } return retHeight } @objc func loadMore(){ if let room = self.room { let id = room.id self.loadMoreComment(roomId: id) } } func loadMoreComment(roomId:String){ QiscusBackgroundThread.async { if self.loadingMore { return } self.loadingMore = true if let r = QRoom.threadSaveRoom(withId: roomId){ if r.canLoadMore{ r.loadMore() }else{ self.loadingMore = false DispatchQueue.main.async { self.loadMoreControl.endRefreshing() self.loadMoreControl.removeFromSuperview() } } }else{ self.loadingMore = false DispatchQueue.main.async { self.loadMoreControl.endRefreshing() } } } } func scrollToComment(comment:QComment){ if let room = self.room { let roomId = room.id let uniqueId = comment.uniqueId QiscusBackgroundThread.async { var found = false var section = 0 var item = 0 for groupUid in self.messagesId { item = 0 for uid in groupUid { if uid == uniqueId { found = true break } if !found { item += 1 } } if !found { section += 1 }else{ break } } if found { self.targetIndexPath = IndexPath(item: item, section: section) DispatchQueue.main.async { self.layoutIfNeeded() self.scrollToItem(at: self.targetIndexPath!, at: .top, animated: true) } } } } } override public func reloadData() { super.reloadData() } public func refreshData(withCompletion completion: (()->Void)? = nil){ if let room = self.room { let rid = room.id // if self.onScrolling { // self.needToReload = true // return // } var hardDelete = false if let softDelete = self.viewDelegate?.viewDelegate?(usingSoftDeleteOnView: self){ hardDelete = !softDelete } var predicate:NSPredicate? if hardDelete { predicate = NSPredicate(format: "statusRaw != %d AND statusRaw != %d", QCommentStatus.deleted.rawValue, QCommentStatus.deleting.rawValue) } QiscusBackgroundThread.async { if let rts = QRoom.threadSaveRoom(withId: rid){ var messages = rts.grouppedCommentsUID(filter: predicate) messages = self.checkHiddenMessage(messages: messages) DispatchQueue.main.async { self.messagesId = messages self.reloadData() if let onFinish = completion { // self.needToReload = false onFinish() } } } } } } internal func checkMessagePos(inGroup group:[String]){ var item = 0 for i in group { var position = QCellPosition.middle if group.count == 1 { position = .single }else{ if item == 0 { position = .first }else if item == group.count - 1 { position = .last } } if let comment = QComment.threadSaveComment(withUniqueId: i){ comment.updateCellPos(cellPos: position) } item += 1 } } internal func checkHiddenMessage(messages:[[String]])->[[String]]{ var retVal = messages if let delegate = self.viewDelegate { var hiddenIndexPaths = [IndexPath]() var groupCheck = [Int]() var section = 0 for s in retVal { var item = 0 for i in s { if let comment = QComment.threadSaveComment(withUniqueId: i){ if let val = delegate.viewDelegate?(view: self, hideCellWith: comment){ if val { hiddenIndexPaths.append(IndexPath(item: item, section: section)) comment.read(check: false) if !groupCheck.contains(section) { groupCheck.append(section) } } } } item += 1 } section += 1 } for indexPath in hiddenIndexPaths.reversed(){ retVal[indexPath.section].remove(at: indexPath.item) } for group in groupCheck.reversed(){ if retVal[group].count == 0 { retVal.remove(at: group) } } var newGroup = [[String]]() var prev:QComment? var s = 0 for group in retVal { if let first = QComment.threadSaveComment(withUniqueId: group.first!) { if prev == nil { newGroup.append(group) prev = first }else{ if prev!.date == first.date && prev!.senderEmail == first.senderEmail && first.type != .system { for uid in group { newGroup[s].append(uid) } }else{ s += 1 newGroup.append(group) prev = first } } } } for group in newGroup { self.checkMessagePos(inGroup: group) } return newGroup }else{ return retVal } } func loadData(){ if let r = self.room { let rid = r.id var hardDelete = false if let softDelete = self.viewDelegate?.viewDelegate?(usingSoftDeleteOnView: self){ hardDelete = !softDelete } var predicate:NSPredicate? if hardDelete { predicate = NSPredicate(format: "statusRaw != %d AND statusRaw != %d AND statusRaw != %d", QCommentStatus.deleted.rawValue, QCommentStatus.deleting.rawValue) } QiscusBackgroundThread.async { if let rts = QRoom.threadSaveRoom(withId: rid){ rts.loadData(onSuccess: { (result) in var messages = result.grouppedCommentsUID(filter: predicate) messages = self.checkHiddenMessage(messages: messages) DispatchQueue.main.async { self.messagesId = messages self.reloadData() } }, onError: { (error) in Qiscus.printLog(text: "fail to load data on room") }) } } } } }
44.2
230
0.516976
5d1cb5dbe358edadaffc3e3b1c14bb7c6b6aa8b2
4,805
// // SBAMedicationFollowupTask.swift // DataTracking (iOS) // // Copyright © 2019 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 Foundation /// A wrapper for displaying a single step of the medication tracking. protocol SBAMedicationFollowupTask : RSDTask, RSDStepNavigator, RSDTrackingTask { /// The single step to display. var trackingStep: RSDStep { get } /// The medication tracker that holds the pointer to the result. var medicationTracker: SBAMedicationTrackingStepNavigator { get } /// Set up the follow up task. Called in `setupTask()` after setting up the medication /// tracker. func setupFollowupTask() } extension SBAMedicationFollowupTask { // MARK: `RSDTask` public var stepNavigator: RSDStepNavigator { return self } public func instantiateTaskResult() -> RSDTaskResult { return RSDTaskResultObject(identifier: self.identifier) } public var copyright: String? { return nil } public var asyncActions: [RSDAsyncActionConfiguration]? { return nil } public func validate() throws { } // MARK: RSDStepNavigator public func step(with identifier: String) -> RSDStep? { guard identifier == trackingStep.identifier else { return nil } return trackingStep } /// Never exit after answering meds. public func shouldExit(after step: RSDStep?, with result: RSDTaskResult) -> Bool { return false } /// Only one step. public func hasStep(before step: RSDStep, with result: RSDTaskResult) -> Bool { return false } /// Return the logging step. public func step(after step: RSDStep?, with result: inout RSDTaskResult) -> (step: RSDStep?, direction: RSDStepDirection) { // Update the tracker medicationTracker.updateInMemoryResult(from: &result, using: step) // Check if there is a step after the input step. That value is *always* the tracking // step (if anything should be shown). guard self.hasStep(after: step, with: result) else { return (nil, .forward) } return (self.trackingStep, .forward) } /// Only one step. public func step(before step: RSDStep, with result: inout RSDTaskResult) -> RSDStep? { return nil } /// Progress is not used. public func progress(for step: RSDStep, with result: RSDTaskResult?) -> (current: Int, total: Int, isEstimated: Bool)? { return nil } // MARK: `RSDTrackingTask` /// Build the task data for this task. public func taskData(for taskResult: RSDTaskResult) -> RSDTaskData? { return self.medicationTracker.taskData(for: taskResult) } /// Set up the previous client data. public func setupTask(with data: RSDTaskData?, for path: RSDTaskPathComponent) { self.medicationTracker.setupTask(with: data, for: path) setupFollowupTask() } /// Not used. Always return `false`. public func shouldSkipStep(_ step: RSDStep) -> (shouldSkip: Bool, stepResult: RSDResult?) { return (false, nil) } }
36.679389
127
0.691988
e094fdc833c37171d806b77b6f65897b9c6a682a
2,160
// // Mastering RxSwift // Copyright (c) KxCoding <[email protected]> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import UIKit class BindingCocoaTouchViewController: UIViewController { @IBOutlet weak var valueLabel: UILabel! @IBOutlet weak var valueField: UITextField! override func viewDidLoad() { super.viewDidLoad() valueLabel.text = "" valueField.delegate = self valueField.becomeFirstResponder() } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) valueField.resignFirstResponder() } } extension BindingCocoaTouchViewController: UITextFieldDelegate { func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { guard let currentText = textField.text else { return true } let finalText = (currentText as NSString).replacingCharacters(in: range, with: string) valueLabel.text = finalText return true } }
36
129
0.705093
dd5eee04ab1aca7df20c93fd79a78a977c6c99db
351
// // SlackChannel.swift // Assistant // // Created by Bananos on 5/14/16. // Copyright © 2016 Bananos. All rights reserved. // import Foundation struct SlackChannel { let id: String let name: String init(json: [String: AnyObject]) { id = json["id"] as? String ?? "" name = json["name"] as? String ?? "" } }
17.55
50
0.578348
e4b2ebc37aff19c8544a51c8f44871e3b1169e60
9,919
// // AcknowledgementsTableViewController.swift // SwiftyAcknowledgements // // Created by Mathias Nagler on 08.09.15. // Copyright (c) 2015 Mathias Nagler. All rights reserved. // import UIKit // MARK: - AcknowledgementsTableViewController open class AcknowledgementsTableViewController: UITableViewController { // MARK: Properties /// The text to be displayed in the **UITableView**'s **tableHeader**, if any. @IBInspectable open var headerText: String? { didSet { headerView.text = headerText updateHeaderFooterViews() } } /// The text to be displayed in the **UITableView**'s **tableFooter**, if any. @IBInspectable open var footerText: String? { didSet { footerView.text = footerText updateHeaderFooterViews() } } /// The font size to be used for the **UITableView**'s **tableHeader**. Defaults to the size of **UIFontTextStyleSubheadline** @IBInspectable open var headerFontSize: CGFloat = UIFontDescriptor.preferredFontSize(withTextStyle: UIFont.TextStyle.subheadline.rawValue) { didSet { headerView.fontSize = headerFontSize updateHeaderFooterViews() } } /// The font size to be used for the **UITableView**'s **tableFooter**. Defaults to the size of **UIFontTextStyleSubheadline** @IBInspectable open var footerFontSize: CGFloat = UIFontDescriptor.preferredFontSize(withTextStyle: UIFont.TextStyle.subheadline.rawValue) { didSet { footerView.fontSize = footerFontSize updateHeaderFooterViews() } } /// The font size to be used for the **UITableView**'s cells. Defaults to the size of **UIFontTextStyleBody** @IBInspectable open var detailFontSize: CGFloat = UIFontDescriptor.preferredFontSize(withTextStyle: UIFont.TextStyle.body.rawValue) /// The name of the plist containing the acknowledgements, defaults to **Acknowledgements**. @IBInspectable open var acknowledgementsPlistName = "Acknowledgements" private lazy var _acknowledgements: [Acknowledgement] = { guard let acknowledgementsPlistPath = Bundle.main.path( forResource: self.acknowledgementsPlistName, ofType: "plist") else { return [Acknowledgement]() } return Acknowledgement.acknowledgements(fromPlistAt: acknowledgementsPlistPath) }() /// The acknowledgements that are displayed by the TableViewController. The array is initialized with the contents of the /// plist with *acknowledgementPlistName*. To display custom acknowledements add them to the array. The tableView will /// reload its contents after any modification to the array. open var acknowledgements: [Acknowledgement] { set { _acknowledgements = sortingClosure != nil ? newValue.sorted(by: sortingClosure!) : newValue tableView.reloadData() } get { return _acknowledgements } } /// Closure type used for sorting acknowledgements. /// - Parameter lhs: acknowledgement *lhs* /// - Parameter rhs: acknowledgement *rhs* /// - Returns: A boolean indicating wether *lhs* is ordered before *rhs* public typealias SortingClosure = ((Acknowledgement, Acknowledgement) -> Bool) /// A closure used to sort the *acknowledgements* array, defaults to a closure /// that sorts alphabetically. The sorting closure can be changed any time and the /// *acknowledgements* array will then be re-sorted and afterwards the tableView /// will reload its contents. open var sortingClosure: SortingClosure? = { (left, right) in var comparsion = left.title.compare(right.title) return comparsion == .orderedAscending } { didSet { if let sortingClosure = sortingClosure { _acknowledgements = _acknowledgements.sorted(by: sortingClosure) } } } private lazy var headerView: HeaderFooterView = { let headerView = HeaderFooterView() headerView.fontSize = self.headerFontSize return headerView }() private lazy var footerView: HeaderFooterView = { let footerView = HeaderFooterView() footerView.fontSize = self.footerFontSize return footerView }() // MARK: Initialization public init(acknowledgementsPlistPath: String? = nil) { super.init(style: .grouped) } override internal init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) } required public init?(coder aDecoder: NSCoder) { super.init(style: .grouped) } // MARK: UIViewController overrides override open func viewDidLoad() { super.viewDidLoad() tableView.register(UITableViewCell.self, forCellReuseIdentifier: UITableViewCell.reuseId) headerView.bounds = CGRect(x: 0, y: 0, width: view.bounds.width, height: 50) tableView.tableHeaderView = headerView footerView.bounds = CGRect(x: 0, y: 0, width: view.bounds.width, height: 50) tableView.tableFooterView = footerView } override open func viewWillAppear(_ animated: Bool) { if title == nil { title = "Acknowledgements" } super.viewWillAppear(animated) } override open func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) { super.viewWillTransition(to: size, with: coordinator) updateHeaderFooterViews(forWidth: size.width) } // MARK: UITableViewDataSource override open func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: UITableViewCell.reuseId, for: indexPath) cell.textLabel?.text = acknowledgements[indexPath.row].title cell.accessoryType = .disclosureIndicator return cell } override open func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return acknowledgements.count } // MARK: UITableViewDelegate override open func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let detailViewController = AcknowledgementViewController(acknowledgement: acknowledgements[indexPath.row]) detailViewController.fontSize = detailFontSize show(detailViewController, sender: self) } // MARK: Private methods private func updateHeaderFooterViews() { updateHeaderFooterViews(forWidth: view.bounds.width) } private func updateHeaderFooterViews(forWidth width: CGFloat) { let headerWidthConstraint = NSLayoutConstraint(item: headerView, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: width) headerWidthConstraint.priority = UILayoutPriority(rawValue: 999) headerWidthConstraint.isActive = true let headerHeight = headerView.systemLayoutSizeFitting(UIView.layoutFittingCompressedSize).height headerWidthConstraint.isActive = false headerView.frame = CGRect(x: 0, y: 0, width: width, height: headerHeight) tableView.tableHeaderView = headerView let footerWidthConstraint = NSLayoutConstraint(item: footerView, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: width) footerWidthConstraint.priority = UILayoutPriority(rawValue: 999) footerWidthConstraint.isActive = true let footerHeight = footerView.systemLayoutSizeFitting(UIView.layoutFittingCompressedSize).height footerWidthConstraint.isActive = false footerView.frame = CGRect(x: 0, y: 0, width: width, height: footerHeight) tableView.tableFooterView = footerView } } private extension UITableViewCell { static var reuseId: String { return String(describing: self) } } // MARK: - HeaderFooterView private class HeaderFooterView: UIView { // MARK: Properties var fontSize: CGFloat { get { return label.font.pointSize } set { label.font = UIFont.systemFont(ofSize: newValue) } } var text: String? { get { return label.text } set { label.text = newValue } } private lazy var label: UILabel = { let label = UILabel() label.translatesAutoresizingMaskIntoConstraints = false label.textAlignment = .center label.numberOfLines = 0 label.textColor = .gray label.font = UIFont.systemFont(ofSize: 12) return label }() // MARK: Initialization override init(frame: CGRect) { super.init(frame: frame) commonInit() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) commonInit() } private func commonInit() { addSubview(label) self.addConstraint(NSLayoutConstraint(item: self, attribute: .leading, relatedBy: .equal, toItem: label, attribute: .leading, multiplier: 1, constant: -16)) self.addConstraint(NSLayoutConstraint(item: self, attribute: .trailing, relatedBy: .equal, toItem: label, attribute: .trailing, multiplier: 1, constant: 16)) self.addConstraint(NSLayoutConstraint(item: self, attribute: .top, relatedBy: .equal, toItem: label, attribute: .top, multiplier: 1, constant: -16)) self.addConstraint(NSLayoutConstraint(item: self, attribute: .bottom, relatedBy: .equal, toItem: label, attribute: .bottom, multiplier: 1, constant: 16)) } }
38.15
183
0.67033
fe5376664ef13dc204403b3c244cbc459f6d1bfc
2,703
// // GKTableViewController.swift // Contacts // // Created by Tirupati Balan on 20/04/19. // Copyright © 2019 Tirupati Balan. All rights reserved. // import Foundation class GKTableViewController : UITableViewController, UIViewControllerProtocol, StoryboardIdentifiable { var activityIndicatorView = UIActivityIndicatorView(style: .gray) override func viewDidLoad() { super.viewDidLoad() self.activityIndicatorView.translatesAutoresizingMaskIntoConstraints = false view.addSubview(activityIndicatorView) self.activityIndicatorView.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true self.activityIndicatorView.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true } override var preferredStatusBarStyle: UIStatusBarStyle { return .lightContent } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } func startViewAnimation() { DispatchQueue.main.async { self.activityIndicatorView.startAnimating() } } func stopViewAnimation() { DispatchQueue.main.async { self.activityIndicatorView.stopAnimating() } } func loadData() { self.startViewAnimation() } @objc func handleRefresh(_ refreshControl: UIRefreshControl) { } func showAlertWithTitleAndMessage(title: String, message: String, handler: ((UIAlertAction) -> Swift.Void)? = nil) { DispatchQueue.main.async { let alert = UIAlertController.init(title: title, message: message, preferredStyle: .alert) alert.addAction(UIAlertAction(title: "OK", style: UIAlertAction.Style.default, handler: handler)) self.present(alert, animated: true, completion: { }) } } func presentController<T>(_ vc: T) { if let vc = vc as? UIViewController { present(vc, animated: true) { } } } func pushController<T>(_ vc: T) { if let vc = vc as? UIViewController { self.navigationController?.pushViewController(vc, animated: true) } } func didFailedResponse<T>(_ error : T) { self.stopViewAnimation() if let error = error as? GKError { self.showAlertWithTitleAndMessage(title: "Error!", message: error.localizedDescription) } } func didSuccessfulResponse<T>(_ response: T) { self.stopViewAnimation() } }
29.380435
120
0.63448
64c2c8566f936a4ce692a43e41575461a2210ebb
2,644
// // GameOverScene.swift // SpaceSwift // // Created by Gerrit Grunwald on 04.01.20. // Copyright © 2020 Gerrit Grunwald. All rights reserved. // import SpriteKit import GameplayKit import AVKit class GameOverScene: SKScene { private let notificationCenter : NotificationCenter = .default private var background : SKSpriteNode? private var scoreLabel : SKLabelNode? private let gameOverSoundAction : SKAction = SKAction.playSoundFileNamed("gameover.wav", waitForCompletion: false) override func didMove(to view: SKView) { // Background image self.background = self.childNode(withName: "//background") as? SKSpriteNode if let background = self.background { background.texture = SKTexture(imageNamed: "gameover.jpg") background.anchorPoint = CGPoint(x: 0.5, y: 0.5) background.position = CGPoint(x: 0, y: 0) } // Get label node from scene and store it for use later self.scoreLabel = self.childNode(withName: "//scoreLabel") as? SKLabelNode if let scoreLabel = self.scoreLabel { scoreLabel.alpha = 0.0 scoreLabel.zPosition = 5 if let map = userData as NSMutableDictionary? { if let score = map["score"] as? Int { scoreLabel.text = String(score) } } scoreLabel.run(SKAction.fadeIn(withDuration: 1.0)) } run(gameOverSoundAction) let sequence = SKAction.sequence([SKAction.wait(forDuration: 5), SKAction.run({ () -> Void in self.notificationCenter.post(name: .moveToStartScene, object: nil) })]); run(sequence) } func touchDown(atPoint pos : CGPoint) { } func touchMoved(toPoint pos : CGPoint) { } func touchUp(atPoint pos : CGPoint) { } override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { for t in touches { self.touchDown(atPoint: t.location(in: self)) } } override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) { for t in touches { self.touchMoved(toPoint: t.location(in: self)) } } override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) { for t in touches { self.touchUp(atPoint: t.location(in: self)) } } override func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent?) { for t in touches { self.touchUp(atPoint: t.location(in: self)) } } }
33.05
128
0.600983
f4819f26102dd601181776c816441835614363f6
1,420
// // AppDelegate.swift // ZoomController // // Created by Maxim Komlev on 4/24/20. // Copyright © 2020 Maxim Komlev. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. return true } // MARK: UISceneSession Lifecycle func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration { // Called when a new scene session is being created. // Use this method to select a configuration to create the new scene with. return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role) } func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) { // Called when the user discards a scene session. // If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions. // Use this method to release any resources that were specific to the discarded scenes, as they will not return. } }
39.444444
179
0.749296
28fd99f69b5ada0f45389b2b9fa9a14315536a49
13,047
// // import Foundation public class PublicClass { internal typealias InternalArray = [PublicClass.InternalStruct] internal typealias InternalStructTypeDef = PublicClass.InternalStruct internal typealias StringToInternalStructMap = [String: PublicClass.InternalStruct] internal var internalStructProperty: PublicClass.InternalStruct { get { let c_result_handle = smoke_PublicClass_internalStructProperty_get(self.c_instance) return moveFromCType(c_result_handle) } set { let c_value = moveToCType(newValue) smoke_PublicClass_internalStructProperty_set(self.c_instance, c_value.ref) } } public internal(set) var internalSetterProperty: String { get { let c_result_handle = smoke_PublicClass_internalSetterProperty_get(self.c_instance) return moveFromCType(c_result_handle) } set { let c_value = moveToCType(newValue) smoke_PublicClass_internalSetterProperty_set(self.c_instance, c_value.ref) } } let c_instance : _baseRef init(cPublicClass: _baseRef) { guard cPublicClass != 0 else { fatalError("Nullptr value is not supported for initializers") } c_instance = cPublicClass } deinit { smoke_PublicClass_remove_swift_object_from_wrapper_cache(c_instance) smoke_PublicClass_release_handle(c_instance) } internal enum InternalEnum : UInt32, CaseIterable, Codable { case foo case bar } internal struct InternalStruct { internal var stringField: String internal init(stringField: String) { self.stringField = stringField } internal init(cHandle: _baseRef) { stringField = moveFromCType(smoke_PublicClass_InternalStruct_stringField_get(cHandle)) } } public struct PublicStruct { internal var internalField: PublicClass.InternalStruct internal init(internalField: PublicClass.InternalStruct) { self.internalField = internalField } internal init(cHandle: _baseRef) { internalField = moveFromCType(smoke_PublicClass_PublicStruct_internalField_get(cHandle)) } } public struct PublicStructWithInternalDefaults { internal var internalField: String public var publicField: Float public init(publicField: Float) { self.publicField = publicField self.internalField = "foo" } internal init(internalField: String = "foo", publicField: Float) { self.internalField = internalField self.publicField = publicField } internal init(cHandle: _baseRef) { internalField = moveFromCType(smoke_PublicClass_PublicStructWithInternalDefaults_internalField_get(cHandle)) publicField = moveFromCType(smoke_PublicClass_PublicStructWithInternalDefaults_publicField_get(cHandle)) } } internal func internalMethod(input: PublicClass.InternalStruct) -> PublicClass.InternalStructTypeDef { let c_input = moveToCType(input) let c_result_handle = smoke_PublicClass_internalMethod(self.c_instance, c_input.ref) return moveFromCType(c_result_handle) } } internal func getRef(_ ref: PublicClass?, owning: Bool = true) -> RefHolder { guard let c_handle = ref?.c_instance else { return RefHolder(0) } let handle_copy = smoke_PublicClass_copy_handle(c_handle) return owning ? RefHolder(ref: handle_copy, release: smoke_PublicClass_release_handle) : RefHolder(handle_copy) } extension PublicClass: NativeBase { /// :nodoc: var c_handle: _baseRef { return c_instance } } extension PublicClass: Hashable { /// :nodoc: public static func == (lhs: PublicClass, rhs: PublicClass) -> Bool { return lhs.c_handle == rhs.c_handle } /// :nodoc: public func hash(into hasher: inout Hasher) { hasher.combine(c_handle) } } internal func PublicClass_copyFromCType(_ handle: _baseRef) -> PublicClass { if let swift_pointer = smoke_PublicClass_get_swift_object_from_wrapper_cache(handle), let re_constructed = Unmanaged<AnyObject>.fromOpaque(swift_pointer).takeUnretainedValue() as? PublicClass { return re_constructed } let result = PublicClass(cPublicClass: smoke_PublicClass_copy_handle(handle)) smoke_PublicClass_cache_swift_object_wrapper(handle, Unmanaged<AnyObject>.passUnretained(result).toOpaque()) return result } internal func PublicClass_moveFromCType(_ handle: _baseRef) -> PublicClass { if let swift_pointer = smoke_PublicClass_get_swift_object_from_wrapper_cache(handle), let re_constructed = Unmanaged<AnyObject>.fromOpaque(swift_pointer).takeUnretainedValue() as? PublicClass { smoke_PublicClass_release_handle(handle) return re_constructed } let result = PublicClass(cPublicClass: handle) smoke_PublicClass_cache_swift_object_wrapper(handle, Unmanaged<AnyObject>.passUnretained(result).toOpaque()) return result } internal func PublicClass_copyFromCType(_ handle: _baseRef) -> PublicClass? { guard handle != 0 else { return nil } return PublicClass_moveFromCType(handle) as PublicClass } internal func PublicClass_moveFromCType(_ handle: _baseRef) -> PublicClass? { guard handle != 0 else { return nil } return PublicClass_moveFromCType(handle) as PublicClass } internal func copyToCType(_ swiftClass: PublicClass) -> RefHolder { return getRef(swiftClass, owning: false) } internal func moveToCType(_ swiftClass: PublicClass) -> RefHolder { return getRef(swiftClass, owning: true) } internal func copyToCType(_ swiftClass: PublicClass?) -> RefHolder { return getRef(swiftClass, owning: false) } internal func moveToCType(_ swiftClass: PublicClass?) -> RefHolder { return getRef(swiftClass, owning: true) } internal func copyFromCType(_ handle: _baseRef) -> PublicClass.InternalStruct { return PublicClass.InternalStruct(cHandle: handle) } internal func moveFromCType(_ handle: _baseRef) -> PublicClass.InternalStruct { defer { smoke_PublicClass_InternalStruct_release_handle(handle) } return copyFromCType(handle) } internal func copyToCType(_ swiftType: PublicClass.InternalStruct) -> RefHolder { let c_stringField = moveToCType(swiftType.stringField) return RefHolder(smoke_PublicClass_InternalStruct_create_handle(c_stringField.ref)) } internal func moveToCType(_ swiftType: PublicClass.InternalStruct) -> RefHolder { return RefHolder(ref: copyToCType(swiftType).ref, release: smoke_PublicClass_InternalStruct_release_handle) } internal func copyFromCType(_ handle: _baseRef) -> PublicClass.InternalStruct? { guard handle != 0 else { return nil } let unwrappedHandle = smoke_PublicClass_InternalStruct_unwrap_optional_handle(handle) return PublicClass.InternalStruct(cHandle: unwrappedHandle) as PublicClass.InternalStruct } internal func moveFromCType(_ handle: _baseRef) -> PublicClass.InternalStruct? { defer { smoke_PublicClass_InternalStruct_release_optional_handle(handle) } return copyFromCType(handle) } internal func copyToCType(_ swiftType: PublicClass.InternalStruct?) -> RefHolder { guard let swiftType = swiftType else { return RefHolder(0) } let c_stringField = moveToCType(swiftType.stringField) return RefHolder(smoke_PublicClass_InternalStruct_create_optional_handle(c_stringField.ref)) } internal func moveToCType(_ swiftType: PublicClass.InternalStruct?) -> RefHolder { return RefHolder(ref: copyToCType(swiftType).ref, release: smoke_PublicClass_InternalStruct_release_optional_handle) } internal func copyFromCType(_ handle: _baseRef) -> PublicClass.PublicStruct { return PublicClass.PublicStruct(cHandle: handle) } internal func moveFromCType(_ handle: _baseRef) -> PublicClass.PublicStruct { defer { smoke_PublicClass_PublicStruct_release_handle(handle) } return copyFromCType(handle) } internal func copyToCType(_ swiftType: PublicClass.PublicStruct) -> RefHolder { let c_internalField = moveToCType(swiftType.internalField) return RefHolder(smoke_PublicClass_PublicStruct_create_handle(c_internalField.ref)) } internal func moveToCType(_ swiftType: PublicClass.PublicStruct) -> RefHolder { return RefHolder(ref: copyToCType(swiftType).ref, release: smoke_PublicClass_PublicStruct_release_handle) } internal func copyFromCType(_ handle: _baseRef) -> PublicClass.PublicStruct? { guard handle != 0 else { return nil } let unwrappedHandle = smoke_PublicClass_PublicStruct_unwrap_optional_handle(handle) return PublicClass.PublicStruct(cHandle: unwrappedHandle) as PublicClass.PublicStruct } internal func moveFromCType(_ handle: _baseRef) -> PublicClass.PublicStruct? { defer { smoke_PublicClass_PublicStruct_release_optional_handle(handle) } return copyFromCType(handle) } internal func copyToCType(_ swiftType: PublicClass.PublicStruct?) -> RefHolder { guard let swiftType = swiftType else { return RefHolder(0) } let c_internalField = moveToCType(swiftType.internalField) return RefHolder(smoke_PublicClass_PublicStruct_create_optional_handle(c_internalField.ref)) } internal func moveToCType(_ swiftType: PublicClass.PublicStruct?) -> RefHolder { return RefHolder(ref: copyToCType(swiftType).ref, release: smoke_PublicClass_PublicStruct_release_optional_handle) } internal func copyFromCType(_ handle: _baseRef) -> PublicClass.PublicStructWithInternalDefaults { return PublicClass.PublicStructWithInternalDefaults(cHandle: handle) } internal func moveFromCType(_ handle: _baseRef) -> PublicClass.PublicStructWithInternalDefaults { defer { smoke_PublicClass_PublicStructWithInternalDefaults_release_handle(handle) } return copyFromCType(handle) } internal func copyToCType(_ swiftType: PublicClass.PublicStructWithInternalDefaults) -> RefHolder { let c_internalField = moveToCType(swiftType.internalField) let c_publicField = moveToCType(swiftType.publicField) return RefHolder(smoke_PublicClass_PublicStructWithInternalDefaults_create_handle(c_internalField.ref, c_publicField.ref)) } internal func moveToCType(_ swiftType: PublicClass.PublicStructWithInternalDefaults) -> RefHolder { return RefHolder(ref: copyToCType(swiftType).ref, release: smoke_PublicClass_PublicStructWithInternalDefaults_release_handle) } internal func copyFromCType(_ handle: _baseRef) -> PublicClass.PublicStructWithInternalDefaults? { guard handle != 0 else { return nil } let unwrappedHandle = smoke_PublicClass_PublicStructWithInternalDefaults_unwrap_optional_handle(handle) return PublicClass.PublicStructWithInternalDefaults(cHandle: unwrappedHandle) as PublicClass.PublicStructWithInternalDefaults } internal func moveFromCType(_ handle: _baseRef) -> PublicClass.PublicStructWithInternalDefaults? { defer { smoke_PublicClass_PublicStructWithInternalDefaults_release_optional_handle(handle) } return copyFromCType(handle) } internal func copyToCType(_ swiftType: PublicClass.PublicStructWithInternalDefaults?) -> RefHolder { guard let swiftType = swiftType else { return RefHolder(0) } let c_internalField = moveToCType(swiftType.internalField) let c_publicField = moveToCType(swiftType.publicField) return RefHolder(smoke_PublicClass_PublicStructWithInternalDefaults_create_optional_handle(c_internalField.ref, c_publicField.ref)) } internal func moveToCType(_ swiftType: PublicClass.PublicStructWithInternalDefaults?) -> RefHolder { return RefHolder(ref: copyToCType(swiftType).ref, release: smoke_PublicClass_PublicStructWithInternalDefaults_release_optional_handle) } internal func copyToCType(_ swiftEnum: PublicClass.InternalEnum) -> PrimitiveHolder<UInt32> { return PrimitiveHolder(swiftEnum.rawValue) } internal func moveToCType(_ swiftEnum: PublicClass.InternalEnum) -> PrimitiveHolder<UInt32> { return copyToCType(swiftEnum) } internal func copyToCType(_ swiftEnum: PublicClass.InternalEnum?) -> RefHolder { return copyToCType(swiftEnum?.rawValue) } internal func moveToCType(_ swiftEnum: PublicClass.InternalEnum?) -> RefHolder { return moveToCType(swiftEnum?.rawValue) } internal func copyFromCType(_ cValue: UInt32) -> PublicClass.InternalEnum { return PublicClass.InternalEnum(rawValue: cValue)! } internal func moveFromCType(_ cValue: UInt32) -> PublicClass.InternalEnum { return copyFromCType(cValue) } internal func copyFromCType(_ handle: _baseRef) -> PublicClass.InternalEnum? { guard handle != 0 else { return nil } return PublicClass.InternalEnum(rawValue: uint32_t_value_get(handle))! } internal func moveFromCType(_ handle: _baseRef) -> PublicClass.InternalEnum? { defer { uint32_t_release_handle(handle) } return copyFromCType(handle) }
43.781879
138
0.756113
2945163d295040e1b8d3035ed41704a7201f620a
2,247
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. // // Code generated by Microsoft (R) AutoRest Code Generator. import Foundation import azureSwiftRuntime internal struct ServiceObjectiveData : ServiceObjectiveProtocol, ProxyResourceProtocol, ResourceProtocol { public var id: String? public var name: String? public var type: String? public var properties: ServiceObjectivePropertiesProtocol? enum CodingKeys: String, CodingKey {case id = "id" case name = "name" case type = "type" case properties = "properties" } public init() { } public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) if container.contains(.id) { self.id = try container.decode(String?.self, forKey: .id) } if container.contains(.name) { self.name = try container.decode(String?.self, forKey: .name) } if container.contains(.type) { self.type = try container.decode(String?.self, forKey: .type) } if container.contains(.properties) { self.properties = try container.decode(ServiceObjectivePropertiesData?.self, forKey: .properties) } if var pageDecoder = decoder as? PageDecoder { if pageDecoder.isPagedData, let nextLinkName = pageDecoder.nextLinkName { pageDecoder.nextLink = try UnknownCodingKey.decodeStringForKey(decoder: decoder, keyForDecode: nextLinkName) } } } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) if self.id != nil {try container.encode(self.id, forKey: .id)} if self.name != nil {try container.encode(self.name, forKey: .name)} if self.type != nil {try container.encode(self.type, forKey: .type)} if self.properties != nil {try container.encode(self.properties as! ServiceObjectivePropertiesData?, forKey: .properties)} } } extension DataFactory { public static func createServiceObjectiveProtocol() -> ServiceObjectiveProtocol { return ServiceObjectiveData() } }
38.741379
127
0.684913
1487a354efcb45a38eb7e1ee984714b8acd9e2cd
1,018
// // API.swift // Gorilla // // Created by Daniel Tarazona on 12/7/19. // Copyright © 2019 Gorilla. All rights reserved. // import Foundation class API { let URL: String init(URL: String) { self.URL = URL } func getPage(completion: (@escaping ([Post]) -> Void )) -> Void { let request = NSMutableURLRequest( url: NSURL(string: "https://gl-endpoint.herokuapp.com/feed")! as URL, cachePolicy: .useProtocolCachePolicy, timeoutInterval: 10.0 ) request.httpMethod = "GET" let session = URLSession.shared let dataTask = session.dataTask( with: request as URLRequest, completionHandler: { (data, response, error) -> Void in if error != nil { print("Error: \(String(describing: error))") } else { if data != nil { let decoder = JSONDecoder() let posts = try! decoder.decode([Post].self, from: data!) completion(posts) } } }) dataTask.resume() } }
20.36
75
0.58055