repo_name
stringlengths
6
91
path
stringlengths
8
968
copies
stringclasses
210 values
size
stringlengths
2
7
content
stringlengths
61
1.01M
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
6
99.8
line_max
int64
12
1k
alpha_frac
float64
0.3
0.91
ratio
float64
2
9.89
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
KlubJagiellonski/pola-ios
BuyPolish/Pola/UI/ProductSearch/ScanCode/ProductCard/OwnBrandContent/OwnBrandContentViewController.swift
1
1267
import UIKit class OwnBrandContentViewController: UIViewController { let result: ScanResult private var ownBrandView: OwnBrandContentView! { view as? OwnBrandContentView } init(result: ScanResult) { self.result = result super.init(nibName: nil, bundle: nil) } @available(*, unavailable) required init?(coder _: NSCoder) { fatalError("init(coder:) has not been implemented") } override func loadView() { view = OwnBrandContentView() } override func viewDidLoad() { super.viewDidLoad() guard let companies = result.companies, companies.count == 2 else { return } setupCompanyTitleView(ownBrandView.primaryCompanyTitleView, company: companies[1]) setupCompanyTitleView(ownBrandView.secondaryCompanyTitleView, company: companies[0]) ownBrandView.descriptionView.text = companies[0].description } private func setupCompanyTitleView(_ titleView: OwnBrandCompanyTitleView, company: Company) { titleView.title = company.name if let score = company.plScore { titleView.progress = CGFloat(score) / 100.0 } else { titleView.progress = 0 } } }
gpl-2.0
7b7eeb0a9350e6c8ebfbd6b3f00a5d02
27.155556
97
0.644041
4.763158
false
false
false
false
velvetroom/columbus
Source/View/Settings/VSettingsListCellDistance+Factory.swift
1
2609
import UIKit extension VSettingsListCellDistance { //MARK: selectors @objc private func selectorSegemented(sender segmented:UISegmentedControl) { let index:Int = segmented.selectedSegmentIndex model?.selected(index:index) } //MARK: internal func factoryTitle() { let labelTitle:UILabel = UILabel() labelTitle.isUserInteractionEnabled = false labelTitle.translatesAutoresizingMaskIntoConstraints = false labelTitle.backgroundColor = UIColor.clear labelTitle.font = UIFont.regular(size:VSettingsListCellDistance.Constants.titleFontSize) labelTitle.textColor = UIColor.colourBackgroundDark labelTitle.text = String.localizedView(key:"VSettingsListCellDistance_labelTitle") addSubview(labelTitle) NSLayoutConstraint.topToTop( view:labelTitle, toView:self) NSLayoutConstraint.height( view:labelTitle, constant:VSettingsListCellDistance.Constants.titleHeight) NSLayoutConstraint.leftToLeft( view:labelTitle, toView:self, constant:VSettingsListCellDistance.Constants.titleLeft) NSLayoutConstraint.rightToRight( view:labelTitle, toView:self) } func factorySegmented(model:MSettingsDistance) { guard self.viewSegmented == nil else { return } let titles:[String] = model.itemsTitle() let viewSegmented:UISegmentedControl = UISegmentedControl(items:titles) viewSegmented.translatesAutoresizingMaskIntoConstraints = false viewSegmented.tintColor = UIColor.colourBackgroundDark viewSegmented.addTarget( self, action:#selector(selectorSegemented(sender:)), for:UIControlEvents.valueChanged) self.viewSegmented = viewSegmented addSubview(viewSegmented) NSLayoutConstraint.topToTop( view:viewSegmented, toView:self, constant:VSettingsListCellDistance.Constants.segmentedTop) NSLayoutConstraint.height( view:viewSegmented, constant:VSettingsListCellDistance.Constants.segmentedHeight) NSLayoutConstraint.width( view:viewSegmented, constant:VSettingsListCellDistance.Constants.segmentedWidth) layoutSegmentedLeft = NSLayoutConstraint.leftToLeft( view:viewSegmented, toView:self) } }
mit
2fad8159d8be1594c3e75d22bcc8835b
31.6125
96
0.646608
5.983945
false
false
false
false
RocketChat/Rocket.Chat.iOS
Rocket.Chat/Views/Chat/New Chat/ChatItems/BasicMessageChatItem.swift
1
1349
// // BasicMessageChatItem.swift // Rocket.Chat // // Created by Filipe Alvarenga on 23/09/18. // Copyright © 2018 Rocket.Chat. All rights reserved. // import Foundation import DifferenceKit import RocketChatViewController final class BasicMessageChatItem: BaseMessageChatItem, ChatItem, Differentiable { var relatedReuseIdentifier: String { return BasicMessageCell.identifier } init(user: UnmanagedUser, message: UnmanagedMessage) { super.init( user: user, message: message ) } var differenceIdentifier: String { return (user?.differenceIdentifier ?? "") + (message?.identifier ?? "") } func isContentEqual(to source: BasicMessageChatItem) -> Bool { guard let user = user, let sourceUser = source.user, let message = message, let sourceMessage = source.message else { return false } return user.name == sourceUser.name && user.username == sourceUser.username && message.temporary == sourceMessage.temporary && message.failed == sourceMessage.failed && message.text == sourceMessage.text && message.updatedAt?.timeIntervalSince1970 == sourceMessage.updatedAt?.timeIntervalSince1970 } }
mit
b7cf4072fd049234c13f7e342d99120e
27.680851
102
0.625371
4.937729
false
false
false
false
ben-ng/swift
test/SILGen/closure_script_global_escape.swift
7
1343
// RUN: %target-swift-frontend -module-name foo -emit-silgen %s | %FileCheck %s // RUN: %target-swift-frontend -module-name foo -emit-sil -verify %s // CHECK-LABEL: sil @main // CHECK: [[GLOBAL:%.*]] = global_addr @_Tv3foo4flagSb // CHECK: [[MARK:%.*]] = mark_uninitialized [var] [[GLOBAL]] var flag: Bool // expected-note* {{defined here}} // CHECK: mark_function_escape [[MARK]] func useFlag() { // expected-error{{'flag' used by function definition before being initialized}} _ = flag } // CHECK: [[CLOSURE:%.*]] = function_ref @_TF3fooU_FT_T_ // CHECK: mark_function_escape [[MARK]] // CHECK: thin_to_thick_function [[CLOSURE]] _ = { _ = flag } // expected-error{{'flag' captured by a closure before being initialized}} // CHECK: mark_function_escape [[MARK]] // CHECK: [[CLOSURE:%.*]] = function_ref @_TF3fooU0_FT_T_ // CHECK: apply [[CLOSURE]] _ = { _ = flag }() // expected-error{{'flag' captured by a closure before being initialized}} flag = true // CHECK: mark_function_escape [[MARK]] func useFlag2() { _ = flag } // CHECK: [[CLOSURE:%.*]] = function_ref @_TF3fooU1_FT_T_ // CHECK: mark_function_escape [[MARK]] // CHECK: thin_to_thick_function [[CLOSURE]] _ = { _ = flag } // CHECK: mark_function_escape [[MARK]] // CHECK: [[CLOSURE:%.*]] = function_ref @_TF3fooU2_FT_T_ // CHECK: apply [[CLOSURE]] _ = { _ = flag }()
apache-2.0
324aace6f3462ba325998f00d504f15b
32.575
97
0.632911
3.16
false
false
false
false
ephread/Instructions
Sources/Instructions/Managers/Public/FlowManager.swift
2
12083
// Copyright (c) 2016-present Frédéric Maquin <[email protected]> and contributors. // Licensed under the terms of the MIT License. import UIKit public class FlowManager { // MARK: - Internal Properties /// `true` if coach marks are currently being displayed, `false` otherwise. public var isStarted: Bool { return currentIndex > -1 } /// Sometimes, the chain of coach mark display can be paused /// to let animations be performed. `true` to pause the execution, /// `false` otherwise. private(set) open var isPaused = false internal unowned let coachMarksViewController: CoachMarksViewController internal weak var dataSource: CoachMarksControllerProxyDataSource? /// An object implementing the delegate data source protocol, /// which methods will be called at various points. internal weak var delegate: CoachMarksControllerProxyDelegate? /// Reference to the currently displayed coach mark, supplied by the `datasource`. internal var currentCoachMark: CoachMark? /// The total number of coach marks, supplied by the `datasource`. private var numberOfCoachMarks = 0 /// Since changing size calls asynchronous completion blocks, /// we might end up firing multiple times the methods adding coach /// marks to the view. To prevent that from happening we use the guard /// property. /// /// Everything is normally happening on the main thread, atomicity should /// not be a problem. Plus, a size change is a very long process compared to /// subview addition. /// /// This property will be checked multiple time during the process of /// showing coach marks and can abort the normal flow. This, it's also /// used to prevent the normal flow when calling `stop(immediately:)`. /// /// `true` when the controller is performing a size change, `false` otherwise. private var disableFlow = false /// This property is much like `disableFlow`, except it's used only to /// prevent a coach mark from being shown multiple times (in case the user /// is tapping too fast. /// /// `true` if a new coach mark can be shown, `false` otherwise. private var canShowCoachMark = true /// The index (in `coachMarks`) of the coach mark being currently displayed. internal var currentIndex = -1 init(coachMarksViewController: CoachMarksViewController) { self.coachMarksViewController = coachMarksViewController } // MARK: Internal methods internal func startFlow(withNumberOfCoachMarks numberOfCoachMarks: Int) { disableFlow = false self.numberOfCoachMarks = numberOfCoachMarks coachMarksViewController.prepareToShowCoachMarks { self.showNextCoachMark() } } internal func reset() { currentIndex = -1 isPaused = false canShowCoachMark = true //disableFlow will be set by startFlow, to enable quick stop. } /// Stop displaying the coach marks and perform some cleanup. /// /// - Parameter immediately: `true` to hide immediately with no animation /// `false` otherwise. /// - Parameter userDidSkip: `true` when the user canceled the flow, `false` otherwise. /// - Parameter shouldCallDelegate: `true` to notify the delegate that the flow /// was stop. internal func stopFlow(immediately: Bool = false, userDidSkip skipped: Bool = false, shouldCallDelegate: Bool = true, completion: (() -> Void)? = nil) { reset() let animationBlock = { () -> Void in self.coachMarksViewController.skipView?.asView?.alpha = 0.0 self.coachMarksViewController.currentCoachMarkView?.alpha = 0.0 } let completionBlock = { [weak self] (finished: Bool) -> Void in guard let strongSelf = self else { return } strongSelf.coachMarksViewController.detachFromWindow() if shouldCallDelegate { strongSelf.delegate?.didEndShowingBySkipping(skipped) } completion?() } if immediately { disableFlow = true animationBlock() completionBlock(true) // TODO: SoC self.coachMarksViewController.overlayManager.overlayView.alpha = 0 } else { UIView.animate(withDuration: coachMarksViewController.overlayManager .fadeAnimationDuration, animations: animationBlock) self.coachMarksViewController.overlayManager.showOverlay(false, completion: completionBlock) } } internal func showNextCoachMark(hidePrevious: Bool = true) { if disableFlow || isPaused || !canShowCoachMark { return } let previousIndex = currentIndex canShowCoachMark = false currentIndex += 1 if currentIndex == 0 { createAndShowCoachMark() return } if let currentCoachMark = currentCoachMark, currentIndex > 0 { delegate?.willHide(coachMark: currentCoachMark, at: currentIndex - 1) } if hidePrevious { guard let currentCoachMark = currentCoachMark else { return } coachMarksViewController.hide(coachMark: currentCoachMark, at: previousIndex) { if self.currentIndex > 0 { self.delegate?.didHide(coachMark: self.currentCoachMark!, at: self.currentIndex - 1) } self.showOrStop() } } else { showOrStop() } } internal func showPreviousCoachMark(hidePrevious: Bool = true) { if disableFlow || isPaused || !canShowCoachMark { return } let previousIndex = currentIndex canShowCoachMark = false currentIndex -= 1 if currentIndex < 0 { stopFlow() return } if let currentCoachMark = currentCoachMark { delegate?.willHide(coachMark: currentCoachMark, at: currentIndex + 1) } if hidePrevious { guard let currentCoachMark = currentCoachMark else { return } coachMarksViewController.hide(coachMark: currentCoachMark, at: previousIndex) { self.delegate?.didHide(coachMark: self.currentCoachMark!, at: self.currentIndex) self.showOrStop() } } else { showOrStop() } } internal func showOrStop() { if self.currentIndex < self.numberOfCoachMarks { self.createAndShowCoachMark() } else { self.stopFlow() } } /// Ask the datasource, create the coach mark and display it. Also /// notifies the delegate. When this method is called during a size change, /// the delegate is not notified. /// /// - Parameter shouldCallDelegate: `true` to call delegate methods, `false` otherwise. internal func createAndShowCoachMark(afterResuming: Bool = false, changing change: ConfigurationChange = .nothing) { if disableFlow { return } if currentIndex < 0 { return } if !afterResuming { guard delegate?.willLoadCoachMark(at: currentIndex) ?? false else { canShowCoachMark = true showNextCoachMark(hidePrevious: false) return } // Retrieves the current coach mark structure from the datasource. // It can't be nil, that's why we'll force unwrap it everywhere. currentCoachMark = self.dataSource!.coachMark(at: currentIndex) // The coach mark will soon show, we notify the delegate, so it // can perform some things and, if required, update the coach mark structure. self.delegate?.willShow(coachMark: &currentCoachMark!, beforeChanging: change, at: currentIndex) } // The delegate might have paused the flow, we check whether or not it's // the case. if !self.isPaused { if coachMarksViewController.instructionsRootView.bounds.isEmpty { print(ErrorMessage.Error.overlayEmptyBounds) self.stopFlow() return } coachMarksViewController.show(coachMark: &currentCoachMark!, at: currentIndex) { self.canShowCoachMark = true self.delegate?.didShow(coachMark: self.currentCoachMark!, afterChanging: change, at: self.currentIndex) } } } // MARK: Public methods public func resume() { if isStarted && isPaused { isPaused = false let completion: (Bool) -> Void = { _ in self.createAndShowCoachMark(afterResuming: true) } if coachMarksViewController.overlayManager.isWindowHidden { coachMarksViewController.overlayManager.showWindow(true, completion: completion) } else if coachMarksViewController.overlayManager.isOverlayInvisible { coachMarksViewController.overlayManager.showOverlay(true, completion: completion) } else { completion(true) } } } public func pause(and pauseStyle: PauseStyle = .hideNothing) { isPaused = true switch pauseStyle { case .hideInstructions: coachMarksViewController.overlayManager.showWindow(false, completion: nil) case .hideOverlay: coachMarksViewController.overlayManager.showOverlay(false, completion: nil) case .hideNothing: break } } /// Show the next specified Coach Mark. /// /// - Parameter numberOfCoachMarksToSkip: the number of coach marks /// to skip. public func showNext(numberOfCoachMarksToSkip numberToSkip: Int = 0) { if !self.isStarted || !canShowCoachMark { return } if numberToSkip < 0 { print(ErrorMessage.Warning.negativeNumberOfCoachMarksToSkip) return } currentIndex += numberToSkip showNextCoachMark(hidePrevious: true) } /// Show the previous specified Coach Mark. /// /// - Parameter numberOfCoachMarksToSkip: the number of coach marks /// to skip. public func showPrevious(numberOfCoachMarksToSkip numberToSkip: Int = 0) { if !self.isStarted || !canShowCoachMark { return } if numberToSkip < 0 { print(ErrorMessage.Warning.negativeNumberOfCoachMarksToSkip) return } currentIndex -= numberToSkip showPreviousCoachMark(hidePrevious: true) } // MARK: Renamed Public Properties @available(*, unavailable, renamed: "isStarted") public var started: Bool = false @available(*, unavailable, renamed: "isPaused") public var paused: Bool = false } extension FlowManager: CoachMarksViewControllerDelegate { func didTap(coachMarkView: CoachMarkView?) { delegate?.didTapCoachMark(at: currentIndex) showNextCoachMark() } func didTap(skipView: CoachMarkSkipView?) { stopFlow(immediately: false, userDidSkip: true, shouldCallDelegate: true) } func willTransition() { coachMarksViewController.prepareForSizeTransition() if let coachMark = currentCoachMark { coachMarksViewController.hide(coachMark: coachMark, at: currentIndex, animated: false, beforeTransition: true) } } func didTransition(afterChanging change: ConfigurationChange) { coachMarksViewController.restoreAfterSizeTransitionDidComplete() createAndShowCoachMark(changing: change) } }
mit
4a6379b96421b5939e7859effd6623f3
36.172308
97
0.618492
5.650608
false
false
false
false
lieyunye/WeixinWalk
微信运动/微信运动/MainViewController.swift
2
5130
// // ViewController.swift // 微信运动 // // Created by Eular on 9/5/15. // Copyright © 2015 Eular. All rights reserved. // import UIKit class MainViewController: UITableViewController { @IBOutlet weak var stepsLabel: UILabel! let healthManager = HealthManager() var scene = WXSceneSession.rawValue var egg_count = 0 override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. // 引导页 let defaults = NSUserDefaults.standardUserDefaults() let hasViewedWalkthrough = defaults.boolForKey("hasViewedWalkthrough") if !hasViewedWalkthrough { if let pageViewController = storyboard?.instantiateViewControllerWithIdentifier("PageViewController") as? PageViewController { self.presentViewController(pageViewController, animated: true, completion: nil) } } let headerView = UIView() let app_icon = UIImageView() let app_name = UILabel() let app_words = UILabel() let width = self.view.bounds.size.width let height = CGFloat(250) let icon_offset = CGFloat(40) let app_icon_width = CGFloat(80) headerView.frame = CGRectMake(0, 0, width, height) app_icon.frame = CGRectMake((width - app_icon_width) / 2, icon_offset, app_icon_width, app_icon_width) app_icon.image = UIImage(named: "health_icon") headerView.addSubview(app_icon) app_name.text = "健康" app_name.frame = CGRectMake(0, icon_offset + app_icon_width + 10, width, 20) app_name.textAlignment = .Center app_name.textColor = UIColor.grayColor() app_name.font = UIFont(name: app_words.font.fontName, size: 22) headerView.addSubview(app_name) app_words.text = "\"微信运动\"读取的是系统的健康数据,且最高步数为98800步" app_words.frame = CGRectMake(20, height - 70, width - 40, 40) app_words.numberOfLines = 2 app_words.textColor = UIColor.grayColor() app_words.font = UIFont(name: app_words.font.fontName, size: 15) headerView.addSubview(app_words) tableView.tableHeaderView = headerView NSNotificationCenter.defaultCenter().addObserver(self, selector:"weixinShareDone:", name: shareDoneNotification, object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector:"weixinShareCancel:", name: shareCancelNotification, object: nil) updateSteps() } func updateSteps() { healthManager.readTotalSteps { (steps) in dispatch_sync(dispatch_get_main_queue(), { () -> Void in self.stepsLabel.text = "\(steps)" }) } } override func viewDidAppear(animated: Bool) { egg_count = 0 updateSteps() } func weixinShareDone(notification: NSNotification) { let stepcount = (scene == WXSceneTimeline.rawValue) ? 10000.0 : 5000.0 healthManager.saveStepsSample(stepcount, endDate: NSDate(), duration: 30) { (success, error) in dispatch_sync(dispatch_get_main_queue(), { () -> Void in self.view.makeToast(message: "哇咔咔,为你增加\(stepcount)步!", duration: 2, position: "center") self.updateSteps() }) } } func weixinShareCancel(notification: NSNotification) { self.view.makeToast(message: "分享作弊被我发现啦!", duration: 2, position: "center") } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { tableView.deselectRowAtIndexPath(indexPath, animated: true) var share = false switch indexPath.row { case 0: egg_count++ case 1: share = true scene = WXSceneTimeline.rawValue case 2: share = true scene = WXSceneSession.rawValue default: break } if egg_count == 10 { egg_count = 0 self.performSegueWithIdentifier("easterEggSegue", sender: nil) } if share { let message = WXMediaMessage() message.title = "我在微信运动上走了98800,不服来战!" message.description = "有了它,妈妈再也不用担心我会为了刷榜而运动啦" message.setThumbImage(UIImage(named: "App")) let ext = WXWebpageObject() ext.webpageUrl = AppDownload message.mediaObject = ext let req = SendMessageToWXReq() req.bText = false req.message = message req.scene = Int32(scene) WXApi.sendReq(req) } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
apache-2.0
d67e35a410411f347319a2879a6d5287
34.12766
138
0.595599
4.422321
false
false
false
false
aschwaighofer/swift
test/Sema/diag_erroneous_iuo.swift
2
11287
// RUN: %target-typecheck-verify-swift -swift-version 5 // These are all legal uses of '!'. struct Fine { var value: Int! func m(_ unnamed: Int!, named: Int!) -> Int! { return unnamed } static func s(_ unnamed: Int!, named: Int!) -> Int! { return named } init(_ value: Int) { self.value = value } init!() { return nil } subscript ( index: Int! ) -> Int! { return index } subscript<T> ( index: T! ) -> T! { return index } } let _: ImplicitlyUnwrappedOptional<Int> = 1 // expected-error {{'ImplicitlyUnwrappedOptional' has been renamed to 'Optional'}}{{8-35=Optional}} let _: ImplicitlyUnwrappedOptional = 1 // expected-error {{'ImplicitlyUnwrappedOptional' has been renamed to 'Optional'}} extension ImplicitlyUnwrappedOptional {} // expected-error {{'ImplicitlyUnwrappedOptional' has been renamed to 'Optional'}} func functionSpelling( _: ImplicitlyUnwrappedOptional<Int> // expected-error {{'ImplicitlyUnwrappedOptional' has been renamed to 'Optional'}}{{6-33=Optional}} ) -> ImplicitlyUnwrappedOptional<Int> { // expected-error {{'ImplicitlyUnwrappedOptional' has been renamed to 'Optional'}}{{6-33=Optional}} return 1 } // Okay, like in the method case. func functionSigil( _: Int! ) -> Int! { return 1 } // Not okay because '!' is not at the top level of the type. func functionSigilArray( _: [Int!] // expected-error {{'!' is not allowed here; perhaps '?' was intended?}}{{10-11=?}} ) -> [Int!] { // expected-error {{'!' is not allowed here; perhaps '?' was intended?}}{{10-11=?}} return [1] } func genericFunction<T>( iuo: ImplicitlyUnwrappedOptional<T> // expected-error {{'ImplicitlyUnwrappedOptional' has been renamed to 'Optional'}}{{8-35=Optional}} ) -> ImplicitlyUnwrappedOptional<T> { // expected-error {{'ImplicitlyUnwrappedOptional' has been renamed to 'Optional'}}{{6-33=Optional}} return iuo } // Okay, like in the non-generic case. func genericFunctionSigil<T>( iuo: T! ) -> T! { return iuo } func genericFunctionSigilArray<T>( // FIXME: We validate these types multiple times resulting in multiple diagnostics iuo: [T!] // expected-error {{'!' is not allowed here; perhaps '?' was intended?}}{{10-11=?}} // expected-error@-1 {{'!' is not allowed here; perhaps '?' was intended?}}{{10-11=?}} ) -> [T!] { // expected-error {{'!' is not allowed here; perhaps '?' was intended?}}{{8-9=?}} // expected-error@-1 {{'!' is not allowed here; perhaps '?' was intended?}}{{8-9=?}} return iuo } protocol P { associatedtype T // expected-note {{protocol requires nested type 'T'; do you want to add it?}} associatedtype U // expected-note {{protocol requires nested type 'U'; do you want to add it?}} } struct S : P { // expected-error {{type 'S' does not conform to protocol 'P'}} typealias T = ImplicitlyUnwrappedOptional<Int> // expected-error {{'ImplicitlyUnwrappedOptional' has been renamed to 'Optional'}}{{17-44=Optional}} typealias U = Optional<ImplicitlyUnwrappedOptional<Int>> // expected-error {{'ImplicitlyUnwrappedOptional' has been renamed to 'Optional'}}{{26-53=Optional}} typealias V = Int! // expected-error {{'!' is not allowed here; perhaps '?' was intended?}}{{20-21=?}} typealias W = Int!? // expected-error {{'!' is not allowed here; perhaps '?' was intended?}}{{20-21=?}} var x: V var y: W var fn1: (Int!) -> Int // expected-error {{'!' is not allowed here; perhaps '?' was intended?}}{{16-17=?}} var fn2: (Int) -> Int! // expected-error {{'!' is not allowed here; perhaps '?' was intended?}}{{24-25=?}} subscript ( index: ImplicitlyUnwrappedOptional<Int> // expected-error {{'ImplicitlyUnwrappedOptional' has been renamed to 'Optional'}}{{12-39=Optional}} ) -> ImplicitlyUnwrappedOptional<Int> { // expected-error {{'ImplicitlyUnwrappedOptional' has been renamed to 'Optional'}}{{12-39=Optional}} return index } subscript<T> ( index: ImplicitlyUnwrappedOptional<T> // expected-error {{'ImplicitlyUnwrappedOptional' has been renamed to 'Optional'}}{{12-39=Optional}} ) -> ImplicitlyUnwrappedOptional<T> { // expected-error {{'ImplicitlyUnwrappedOptional' has been renamed to 'Optional'}}{{12-39=Optional}} return index } } func generic<T : P>(_: T) where T.T == ImplicitlyUnwrappedOptional<Int> { } // expected-error {{'ImplicitlyUnwrappedOptional' has been renamed to 'Optional'}}{{40-67=Optional}} func genericOptIUO<T : P>(_: T) where T.U == Optional<ImplicitlyUnwrappedOptional<Int>> {} // expected-error {{'ImplicitlyUnwrappedOptional' has been renamed to 'Optional'}}{{55-82=Optional}} func testClosure() -> Int { return { (i: ImplicitlyUnwrappedOptional<Int>) // expected-error {{'ImplicitlyUnwrappedOptional' has been renamed to 'Optional'}}{{9-36=Optional}} -> ImplicitlyUnwrappedOptional<Int> in // expected-error {{'ImplicitlyUnwrappedOptional' has been renamed to 'Optional'}}{{9-36=Optional}} return i }(1)! } _ = Array<Int!>() // expected-error {{'!' is not allowed here; perhaps '?' was intended?}}{{14-15=?}} let _: Array<Int!> = [1] // expected-error {{'!' is not allowed here; perhaps '?' was intended?}}{{17-18=?}} _ = [Int!]() // expected-error {{'!' is not allowed here; perhaps '?' was intended?}}{{9-10=?}} let _: [Int!] = [1] // expected-error {{'!' is not allowed here; perhaps '?' was intended?}}{{12-13=?}} _ = Optional<Int!>(nil) // expected-error {{'!' is not allowed here; perhaps '?' was intended?}}{{17-18=?}} let _: Optional<Int!> = nil // expected-error {{'!' is not allowed here; perhaps '?' was intended?}}{{20-21=?}} _ = Int!?(0) // expected-error 3 {{'!' is not allowed here; perhaps '?' was intended?}}{{8-9=?}} let _: Int!? = 0 // expected-error {{'!' is not allowed here; perhaps '?' was intended?}}{{11-12=?}} _ = ( Int!, // expected-error {{'!' is not allowed here; perhaps '?' was intended?}}{{6-7=?}} Float!, // expected-error {{'!' is not allowed here; perhaps '?' was intended?}}{{8-9=?}} String! // expected-error {{'!' is not allowed here; perhaps '?' was intended?}}{{9-10=?}} )(1, 2.0, "3") let _: ( Int!, // expected-error {{'!' is not allowed here; perhaps '?' was intended?}}{{6-7=?}} Float!, // expected-error {{'!' is not allowed here; perhaps '?' was intended?}}{{8-9=?}} String! // expected-error {{'!' is not allowed here; perhaps '?' was intended?}}{{9-10=?}} ) = (1, 2.0, "3") struct Generic<T, U, C> { init(_ t: T, _ u: U, _ c: C) {} } _ = Generic<Int!, // expected-error {{'!' is not allowed here; perhaps '?' was intended?}}{{16-17=?}} Float!, // expected-error {{'!' is not allowed here; perhaps '?' was intended?}}{{18-19=?}} String!>(1, 2.0, "3") // expected-error {{'!' is not allowed here; perhaps '?' was intended?}}{{19-20=?}} let _: Generic<Int!, // expected-error {{'!' is not allowed here; perhaps '?' was intended?}}{{19-20=?}} Float!, // expected-error {{'!' is not allowed here; perhaps '?' was intended?}}{{21-22=?}} String!> = Generic(1, 2.0, "3") // expected-error {{'!' is not allowed here; perhaps '?' was intended?}}{{22-23=?}} func vararg(_ first: Int, more: Int!...) { // expected-error {{'!' is not allowed here; perhaps '?' was intended?}}{{36-37=?}} } func varargIdentifier(_ first: Int, more: ImplicitlyUnwrappedOptional<Int>...) { // expected-error {{'ImplicitlyUnwrappedOptional' has been renamed to 'Optional'}}{{43-70=Optional}} } func iuoInTuple() -> (Int!) { // expected-error {{'!' is not allowed here; perhaps '?' was intended?}}{{26-27=?}} return 1 } func iuoInTupleIdentifier() -> (ImplicitlyUnwrappedOptional<Int>) { // expected-error {{'ImplicitlyUnwrappedOptional' has been renamed to 'Optional'}}{{33-60=Optional}} return 1 } func iuoInTuple2() -> (Float, Int!) { // expected-error {{'!' is not allowed here; perhaps '?' was intended?}}{{34-35=?}} return (1.0, 1) } func iuoInTuple2Identifier() -> (Float, ImplicitlyUnwrappedOptional<Int>) { // expected-error {{'ImplicitlyUnwrappedOptional' has been renamed to 'Optional'}}{{41-68=Optional}} return (1.0, 1) } func takesFunc(_ fn: (Int!) -> Int) -> Int { // expected-error {{'!' is not allowed here; perhaps '?' was intended?}}{{26-27=?}} return fn(0) } func takesFuncIdentifier(_ fn: (ImplicitlyUnwrappedOptional<Int>) -> Int) -> Int { // expected-error {{'ImplicitlyUnwrappedOptional' has been renamed to 'Optional'}}{{33-60=Optional}} return fn(0) } func takesFunc2(_ fn: (Int) -> Int!) -> Int { // expected-error {{'!' is not allowed here; perhaps '?' was intended?}}{{35-36=?}} return fn(0)! } func takesFunc2Identifier(_ fn: (Int) -> ImplicitlyUnwrappedOptional<Int>) -> Int { // expected-error {{'ImplicitlyUnwrappedOptional' has been renamed to 'Optional'}}{{42-69=Optional}} return fn(0)! } func returnsFunc() -> (Int!) -> Int { // expected-error {{'!' is not allowed here; perhaps '?' was intended?}}{{27-28=?}} return { $0! } } func returnsFuncIdentifier() -> (ImplicitlyUnwrappedOptional<Int>) -> Int { // expected-error {{'ImplicitlyUnwrappedOptional' has been renamed to 'Optional'}}{{34-61=Optional}} return { $0! } } func returnsFunc2() -> (Int) -> Int! { // expected-error {{'!' is not allowed here; perhaps '?' was intended?}}{{36-37=?}} return { $0 } } func returnsFunc2Identifier() -> (Int) -> ImplicitlyUnwrappedOptional<Int> { // expected-error {{'ImplicitlyUnwrappedOptional' has been renamed to 'Optional'}}{{43-70=Optional}} return { $0 } } let x0 = 1 as ImplicitlyUnwrappedOptional // expected-error {{'ImplicitlyUnwrappedOptional' has been renamed to 'Optional'}}{{15-42=Optional}} let x: Int? = 1 let y0: Int = x as Int! // expected-error {{using '!' is not allowed here; perhaps '?' was intended?}}{{23-24=?}} let y1: Int = (x as Int!)! // expected-error {{using '!' is not allowed here; perhaps '?' was intended?}}{{24-25=?}} let z0: Int = x as! Int! // expected-error {{using '!' is not allowed here; perhaps '?' was intended?}}{{24-25=?}} // expected-warning@-1 {{forced cast from 'Int?' to 'Int' only unwraps optionals; did you mean to use '!'?}} let z1: Int = (x as! Int!)! // expected-error {{using '!' is not allowed here; perhaps '?' was intended?}}{{25-26=?}} // expected-warning@-1 {{forced cast of 'Int?' to same type has no effect}} let w0: Int = (x as? Int!)! // expected-warning {{conditional cast from 'Int?' to 'Int?' always succeeds}} // expected-error@-1 {{using '!' is not allowed here; perhaps '?' was intended?}}{{25-26=?}} let w1: Int = (x as? Int!)!! // expected-warning {{conditional cast from 'Int?' to 'Int?' always succeeds}} // expected-error@-1 {{using '!' is not allowed here; perhaps '?' was intended?}}{{25-26=?}} func overloadedByOptionality(_ a: inout Int!) {} // expected-note@-1 {{'overloadedByOptionality' previously declared here}} func overloadedByOptionality(_ a: inout Int?) {} // expected-error@-1 {{invalid redeclaration of 'overloadedByOptionality'}} struct T { let i: Int! var j: Int! let k: Int } func select(i: Int!, m: Int, t: T) { let _ = i ? i : m // expected-error {{optional type 'Int?' cannot be used as a boolean; test for '!= nil' instead}} {{11-11=(}} {{12-12= != nil)}} let _ = t.i ? t.j : t.k // expected-error {{optional type 'Int?' cannot be used as a boolean; test for '!= nil' instead}} {{11-11=(}} {{14-14= != nil)}} }
apache-2.0
7103d52991eacc6de98c9c35be615c95
49.388393
191
0.646053
3.870713
false
false
false
false
guumeyer/MarveListHeroes
MarvelHeroes/Extensions/String+Extension.swift
1
788
// // String+Extension.swift // MarvelHeros // // Created by gustavo r meyer on 8/12/17. // Copyright © 2017 gustavo r meyer. All rights reserved. // import Foundation extension String { func md5() -> String! { let str = self.cString(using: String.Encoding.utf8) let strLen = CUnsignedInt(self.lengthOfBytes(using: String.Encoding.utf8)) let digestLen = Int(CC_MD5_DIGEST_LENGTH) let result = UnsafeMutablePointer<CUnsignedChar>.allocate(capacity: digestLen) CC_MD5(str!, strLen, result) let hash = NSMutableString() for i in 0..<digestLen { hash.appendFormat("%02x", result[i]) } result.deinitialize() return String(format: hash as String) } }
apache-2.0
850e1c7127d647b1608c0202a25e8717
26.137931
86
0.60864
3.994924
false
false
false
false
kalanyuz/SwiftR
CommonSource/common/SRSplashBGView.swift
1
4932
// // NSSpashBGView.swift // NativeSigP // // Created by Kalanyu Zintus-art on 10/27/15. // Copyright © 2017 KalanyuZ. All rights reserved. // public struct SplashBGPosition { let TopLeft = CGPoint(x:0, y:1) let TopRight = CGPoint(x:1, y:1) let BottomLeft = CGPoint(x:0 ,y:0) let BottomRight = CGPoint(x:1, y:0) } public enum SplashDirection { case left case right } public protocol SRSplashViewDelegate { func splashAnimationEnded(startedFrom from: SplashDirection) } #if os(macOS) extension SRSplashBGView: CALayerDelegate {} #endif open class SRSplashBGView: SRView { public var delegate: SRSplashViewDelegate? let splashLayer = CALayer() fileprivate var splashColor : SRColor = SRColor.white fileprivate let initialSplashSize : CGFloat = 50 required override public init(frame frameRect: SRRect) { super.init(frame: frameRect) #if os(macOS) self.wantsLayer = true self.splashLayer.autoresizingMask = [.layerWidthSizable, .layerHeightSizable] self.layer?.autoresizingMask = [.layerWidthSizable, .layerHeightSizable] self.layer?.addSublayer(splashLayer) #elseif os(iOS) self.layer.addSublayer(splashLayer) #endif self.splashLayer.delegate = self } required public init?(coder: NSCoder) { super.init(coder: coder) #if os(macOS) self.wantsLayer = true self.splashLayer.autoresizingMask = [.layerWidthSizable, .layerHeightSizable] self.layer?.autoresizingMask = [.layerWidthSizable, .layerHeightSizable] self.layer?.addSublayer(splashLayer) #elseif os(iOS) self.layer.addSublayer(splashLayer) #endif } override open func draw(_ dirtyRect: SRRect) { super.draw(dirtyRect) // Drawing code here. } #if os(macOS) open func draw(_ layer: CALayer, in ctx: CGContext) { if layer === splashLayer { let circlePath = SRBezierPath() ctx.beginPath() circlePath.appendOval(in: CGRect(x: 0 - (initialSplashSize/2),y: 0 - (initialSplashSize/2), width: initialSplashSize, height: initialSplashSize)) ctx.addPath(circlePath.cgPath) ctx.closePath() ctx.setFillColor(splashColor.cgColor) ctx.fillPath() } } override open func fade(toAlpha alpha: CGFloat) { super.fade(toAlpha: alpha) } #elseif os(iOS) override open func draw(_ layer: CALayer, in ctx: CGContext) { if layer === splashLayer { let circlePath = SRBezierPath() ctx.beginPath() circlePath.append(SRBezierPath(ovalIn: CGRect(x: 0 - (initialSplashSize/2),y: 0 - (initialSplashSize/2),width: initialSplashSize, height: initialSplashSize))) ctx.addPath(circlePath.cgPath) ctx.closePath() ctx.setFillColor(splashColor.cgColor) ctx.fillPath() } } #endif open func initLayers() { self.splashLayer.bounds = self.bounds self.splashLayer.anchorPoint = CGPoint(x: 0, y: 0) self.splashLayer.contentsScale = 2 self.splashLayer.setNeedsDisplay() } open func splashFill(toColor color: SRColor,_ splashDirection: SplashDirection) { splashColor = color splashLayer.setNeedsDisplay() self.splashLayer.transform = CATransform3DMakeScale(1, 1, 1) if splashDirection == .right { CATransaction.begin() CATransaction.setAnimationDuration(0) let translate = CATransform3DTranslate(self.splashLayer.transform, self.bounds.maxX, 0, 0) self.splashLayer.transform = CATransform3DRotate(translate,CGFloat(M_PI), 0, -1, 0) CATransaction.commit() } CATransaction.begin() CATransaction.setCompletionBlock({ #if os(macOS) self.layer?.backgroundColor = self.splashColor.cgColor #elseif os(iOS) self.layer.backgroundColor = self.splashColor.cgColor #endif self.splashLayer.backgroundColor = self.splashColor.cgColor self.delegate?.splashAnimationEnded(startedFrom: splashDirection) }) let animation = CABasicAnimation(keyPath: "transform") animation.duration = 0.3 animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear) animation.toValue = NSValue(caTransform3D: CATransform3DScale(self.splashLayer.transform, round(self.bounds.size.width * 3 / initialSplashSize), round(self.bounds.size.width * 3 / initialSplashSize), 1)) animation.fillMode = kCAFillModeForwards animation.isRemovedOnCompletion = false self.splashLayer.add(animation, forKey: "transform") CATransaction.commit() } #if os(iOS) override open func layoutSublayers(of layer: CALayer) { splashLayer.setNeedsDisplay() self.layer.setNeedsDisplay() } #elseif os(macOS) open func layoutSublayers(of layer: CALayer) { splashLayer.setNeedsDisplay() self.layer!.setNeedsDisplay() } #endif }
apache-2.0
9ed71cd145774041b27103cc9f475186
27.017045
211
0.685459
3.995948
false
false
false
false
ncreated/Framing
FramingTests/FramingTests.swift
1
6912
// // FramingTests.swift // FramingTests // // Created by Maciek Grzybowski on 29.11.2016. // Copyright © 2016 ncreated. All rights reserved. // import XCTest import Framing class FramingTests: XCTestCase { func testInitialization() { let frame = Frame(x: 10, y: 10, width: 100, height: 100) XCTAssertEqual(frame.x, 10) XCTAssertEqual(frame.y, 10) XCTAssertEqual(frame.width, 100) XCTAssertEqual(frame.height, 100) XCTAssertEqual(frame.minX, 10) XCTAssertEqual(frame.minY, 10) XCTAssertEqual(frame.maxX, 110) XCTAssertEqual(frame.maxY, 110) let fromRect = Frame(rect: CGRect(x: 10, y: 10, width: 100, height: 100)) XCTAssertEqual(frame, fromRect) } func testInsetting() { let frame = Frame(width: 100, height: 100) let modified = frame.inset(top: 5, left: 10, bottom: 20, right: 30) XCTAssertEqual(modified, Frame(x: 10, y: 5, width: 60, height: 75)) } func testOffsetting() { let frame = Frame(width: 100, height: 100) let modified = frame.offsetBy(x: 10, y: 20) XCTAssertEqual(modified, Frame(x: 10, y: 20, width: 100, height: 100)) } func testPositioningAbove() { let base = Frame(width: 100, height: 100) let frame = Frame(width: 50, height: 50) let left = frame.putAbove(base, alignTo: .left) XCTAssertEqual(left, Frame(x: 0, y: -50, width: 50, height: 50)) let right = frame.putAbove(base, alignTo: .right) XCTAssertEqual(right, Frame(x: 50, y: -50, width: 50, height: 50)) let center = frame.putAbove(base, alignTo: .center) XCTAssertEqual(center, Frame(x: 25, y: -50, width: 50, height: 50)) } func testPositioningBelow() { let base = Frame(width: 100, height: 100) let frame = Frame(width: 50, height: 50) let left = frame.putBelow(base, alignTo: .left) XCTAssertEqual(left, Frame(x: 0, y: 100, width: 50, height: 50)) let right = frame.putBelow(base, alignTo: .right) XCTAssertEqual(right, Frame(x: 50, y: 100, width: 50, height: 50)) let center = frame.putBelow(base, alignTo: .center) XCTAssertEqual(center, Frame(x: 25, y: 100, width: 50, height: 50)) } func testPositioningOnLeft() { let base = Frame(width: 100, height: 100) let frame = Frame(width: 50, height: 50) let top = frame.putOnLeft(of: base, alignTo: .top) XCTAssertEqual(top, Frame(x: -50, y: 0, width: 50, height: 50)) let bottom = frame.putOnLeft(of: base, alignTo: .bottom) XCTAssertEqual(bottom, Frame(x: -50, y: 50, width: 50, height: 50)) let middle = frame.putOnLeft(of: base, alignTo: .middle) XCTAssertEqual(middle, Frame(x: -50, y: 25, width: 50, height: 50)) } func testPositioningOnRight() { let base = Frame(width: 100, height: 100) let frame = Frame(width: 50, height: 50) let top = frame.putOnRight(of: base, alignTo: .top) XCTAssertEqual(top, Frame(x: 100, y: 0, width: 50, height: 50)) let bottom = frame.putOnRight(of: base, alignTo: .bottom) XCTAssertEqual(bottom, Frame(x: 100, y: 50, width: 50, height: 50)) let middle = frame.putOnRight(of: base, alignTo: .middle) XCTAssertEqual(middle, Frame(x: 100, y: 25, width: 50, height: 50)) } func testPositioningInside() { let base = Frame(width: 100, height: 100) let frame = Frame(width: 50, height: 50) let topLeft = frame.putInside(base, alignTo: .topLeft) XCTAssertEqual(topLeft, Frame(x: 0, y: 0, width: 50, height: 50)) let topCenter = frame.putInside(base, alignTo: .topCenter) XCTAssertEqual(topCenter, Frame(x: 25, y: 0, width: 50, height: 50)) let topRight = frame.putInside(base, alignTo: .topRight) XCTAssertEqual(topRight, Frame(x: 50, y: 0, width: 50, height: 50)) let middleLeft = frame.putInside(base, alignTo: .middleLeft) XCTAssertEqual(middleLeft, Frame(x: 0, y: 25, width: 50, height: 50)) let middleCenter = frame.putInside(base, alignTo: .middleCenter) XCTAssertEqual(middleCenter, Frame(x: 25, y: 25, width: 50, height: 50)) let middleRight = frame.putInside(base, alignTo: .middleRight) XCTAssertEqual(middleRight, Frame(x: 50, y: 25, width: 50, height: 50)) let bottomLeft = frame.putInside(base, alignTo: .bottomLeft) XCTAssertEqual(bottomLeft, Frame(x: 0, y: 50, width: 50, height: 50)) let bottomCenter = frame.putInside(base, alignTo: .bottomCenter) XCTAssertEqual(bottomCenter, Frame(x: 25, y: 50, width: 50, height: 50)) let bottomRight = frame.putInside(base, alignTo: .bottomRight) XCTAssertEqual(bottomRight, Frame(x: 50, y: 50, width: 50, height: 50)) } func testDividingIntoEqualRows() { let frame = Frame(x: 100, y: 100, width: 120, height: 120) let row0 = frame.divideIntoEqual(rows: 3, take: 0) XCTAssertEqual(row0, Frame(x: 100, y: 100, width: 120, height: 40)) let row1 = frame.divideIntoEqual(rows: 3, take: 1) XCTAssertEqual(row1, Frame(x: 100, y: 140, width: 120, height: 40)) let row2 = frame.divideIntoEqual(rows: 3, take: 2) XCTAssertEqual(row2, Frame(x: 100, y: 180, width: 120, height: 40)) } func testDividingIntoEqualColumns() { let frame = Frame(x: 100, y: 100, width: 120, height: 120) let column0 = frame.divideIntoEqual(columns: 3, take: 0) XCTAssertEqual(column0, Frame(x: 100, y: 100, width: 40, height: 120)) let column1 = frame.divideIntoEqual(columns: 3, take: 1) XCTAssertEqual(column1, Frame(x: 140, y: 100, width: 40, height: 120)) let column2 = frame.divideIntoEqual(columns: 3, take: 2) XCTAssertEqual(column2, Frame(x: 180, y: 100, width: 40, height: 120)) } func testConditioning() { let frame = Frame(width: 100, height: 100) let modified = frame.if(condition: true, then: { $0.offsetBy(x: 10).inset(top: 5) }) XCTAssertEqual(modified, Frame(x: 10, y: 5, width: 100, height: 95)) let notModified = frame.if(false) { $0.offsetBy(x: 10).inset(top: 5) } XCTAssertEqual(notModified, frame) let notModified2 = frame.if(condition: false, then: { $0.offsetBy(x: 10).inset(top: 5) }, else: { $0.offsetBy(x: -10).inset(top: 5) }) XCTAssertEqual(notModified2, Frame(x: -10, y: 5, width: 100, height: 95)) } }
mit
891d8b6cf8c8caf50d35ecba5984db2a
38.947977
142
0.591231
3.645042
false
true
false
false
GhostSK/SpriteKitPractice
MagicTower/MagicTower/GameViewController.swift
1
1405
// // GameViewController.swift // MagicTower // // Created by 胡杨林 on 2017/4/28. // Copyright © 2017年 胡杨林. All rights reserved. // import UIKit import SpriteKit //import GameplayKit class GameViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() if let view = self.view as! SKView? { // Load the SKScene from 'GameScene.sks' let scene = testScene(size: (self.view?.frame.size)!) // Set the scale mode to scale to fit the window scene.scaleMode = .aspectFill // Present the scene view.presentScene(scene) view.ignoresSiblingOrder = true view.showsFPS = true view.showsNodeCount = true } } override var shouldAutorotate: Bool { return true } override var supportedInterfaceOrientations: UIInterfaceOrientationMask { if UIDevice.current.userInterfaceIdiom == .phone { return .allButUpsideDown } else { return .all } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Release any cached data, images, etc that aren't in use. } override var prefersStatusBarHidden: Bool { return true } }
apache-2.0
3fbe0664518ed115efe4a3ebffd4f885
23.821429
77
0.57482
5.305344
false
false
false
false
xivol/MCS-V3-Mobile
examples/uiKit/UIKitCatalog.playground/Pages/UIScrollView.xcplaygroundpage/Contents.swift
1
1601
//: # UIScrollView //: The UIScrollView class provides support for displaying content that is larger than the size of the application’s window. It enables users to scroll within that content by making swiping gestures, and to zoom in and back from portions of the content by making pinching gestures. //: //:[UIScrollView API Reference](https://developer.apple.com/reference/uikit/uiscrollview) import UIKit import PlaygroundSupport class Zoom: NSObject, UIScrollViewDelegate { let content: UIView? func viewForZooming(in scrollView: UIScrollView) -> UIView? { return content } func scrollViewDidZoom(_ scrollView: UIScrollView) { print("zooom") } init(content: UIView) { self.content = content } } //: ### Initialize Scroll View let scrollView = UIScrollView(frame: CGRect(x: 0, y: 0, width: 250, height: 400)) scrollView.bounces = true scrollView.backgroundColor = #colorLiteral(red: 1, green: 1, blue: 1, alpha: 1) //: ### Add Content let imageView = UIImageView(image: #imageLiteral(resourceName: "swift.png")) scrollView.contentSize = imageView.image!.size scrollView.addSubview(imageView) //: ### Add Delegate for Zoom //??? Zoom seems to be broken in Playground Simulator ??? let zoomDelegate = Zoom(content: imageView) scrollView.bouncesZoom = false scrollView.minimumZoomScale = scrollView.bounds.width / imageView.bounds.width scrollView.maximumZoomScale = 1 scrollView.delegate = zoomDelegate PlaygroundPage.current.liveView = scrollView //: [Previous](@previous) | [Table of Contents](TableOfContents) | [Next](@next)
mit
66f7896328ef362436e153e2ab1480c1
38.975
281
0.737336
4.542614
false
false
false
false
syoutsey/swift-corelibs-foundation
Foundation/NSURLError.swift
5
6179
// This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // /* @discussion Constants used by NSError to differentiate between "domains" of error codes, serving as a discriminator for error codes that originate from different subsystems or sources. @constant NSURLErrorDomain Indicates an NSURL error. */ public let NSURLErrorDomain: String = "NSURLErrorDomain" /*! @const NSURLErrorFailingURLErrorKey @abstract The NSError userInfo dictionary key used to store and retrieve the URL which caused a load to fail. */ public let NSURLErrorFailingURLErrorKey: String = "NSErrorFailingURLKey" /*! @const NSURLErrorFailingURLStringErrorKey @abstract The NSError userInfo dictionary key used to store and retrieve the NSString object for the URL which caused a load to fail. @discussion This constant supersedes NSErrorFailingURLStringKey, which was deprecated in Mac OS X 10.6. Both constants refer to the same value for backward-compatibility, but this symbol name has a better prefix. */ public let NSURLErrorFailingURLStringErrorKey: String = "NSErrorFailingURLStringKey" /*! @const NSErrorFailingURLStringKey @abstract The NSError userInfo dictionary key used to store and retrieve the NSString object for the URL which caused a load to fail. @discussion This constant is deprecated in Mac OS X 10.6, and is superseded by NSURLErrorFailingURLStringErrorKey. Both constants refer to the same value for backward-compatibility, but the new symbol name has a better prefix. */ /*! @const NSURLErrorFailingURLPeerTrustErrorKey @abstract The NSError userInfo dictionary key used to store and retrieve the SecTrustRef object representing the state of a failed SSL handshake. */ public let NSURLErrorFailingURLPeerTrustErrorKey: String = "NSURLErrorFailingURLPeerTrustErrorKey" /*! @const NSURLErrorBackgroundTaskCancelledReasonKey @abstract The NSError userInfo dictionary key used to store and retrieve the NSNumber corresponding to the reason why a background NSURLSessionTask was cancelled */ public let NSURLErrorBackgroundTaskCancelledReasonKey: String = "NSURLErrorBackgroundTaskCancelledReasonKey" /*! @enum Codes associated with NSURLErrorBackgroundTaskCancelledReasonKey @abstract Constants used by NSError to indicate why a background NSURLSessionTask was cancelled. */ public var NSURLErrorCancelledReasonUserForceQuitApplication: Int { return 0 } public var NSURLErrorCancelledReasonBackgroundUpdatesDisabled: Int { return 1 } public var NSURLErrorCancelledReasonInsufficientSystemResources: Int { return 2 } /*! @enum NSURL-related Error Codes @abstract Constants used by NSError to indicate errors in the NSURL domain */ public var NSURLErrorUnknown: Int { return -1 } public var NSURLErrorCancelled: Int { return -999 } public var NSURLErrorBadURL: Int { return -1000 } public var NSURLErrorTimedOut: Int { return -1001 } public var NSURLErrorUnsupportedURL: Int { return -1002 } public var NSURLErrorCannotFindHost: Int { return -1003 } public var NSURLErrorCannotConnectToHost: Int { return -1004 } public var NSURLErrorNetworkConnectionLost: Int { return -1005 } public var NSURLErrorDNSLookupFailed: Int { return -1006 } public var NSURLErrorHTTPTooManyRedirects: Int { return -1007 } public var NSURLErrorResourceUnavailable: Int { return -1008 } public var NSURLErrorNotConnectedToInternet: Int { return -1009 } public var NSURLErrorRedirectToNonExistentLocation: Int { return -1010 } public var NSURLErrorBadServerResponse: Int { return -1011 } public var NSURLErrorUserCancelledAuthentication: Int { return -1012 } public var NSURLErrorUserAuthenticationRequired: Int { return -1013 } public var NSURLErrorZeroByteResource: Int { return -1014 } public var NSURLErrorCannotDecodeRawData: Int { return -1015 } public var NSURLErrorCannotDecodeContentData: Int { return -1016 } public var NSURLErrorCannotParseResponse: Int { return -1017 } public var NSURLErrorAppTransportSecurityRequiresSecureConnection: Int { return -1022 } public var NSURLErrorFileDoesNotExist: Int { return -1100 } public var NSURLErrorFileIsDirectory: Int { return -1101 } public var NSURLErrorNoPermissionsToReadFile: Int { return -1102 } public var NSURLErrorDataLengthExceedsMaximum: Int { return -1103 } // SSL errors public var NSURLErrorSecureConnectionFailed: Int { return -1201 } public var NSURLErrorServerCertificateHasBadDate: Int { return -1202 } public var NSURLErrorServerCertificateUntrusted: Int { return -1203 } public var NSURLErrorServerCertificateHasUnknownRoot: Int { return -1204 } public var NSURLErrorServerCertificateNotYetValid: Int { return -1205 } public var NSURLErrorClientCertificateRejected: Int { return -1206 } public var NSURLErrorClientCertificateRequired: Int { return -1207 } public var NSURLErrorCannotLoadFromNetwork: Int { return -2000 } // Download and file I/O errors public var NSURLErrorCannotCreateFile: Int { return -3000 } public var NSURLErrorCannotOpenFile: Int { return -3001 } public var NSURLErrorCannotCloseFile: Int { return -3002 } public var NSURLErrorCannotWriteToFile: Int { return -3003 } public var NSURLErrorCannotRemoveFile: Int { return -3004 } public var NSURLErrorCannotMoveFile: Int { return -3005 } public var NSURLErrorDownloadDecodingFailedMidStream: Int { return -3006 } public var NSURLErrorDownloadDecodingFailedToComplete: Int { return -3007 } public var NSURLErrorInternationalRoamingOff: Int { return -1018 } public var NSURLErrorCallIsActive: Int { return -1019 } public var NSURLErrorDataNotAllowed: Int { return -1020 } public var NSURLErrorRequestBodyStreamExhausted: Int { return -1021 } public var NSURLErrorBackgroundSessionRequiresSharedContainer: Int { return -995 } public var NSURLErrorBackgroundSessionInUseByAnotherProcess: Int { return -996 } public var NSURLErrorBackgroundSessionWasDisconnected: Int { return -997 }
apache-2.0
33658b8dbc1d7ed13f56227527691eec
51.811966
231
0.805794
5.236441
false
false
false
false
multinerd/Mia
Mia/Libraries/DeviceKit/Application.swift
1
1845
// MARK: - *** Application *** public struct Application { /// A UUID that may be used to uniquely identify the device, same across apps from a single vendor. public static var identifierForVendor: UUID? { return UIDevice.current.identifierForVendor! } } // MARK: - *** Bundle *** extension Application { public enum BundleInfo: String { case name = "CFBundleName" case displayName = "CFBundleDisplayName" case identifier = "CFBundleIdentifier" case version = "CFBundleShortVersionString" case build = "CFBundleVersion" case executable = "CFBundleExecutable" /// Returns the app's product name if display name is not available. public static var dynamicName: BundleInfo { return BundleInfo.displayName.description.isEmpty ? BundleInfo.name : BundleInfo.displayName } } } extension Application.BundleInfo: CustomStringConvertible { public var description: String { return Bundle.main.infoDictionary?[self.rawValue] as? String ?? "" } } // MARK: - *** Environment *** extension Application { /// Determines whether the application was launched from Xcode @available(*, deprecated, message: "This code will only execute when launching from Xcode.") public static var isBeingDebugged: Bool { var info = kinfo_proc() var mib: [Int32] = [ CTL_KERN, KERN_PROC, KERN_PROC_PID, getpid() ] var size = MemoryLayout<kinfo_proc>.stride let junk = sysctl(&mib, UInt32(mib.count), &info, &size, nil, 0) assert(junk == 0, "sysctl failed") return (info.kp_proc.p_flag & P_TRACED) != 0 } /// Determines whether the application is running tests public static var isRunningUnitTests: Bool { return NSClassFromString("XCTest") != nil } }
mit
3783bc734021d8a8188bb5f557ca197c
29.75
104
0.659079
4.589552
false
false
false
false
kyouko-taiga/anzen
Sources/Sema/SubstitutionTable.swift
1
5778
import AST private final class MappingRef { var value: [TypeVariable: TypeBase] init(_ value: [TypeVariable: TypeBase] = [:]) { self.value = value } } public struct SubstitutionTable { private var mappingsRef: MappingRef private var mappings: [TypeVariable: TypeBase] { get { return mappingsRef.value } set { guard isKnownUniquelyReferenced(&mappingsRef) else { mappingsRef = MappingRef(newValue) return } mappingsRef.value = newValue } } public init(_ mappings: [TypeVariable: TypeBase] = [:]) { self.mappingsRef = MappingRef(mappings) } public func substitution(for type: TypeBase) -> TypeBase { if let var_ = type as? TypeVariable { return mappings[var_].map { substitution(for: $0) } ?? var_ } return type } public mutating func set(substitution: TypeBase, for var_: TypeVariable) { let walked = self.substitution(for: var_) guard let key = walked as? TypeVariable else { assert(walked == substitution, "inconsistent substitution") return } assert(key != substitution, "occur check failed") mappings[key] = substitution } public func reified(in context: ASTContext) -> SubstitutionTable { var visited: [NominalType] = [] var reifiedMappings: [TypeVariable: TypeBase] = [:] for (key, value) in mappings { reifiedMappings[key] = reify(type: value, in: context, skipping: &visited) } return SubstitutionTable(reifiedMappings) } public func reify(type: TypeBase, in context: ASTContext) -> TypeBase { var visited: [NominalType] = [] return reify(type: type, in: context, skipping: &visited) } public func reify(type: TypeBase, in context: ASTContext, skipping visited: inout [NominalType]) -> TypeBase { let walked = substitution(for: type) if let result = visited.first(where: { $0 == walked }) { return result } switch walked { case let t as BoundGenericType: let unbound = reify(type: t.unboundType, in: context, skipping: &visited) if let placeholder = unbound as? PlaceholderType { return reify(type: t.bindings[placeholder]!, in: context, skipping: &visited) } let reifiedBindings = Dictionary( uniqueKeysWithValues: t.bindings.map({ ($0.key, reify(type: $0.value, in: context, skipping: &visited)) })) return BoundGenericType(unboundType: unbound, bindings: reifiedBindings) case let t as NominalType: visited.append(t) for symbol in t.members { symbol.type = reify(type: symbol.type!, in: context, skipping: &visited) } return t case let t as FunctionType: return context.getFunctionType( from: t.domain.map({ Parameter( label: $0.label, type: reify(type: $0.type, in: context, skipping: &visited)) }), to: reify(type: t.codomain, in: context, skipping: &visited), placeholders: t.placeholders) default: return walked } } /// Determines whether this substitution table is equivalent to another one, up to the variables /// they share. /// /// Let a substitution table be a partial function `V -> T` where `V` is the set of type variables /// and `T` the set of types. Two tables `t1`, `t2` are equivalent if for all variable `v` such /// both `t1` and `t2` are defined `t1(v) = t2(v)`. Variables outside of represent intermediate /// results introduced by the solver, and irrelevant after reification. public func isEquivalent(to other: SubstitutionTable) -> Bool { if self.mappingsRef === other.mappingsRef { // Nothing to do if both tables are trivially equal. return true } for key in Set(mappings.keys).intersection(other.mappings.keys) { guard mappings[key] == other.mappings[key] else { return false } } return true } /// Determines whether this substitution table is more specific than another one, up to the /// variables they share. /// /// Let a substitution table be a partial function `V -> T` where `V` is the set of type variables /// and `T` the set of types. A table `t1` is said more specific than an other table `t2` if the /// set of variables `v` such that `t1(v) < t2(v)` is bigger than the set of variables `w` such /// that `t1(w) > t2(w)`. Variables outside of both domains represent intermediate results /// introduced by the solver, and irrelevant after reification. public func isMoreSpecific(than other: SubstitutionTable) -> Bool { var score = 0 for key in Set(mappings.keys).intersection(other.mappings.keys) { if mappings[key]!.isSubtype(of: other.mappings[key]!) { score -= 1 } else if mappings[key]!.isSubtype(of: other.mappings[key]!) { score += 1 } } return score < 0 } } extension SubstitutionTable: Hashable { public func hash(into hasher: inout Hasher) { for key in mappings.keys { hasher.combine(key) } } public static func == (lhs: SubstitutionTable, rhs: SubstitutionTable) -> Bool { return lhs.mappingsRef === rhs.mappingsRef || lhs.mappings == rhs.mappings } } extension SubstitutionTable: Sequence { public func makeIterator() -> Dictionary<TypeVariable, TypeBase>.Iterator { return mappings.makeIterator() } } extension SubstitutionTable: ExpressibleByDictionaryLiteral { public init(dictionaryLiteral elements: (TypeVariable, TypeBase)...) { self.init(Dictionary(uniqueKeysWithValues: elements)) } } extension SubstitutionTable: CustomDebugStringConvertible { public var debugDescription: String { var result = "" for (v, t) in self.mappings { result += "\(v) => \(t)\n" } return result } }
apache-2.0
f573e681bc2ecca9131296d30671839a
29.734043
100
0.658705
4.040559
false
false
false
false
congncif/SiFUtilities
Example/Pods/Boardy/Boardy/Core/BoardType/Flow.swift
1
12876
// // Flow.swift // Boardy // // Created by NGUYEN CHI CONG on 3/18/20. // import Foundation /// Special data type which should be forwarded through all of steps of the flow. public protocol BoardFlowAction {} public typealias FlowID = BoardID public protocol BoardFlow { func match(with output: BoardOutputModel) -> Bool func doNext(with output: BoardOutputModel) } public protocol FlowManageable: AnyObject { var flows: [BoardFlow] { get } @discardableResult func registerFlow(_ flow: BoardFlow) -> Self func resetFlows() } public extension FlowManageable { @discardableResult func registerFlows(_ flows: [BoardFlow]) -> Self { flows.forEach { [unowned self] in self.registerFlow($0) } return self } /// A General Flow doesn't check identifier of sender, handler will be executed whenever data matches with Output type. This mean it will be applied for all senders in workflow. @discardableResult func registerGeneralFlow<Output>(uniqueOutputType: Output.Type = Output.self, nextHandler: @escaping (Output) -> Void) -> Self { let generalFlow = BoardActivateFlow(matcher: { _ in true }, nextHandler: { data in guard let output = data as? Output else { return } nextHandler(output) }) registerFlow(generalFlow) return self } /// A General Flow doesn't check identifier of sender, handler will be executed whenever data matches with Output type. This mean it will be applied for all senders in workflow. @discardableResult func registerGeneralFlow<Target, Output>( target: Target, uniqueOutputType: Output.Type = Output.self, nextHandler: @escaping (Target, Output) -> Void ) -> Self { let box = ObjectBox() box.setObject(target) let generalFlow = BoardActivateFlow(matcher: { _ in true }, nextHandler: { [box] data in guard let output = data as? Output, let target = box.unboxed(Target.self) else { return } nextHandler(target, output) }) registerFlow(generalFlow) return self } /// Default flow is a dedicated flow with specified output type. If data matches with Output type, handler will be executed, otherwise the handler will be skipped. @discardableResult func registerFlow<Output>( matchedIdentifiers: [FlowID], uniqueOutputType: Output.Type = Output.self, nextHandler: @escaping (Output) -> Void ) -> Self { let generalFlow = BoardActivateFlow(matchedIdentifiers: matchedIdentifiers, dedicatedNextHandler: { (output: Output?) in guard let output = output else { return } nextHandler(output) }) registerFlow(generalFlow) return self } /// Default flow is a dedicated flow with specified output type. If data matches with Output type, handler will be executed, otherwise the handler will be skipped. @discardableResult func registerFlow<Target, Output>( matchedIdentifiers: [FlowID], target: Target, uniqueOutputType: Output.Type = Output.self, nextHandler: @escaping (Target, Output) -> Void ) -> Self { let box = ObjectBox() box.setObject(target) let generalFlow = BoardActivateFlow(matchedIdentifiers: matchedIdentifiers, dedicatedNextHandler: { [box] (output: Output?) in guard let output = output, let target = box.unboxed(Target.self) else { return } nextHandler(target, output) }) registerFlow(generalFlow) return self } /// Guaranteed Flow ensures data must match with Output type if not handler will fatal in debug and will be skipped in release mode. @discardableResult func registerGuaranteedFlow<Target, Output>( matchedIdentifiers: [FlowID], target: Target, uniqueOutputType: Output.Type = Output.self, handler: @escaping (Target, Output) -> Void ) -> Self { let box = ObjectBox() box.setObject(target) let generalFlow = BoardActivateFlow(matchedIdentifiers: matchedIdentifiers, guaranteedNextHandler: { [box] (output: Output) in if let target = box.unboxed(Target.self) { handler(target, output) } }) registerFlow(generalFlow) return self } /// Chain Flow handles step by step of chain of handlers until a handler in chain is executed. Eventually handler is mandatory to register this flow. func registerChainFlow<Target>(matchedIdentifiers: [FlowID], target: Target) -> ChainBoardFlow<Target> { let flow = ChainBoardFlow(manager: self, target: target) { matchedIdentifiers.contains($0.identifier) } return flow } } public extension FlowManageable where Self: MotherboardType { /// Flow Steps will skip Silent Data Types (`BoardFlowAction`, `BoardInputModel`, `BoardCommandModel`, `CompleteAction`). So to register Flow Steps, the Board InputType can't be Silent Data Types. If you still want to handle Silent Data Types as Input of your board, you must register by regular `BoardActivateFlow`. @discardableResult func registerFlowSteps(_ flowSteps: [IDFlowStep]) -> Self { let activateFlows = flowSteps.map { flowStep in BoardActivateFlow( matcher: { board -> Bool in flowStep.source == board.identifier }, nextHandler: { [weak self] data in // Guaranteed data is not Silent Data Types otherwise skip handling. guard !isSilentData(data) else { return } self?.activateBoard(identifier: flowStep.destination, withOption: data) } ) } registerFlows(activateFlows) return self } } private final class HandlerInfo<Target> { let handler: (Target, BoardOutputModel) -> Bool init(handler: @escaping (Target, BoardOutputModel) -> Bool) { self.handler = handler } } public final class ChainBoardFlow<Target>: BoardFlow { private var handlers: [HandlerInfo<Target>] = [] private let matcher: (BoardOutputModel) -> Bool private unowned let manager: FlowManageable private let box = ObjectBox() private var target: Target? { return box.unboxed(Target.self) } init(manager: FlowManageable, target: Target, matcher: @escaping (BoardOutputModel) -> Bool) { self.manager = manager self.matcher = matcher box.setObject(target) } public func handle<Output>(outputType: Output.Type, handler: @escaping (Target, Output) -> Void) -> Self { let matcher = HandlerInfo { (object: Target, output) in let data = output.data if let output = data as? Output { handler(object, output) return true } else { return false } } handlers.append(matcher) return self } @discardableResult public func eventuallyHandle<Output>(outputType: Output.Type, handler: @escaping (Target, Output?) -> Void) -> FlowManageable { let matcher = HandlerInfo { (object: Target, output) in let data = output.data let output = data as? Output handler(object, output) return true } handlers.append(matcher) return manager.registerFlow(self) } @discardableResult public func eventuallyHandle(skipSilentData: Bool = true, handler: @escaping (Target, Any?) -> Void) -> FlowManageable { let matcher = HandlerInfo { (object: Target, output) in let data = output.data if skipSilentData, isSilentData(data) { return true } handler(object, data) return true } handlers.append(matcher) return manager.registerFlow(self) } @discardableResult public func eventuallySkipHandling() -> FlowManageable { return eventuallyHandle { _, _ in } } public func match(with output: BoardOutputModel) -> Bool { return matcher(output) } public func doNext(with output: BoardOutputModel) { guard let target = target else { return } for matcher in handlers { if matcher.handler(target, output) { return } } } } public struct BoardActivateFlow: BoardFlow { private let matcher: (BoardOutputModel) -> Bool private let outputNextHandler: (BoardOutputModel) -> Void public init( matcher: @escaping (BoardOutputModel) -> Bool, outputNextHandler: @escaping (BoardOutputModel) -> Void ) { self.matcher = matcher self.outputNextHandler = outputNextHandler } public init( matcher: @escaping (BoardOutputModel) -> Bool, nextHandler: @escaping (Any?) -> Void ) { self.matcher = matcher outputNextHandler = { nextHandler($0.data) } } public init<Output>( matcher: @escaping (BoardOutputModel) -> Bool, dedicatedNextHandler: @escaping (Output?) -> Void ) { self.matcher = matcher outputNextHandler = { output in let data = output.data as? Output dedicatedNextHandler(data) } } public init<Output>( matcher: @escaping (BoardOutputModel) -> Bool, guaranteedNextHandler: @escaping (Output) -> Void ) { self.matcher = matcher outputNextHandler = { output in guard let data = output.data as? Output else { // Guaranteed output is Silent Data Types otherwise raise an assertion. guard isSilentData(output.data) else { assertionFailure("🔥 [Flow with mismatch data type] [\(output.identifier)] Cannot convert output of board \(output.identifier) from type \(String(describing: output.data)) to type \(Output.self)") return } return } guaranteedNextHandler(data) } } public init(matchedIdentifiers: [FlowID], outputNextHandler: @escaping (BoardOutputModel) -> Void) { self.init(matcher: { matchedIdentifiers.contains($0.identifier) }, outputNextHandler: outputNextHandler) } public init(matchedIdentifiers: [FlowID], nextHandler: @escaping (Any?) -> Void) { self.init(matcher: { matchedIdentifiers.contains($0.identifier) }, nextHandler: nextHandler) } public init<Output>(matchedIdentifiers: [FlowID], dedicatedNextHandler: @escaping (Output?) -> Void) { self.init(matcher: { matchedIdentifiers.contains($0.identifier) }, dedicatedNextHandler: dedicatedNextHandler) } public init<Output>(matchedIdentifiers: [FlowID], guaranteedNextHandler: @escaping (Output) -> Void) { self.init(matcher: { matchedIdentifiers.contains($0.identifier) }, guaranteedNextHandler: guaranteedNextHandler) } public func match(with output: BoardOutputModel) -> Bool { return matcher(output) } public func doNext(with output: BoardOutputModel) { outputNextHandler(output) } } public struct IDFlowStep { public let source: FlowID public let destination: FlowID public init(source: FlowID, destination: FlowID) { self.source = source self.destination = destination } } infix operator ->>: MultiplicationPrecedence public func ->> (left: FlowID, right: FlowID) -> [IDFlowStep] { return [IDFlowStep(source: left, destination: right)] } public func ->> (left: [IDFlowStep], right: FlowID) -> [IDFlowStep] { guard let lastLeft = left.last else { assertionFailure("Empty flow is not allowed") return [] } return left + [IDFlowStep(source: lastLeft.destination, destination: right)] } public typealias FlowMotherboard = MotherboardType & FlowManageable public extension BoardDelegate where Self: FlowManageable { func board(_ board: IdentifiableBoard, didSendData data: Any?) { // Handle dedicated flow actions let output = OutputModel(identifier: board.identifier, data: data) flows.filter { $0.match(with: output) }.forEach { $0.doNext(with: output) } } } // MARK: - Forward functions public extension FlowManageable { func forwardActionFlow(to board: IdentifiableBoard) { registerGeneralFlow { [weak board] in board?.sendFlowAction($0) } } func forwardActivationFlow(to board: IdentifiableBoard) { registerGeneralFlow { [weak board] in board?.nextToBoard(model: $0) } } } struct OutputModel: BoardOutputModel { let identifier: BoardID let data: Any? }
mit
5a952e006ea91331e59fd8335e8826ec
34.758333
320
0.640332
4.535941
false
false
false
false
drinkapoint/DrinkPoint-iOS
DrinkPoint/DrinkPoint/UploadAddressBookViewController.swift
1
2858
//// //// UploadAddressBookViewController.swift //// DrinkPoint //// //// Created by Paul Kirk Adams on 7/27/16. //// Copyright © 2016 Paul Kirk Adams. All rights reserved. //// // //import UIKit //import DigitsKit // //class UploadAddressBookViewController: UIViewController { // // override func viewDidLoad() { // super.viewDidLoad() // let authenticateButton = DGTAuthenticateButton { session, error in // if session != nil { // dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(1 * NSEC_PER_SEC)), dispatch_get_main_queue()) { // self.uploadDigitsContacts(session) // } // } // } // authenticateButton.center = self.view.center // authenticateButton.digitsAppearance = self.makeDigitsTheme() // self.view.addSubview(authenticateButton) // } // // func makeDigitsTheme() -> DGTAppearance { // let digitsTheme = DGTAppearance(); // digitsTheme.bodyFont = UIFont(name: "SanFranciscoDisplay-Light", size: 16); // digitsTheme.labelFont = UIFont(name: "SanFranciscoDisplay-Regular", size: 17); // digitsTheme.accentColor = UIColor.orangeColor() // digitsTheme.backgroundColor = UIColor.blackColor() // digitsTheme.logoImage = UIImage(named: "DrinkPoint") // return digitsTheme; // } // // private func uploadDigitsContacts(session: DGTSession) { // let digitsContacts = DGTContacts(userSession: session) // digitsContacts.startContactsUploadWithCompletion { result, error in // if result != nil { // // The result object tells you how many of the contacts were uploaded. // print("DrinkPoint successfully uploaded \(result.numberOfUploadedContacts) of your \(result.totalContacts) contacts!") // } // self.findDigitsFriends(session) // } // } // // private func findDigitsFriends(session: DGTSession) { // let digitsContacts = DGTContacts(userSession: session) // digitsContacts.lookupContactMatchesWithCursor(nil) { (matches, nextCursor, error) -> Void in // print("Friends:") // for digitsUser in matches { // print("Digits ID: \(digitsUser.userID)") // } // dispatch_async(dispatch_get_main_queue()) { // let message = "DrinkPoint found \(matches.count) of your friends!" // let alertController = UIAlertController(title: "Lookup complete", message: message, preferredStyle: .Alert) // let cancel = UIAlertAction(title: "Got It!", style: .Cancel, handler:nil) // alertController.addAction(cancel) // self.presentViewController(alertController, animated: true, completion: nil) // } // } // } //}
mit
9c292d0841fd5b6172ca3d592f6af547
42.953846
137
0.613231
4.220089
false
false
false
false
ismailbozk/ObjectScanner
ObjectScanner/ObjectScanner/Views/OSPointCloudView.swift
1
13279
// // OSPointCloudView.swift // ObjectScanner // // Created by Ismail Bozkurt on 01/08/2015. // The MIT License (MIT) // // Copyright (c) 2015 Ismail Bozkurt // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software // and associated documentation files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following conditions: // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING // BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // import UIKit import Metal import QuartzCore struct Uniforms { var viewMatrix : Matrix4 = Matrix4.Identity; var projectionMatrix : Matrix4 = Matrix4.Identity; } let kOSPointCloudViewVelocityScale: CGFloat = 0.01; let kOSPointCloudViewDamping: CGFloat = 0.05; let kOSPointCloudViewXAxis: Vector3 = Vector3(1.0, 0.0, 0.0); let kOSPointCloudViewYAxis: Vector3 = Vector3(0.0, 1.0, 0.0); class OSPointCloudView: UIView, OSContentLoadingProtocol{ fileprivate let panGestureRecognizer: UIGestureRecognizer = UIPanGestureRecognizer(); fileprivate var angularVelocity: CGPoint = CGPoint.zero; fileprivate var angle: CGPoint = CGPoint.zero; fileprivate var lastFrameTime: TimeInterval = 0.0; fileprivate var metalLayer: CAMetalLayer! = nil; fileprivate static let device: MTLDevice = MTLCreateSystemDefaultDevice()!; fileprivate static let commandQueue: MTLCommandQueue = OSPointCloudView.device.makeCommandQueue(); fileprivate static var pipelineState: MTLRenderPipelineState?; fileprivate static var depthStencilState: MTLDepthStencilState?; fileprivate var timer: CADisplayLink?; fileprivate var isReadForAction = false; fileprivate var vertices: [OSPoint] = [OSPoint](); fileprivate let threadSafeConcurrentVertexAccessQueue = DispatchQueue(label: "OSPointCloudViewThreadSafeConcurrentVertexAccessQueue", attributes: DispatchQueue.Attributes.concurrent); fileprivate var vertexBuffer: MTLBuffer?; fileprivate let threadSafeConcurrentVertexBufferAccessQueue : DispatchQueue = DispatchQueue(label: "OSPointCloudViewThreadSafeConcurrentVertexBufferAccessQueue", attributes: DispatchQueue.Attributes.concurrent);//don't use that queue anywhere else other than custom getters and setters for vertexBuffer property. fileprivate var transformationMatrices: [Matrix4] = [Matrix4](); fileprivate var transformationBuffer: MTLBuffer?; fileprivate let threadSafeConcurrentTransformationBufferAccessQueue : DispatchQueue = DispatchQueue(label: "OSPointCloudViewThreadSafeConcurrentTransformationBufferAccessQueue", attributes: DispatchQueue.Attributes.concurrent);//don't use that queue anywhere else other than custom getters and setters for transformationBuffer property. fileprivate var uniforms: Uniforms = Uniforms(); fileprivate var uniformBuffer: MTLBuffer?; // MARK: Lifecycle required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder); panGestureRecognizer.addTarget(self, action: #selector(OSPointCloudView.gestureRecognizerDidRecognize(_:))); self .addGestureRecognizer(panGestureRecognizer); metalLayer = (self.layer as! CAMetalLayer); metalLayer.device = OSPointCloudView.device; metalLayer.pixelFormat = .bgra8Unorm; metalLayer.framebufferOnly = true; timer = CADisplayLink(target: self, selector: #selector(OSPointCloudView.tic(_:))) timer!.add(to: RunLoop.main, forMode: RunLoopMode.defaultRunLoopMode) self.lastFrameTime = CFAbsoluteTimeGetCurrent(); } override var frame: CGRect{ didSet { if (self.metalLayer != nil) { let scale : CGFloat = UIScreen.main.scale; self.metalLayer.drawableSize = CGSize(width: self.bounds.width * scale, height: self.bounds.height * scale); } } } deinit { self.timer?.invalidate(); } override class var layerClass : AnyClass { return CAMetalLayer.self; } // MARK: Display methods func tic(_ displayLink: CADisplayLink) { if (self.isReadForAction == true) { self.updateMotion(); self.updateUniforms(); if let drawable = metalLayer.nextDrawable(), let tempVertexBuffer = self.getVertexBuffer(), let tempTransformationBuffer = self.getTransformationBuffer() { let vertexCount = self.getVertexArray()!.count; let renderPassDescriptor = MTLRenderPassDescriptor(); renderPassDescriptor.colorAttachments[0].texture = drawable.texture; renderPassDescriptor.colorAttachments[0].loadAction = .clear renderPassDescriptor.colorAttachments[0].clearColor = MTLClearColor(red: 0.0, green: 104.0/255.0, blue: 5.0/255.0, alpha: 1.0); renderPassDescriptor.colorAttachments[0].storeAction = .store let commandBuffer = OSPointCloudView.commandQueue.makeCommandBuffer(); let renderEncoder = commandBuffer.makeRenderCommandEncoder(descriptor: renderPassDescriptor); renderEncoder.setFrontFacing(MTLWinding.counterClockwise) renderEncoder.setCullMode(MTLCullMode.front); renderEncoder.setRenderPipelineState(OSPointCloudView.pipelineState!); renderEncoder.setDepthStencilState(OSPointCloudView.depthStencilState);//this will prevents the points, that should appear farther away, to be drawn on top of the other points, which are closer to the camera. renderEncoder.setVertexBuffer(tempVertexBuffer, offset: 0, at: 0); renderEncoder.setVertexBuffer(tempTransformationBuffer, offset: 0, at: 2); renderEncoder.setVertexBuffer(self.uniformBuffer, offset: 0, at: 1); renderEncoder.drawPrimitives(type: MTLPrimitiveType.point, vertexStart: 0, vertexCount: vertexCount); renderEncoder.endEncoding(); commandBuffer.present(drawable); commandBuffer.commit() } } } fileprivate func updateMotion() { let frameTime = CFAbsoluteTimeGetCurrent(); let frameDuration = CGFloat(frameTime - self.lastFrameTime); self.lastFrameTime = frameTime; if (frameDuration > 0.0) { self.angle = CGPoint(x: self.angle.x + self.angularVelocity.x * frameDuration, y: self.angle.y + self.angularVelocity.y * frameDuration); self.angularVelocity = CGPoint(x: self.angularVelocity.x * (1 - kOSPointCloudViewDamping), y: self.angularVelocity.y * (1 - kOSPointCloudViewDamping)); } } fileprivate func updateUniforms() { var viewMatrix = Matrix4.Identity; viewMatrix = Matrix4.rotation(axis: kOSPointCloudViewYAxis, angle: Scalar(self.angle.x)) * viewMatrix; viewMatrix = Matrix4.rotation(axis: kOSPointCloudViewXAxis, angle: Scalar(self.angle.y)) * viewMatrix; let near: Float = 0.1; let far: Float = 100.0; let aspect: Float = Float(self.bounds.size.width / self.bounds.size.height); let projectionMatrix = Matrix4.perspectiveProjection(aspect: aspect, fovy: Float.degToRad(95.0), near: near, far: far); var uniforms: Uniforms = Uniforms(); uniforms.viewMatrix = viewMatrix; let modelViewProj: Matrix4 = projectionMatrix uniforms.projectionMatrix = modelViewProj; self.uniforms = uniforms; self.uniformBuffer = OSPointCloudView.device.makeBuffer(bytes: &self.uniforms, length: MemoryLayout<Uniforms>.size, options:MTLResourceOptions.cpuCacheModeWriteCombined); } // MARK: Custom Getter/Setters func getVertexBuffer() -> MTLBuffer? { var vertexBuffer : MTLBuffer?; (self.threadSafeConcurrentVertexBufferAccessQueue).sync { () -> Void in vertexBuffer = self.vertexBuffer; }; return vertexBuffer; } func getTransformationBuffer() -> MTLBuffer? { var transformationBuffer: MTLBuffer?; (self.threadSafeConcurrentTransformationBufferAccessQueue).sync { () -> Void in transformationBuffer = self.transformationBuffer; }; return transformationBuffer; } func setVertexBuffers(vertexBuffer: MTLBuffer, transformationBuffer: MTLBuffer) { self.threadSafeConcurrentVertexBufferAccessQueue.async(flags: .barrier, execute: { () -> Void in self.vertexBuffer = vertexBuffer; self.transformationBuffer = transformationBuffer; }) ; } func getVertexArray() -> [OSPoint]? { var vertexArray: [OSPoint]? self.threadSafeConcurrentVertexAccessQueue.sync { () -> Void in vertexArray = self.vertices; } return vertexArray; } func setVertexArray(_ vertexArray: [OSPoint]) { self.threadSafeConcurrentVertexAccessQueue.async(flags: .barrier, execute: { () -> Void in self.vertices = vertexArray; }) ; } // MARK: Publics func appendFrame(_ frame: OSBaseFrame) { self.transformationMatrices.append(frame.transformationMatrix); let transformationBuffer = OSPointCloudView.device.makeBuffer(bytes: self.transformationMatrices, length: self.transformationMatrices.count * MemoryLayout<Matrix4>.size, options: []); // self.setVertexArray(self.vertices + frame.pointCloud); self.vertices += frame.pointCloud; let vertexBuffer = OSPointCloudView.device.makeBuffer(bytes: self.getVertexArray()!, length: self.getVertexArray()!.count * MemoryLayout<OSPoint>.size, options: []); self.setVertexBuffers(vertexBuffer: vertexBuffer, transformationBuffer: transformationBuffer); self.isReadForAction = true; } // MARK: Gesture Recogniser func gestureRecognizerDidRecognize(_ recogniser : UIPanGestureRecognizer) { let velocity: CGPoint = recogniser.velocity(in: self); self.angularVelocity = CGPoint(x: velocity.x * kOSPointCloudViewVelocityScale, y: velocity.y * kOSPointCloudViewVelocityScale); } // MARK: OSContentLoadingProtocol static func loadContent(_ completionHandler: (() -> Void)!) { DispatchQueue.global(qos: DispatchQoS.QoSClass.userInteractive).async { () -> Void in OSPointCloudView.device; OSPointCloudView.commandQueue; if (OSPointCloudView.pipelineState == nil) { let defaultLibrary = OSPointCloudView.device.newDefaultLibrary(); let vertexFunction = defaultLibrary!.makeFunction(name: "pointCloudVertex"); let fragmentFunction = defaultLibrary!.makeFunction(name: "pointCloudFragment"); let pipelineStateDescriptor = MTLRenderPipelineDescriptor(); pipelineStateDescriptor.vertexFunction = vertexFunction; pipelineStateDescriptor.fragmentFunction = fragmentFunction; pipelineStateDescriptor.colorAttachments[0].pixelFormat = .bgra8Unorm; do{ OSPointCloudView.pipelineState = try OSPointCloudView.device.makeRenderPipelineState(descriptor: pipelineStateDescriptor); } catch _ { OSPointCloudView.pipelineState = nil; print("Failed to create pipeline state."); }; let depthStencilDescriptor: MTLDepthStencilDescriptor = MTLDepthStencilDescriptor(); depthStencilDescriptor.depthCompareFunction = MTLCompareFunction.less; depthStencilDescriptor.isDepthWriteEnabled = true; OSPointCloudView.depthStencilState = OSPointCloudView.device.makeDepthStencilState(descriptor: depthStencilDescriptor); } DispatchQueue.main.sync { () -> Void in completionHandler?(); }; }; } }
mit
edc3577b1363fdce5ca7b856d6e8334a
43.560403
340
0.664207
5.284123
false
false
false
false
dbsystel/DBNetworkStack
Source/NetworkServiceMock.swift
1
7065
// // Copyright (C) 2017 DB Systel GmbH. // DB Systel GmbH; Jürgen-Ponto-Platz 1; D-60329 Frankfurt am Main; Germany; http://www.dbsystel.de/ // // 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 Dispatch struct NetworkServiceMockCallback { let onErrorCallback: (NetworkError) -> Void let onTypedSuccess: (Any, HTTPURLResponse) throws -> Void init<Result>(resource: Resource<Result>, onCompletionWithResponse: @escaping (Result, HTTPURLResponse) -> Void, onError: @escaping (NetworkError) -> Void) { onTypedSuccess = { anyResult, response in guard let typedResult = anyResult as? Result else { throw NetworkServiceMock.Error.typeMismatch } onCompletionWithResponse(typedResult, response) } onErrorCallback = { error in onError(error) } } } /** Mocks a `NetworkService`. You can configure expected results or errors to have a fully functional mock. **Example**: ```swift //Given let networkServiceMock = NetworkServiceMock() let resource: Resource<String> = // //When networkService.request( resource, onCompletion: { string in /*...*/ }, onError: { error in /*...*/ } ) networkService.returnSuccess(with: "Sucess") //Then //Test your expectations ``` It is possible to start multiple requests at a time. All requests and responses (or errors) are processed in order they have been called. So, everything is serial. **Example**: ```swift //Given let networkServiceMock = NetworkServiceMock() let resource: Resource<String> = // //When networkService.request( resource, onCompletion: { string in /* Success */ }, onError: { error in /*...*/ } ) networkService.request( resource, onCompletion: { string in /*...*/ }, onError: { error in /*. cancel error .*/ } ) networkService.returnSuccess(with: "Sucess") networkService.returnError(with: .cancelled) //Then //Test your expectations ``` - seealso: `NetworkService` */ public final class NetworkServiceMock: NetworkService { public enum Error: Swift.Error, CustomDebugStringConvertible { case missingRequest case typeMismatch public var debugDescription: String { switch self { case .missingRequest: return "Could not return because no request" case .typeMismatch: return "Return type does not match requested type" } } } /// Count of all started requests public var requestCount: Int { return lastRequests.count } /// Last executed request public var lastRequest: URLRequest? { return lastRequests.last } public var pendingRequestCount: Int { return callbacks.count } /// All executed requests. public private(set) var lastRequests: [URLRequest] = [] /// Set this to hava a custom networktask returned by the mock public var nextNetworkTask: NetworkTask? private var callbacks: [NetworkServiceMockCallback] = [] /// Creates an instace of `NetworkServiceMock` public init() {} /** Fetches a resource asynchronously from remote location. Execution of the requests starts immediately. Execution happens on no specific queue. It dependes on the network access which queue is used. Once execution is finished either the completion block or the error block gets called. You decide on which queue these blocks get executed. **Example**: ```swift let networkService: NetworkService = // let resource: Resource<String> = // networkService.request(queue: .main, resource: resource, onCompletionWithResponse: { htmlText, response in print(htmlText, response) }, onError: { error in // Handle errors }) ``` - parameter queue: The `DispatchQueue` to execute the completion and error block on. - parameter resource: The resource you want to fetch. - parameter onCompletionWithResponse: Callback which gets called when fetching and transforming into model succeeds. - parameter onError: Callback which gets called when fetching or transforming fails. - returns: a running network task */ @discardableResult public func request<Result>(queue: DispatchQueue, resource: Resource<Result>, onCompletionWithResponse: @escaping (Result, HTTPURLResponse) -> Void, onError: @escaping (NetworkError) -> Void) -> NetworkTask { lastRequests.append(resource.request) callbacks.append(NetworkServiceMockCallback( resource: resource, onCompletionWithResponse: onCompletionWithResponse, onError: onError )) return nextNetworkTask ?? NetworkTaskMock() } /// Will return an error to the current waiting request. /// /// - Parameters: /// - error: the error which gets passed to the caller /// /// - Throws: An error of type `NetworkServiceMock.Error` public func returnError(with error: NetworkError) throws { guard !callbacks.isEmpty else { throw Error.missingRequest } callbacks.removeFirst().onErrorCallback(error) } /// Will return a successful request, by using the given type `T` as serialized result of a request. /// /// - Parameters: /// - data: the mock response from the server. `Data()` by default /// - httpResponse: the mock `HTTPURLResponse` from the server. `HTTPURLResponse()` by default /// /// - Throws: An error of type `NetworkServiceMock.Error` public func returnSuccess<T>(with serializedResponse: T, httpResponse: HTTPURLResponse = HTTPURLResponse()) throws { guard !callbacks.isEmpty else { throw Error.missingRequest } try callbacks.removeFirst().onTypedSuccess(serializedResponse, httpResponse) } }
mit
b82e4542c83759ec7bcb85d3717a2b2d
33.458537
160
0.671574
4.838356
false
false
false
false
randymarsh77/amethyst
servers/meta/Sources/main.swift
1
1242
import Bonjour import Vapor //import Redbird import InMemoryCache import iTunes import HTTP import Using //let config = RedbirdConfig(address: "127.0.0.1", port: 6379) //let redis = try Redbird(config: config) let drop = Droplet() let itunes = iTunes.Instance() let cache = InMemoryCache() _ = PollingWatcher.Watch(itunes.currentTrack.name.data(using: .utf8)) { value in cache.set([ "title" : value ]) } drop.get("/art") { _ in let bytes: Bytes = try itunes.currentTrack.artworks.first!.data.makeBytes() return Response(status: .ok, headers: ["Content-Type": "image/png"], body: .data(bytes)) // return try redis.command("GET", params: ["current"]).toString() } drop.get("/meta") { _ in let title: String = String(data: cache.get(["title"])["title"]!!, encoding: .utf8)! let json = "{ \"title\": \"\(title)\" }".bytes return Response(status: .ok, headers: ["Content-Type": "application/json"], body: .data(json)) // return try redis.command("GET", params: ["current"]).toString() } let port = 8080 let settings = BroadcastSettings( name: "CrystalMeta", serviceType: .Unregistered(identifier: "_crystal-meta"), serviceProtocol: .TCP, domain: .AnyDomain, port: Int32(port)) using (Bonjour.Broadcast(settings)) { drop.run() }
mit
1d71f3d91bce7f15af8c353e56959718
27.883721
95
0.690821
3.209302
false
true
false
false
mvader/subtitler
Subtitler/OpenSubtitles.swift
1
3463
import Foundation import Alamofire import AlamofireXMLRPC private let OpenSubtitlesApi: String = "http://api.opensubtitles.org/xml-rpc" private enum Method: String { case LogIn, SearchSubtitles } public enum OpenSubtitlesError: ErrorType { case NotLoggedIn, Empty case RequestError(_: NSError) case StatusError(_: String) } private struct Status { var code: Int var msg: String var success: Bool { get { return code == 200 } } } class OpenSubtitlesClient: NSObject { private var userAgent: String private var lang: String private var token: String = "" init(userAgent: String, lang: String) { self.userAgent = userAgent self.lang = lang } func login(onComplete: Result<String, OpenSubtitlesError> -> Void) { self.request(.LogIn, ["", "", self.lang, self.userAgent], onComplete: { response in switch response.result { case .Success(let node): let status = self.status(node) if status.success { self.token = node[0]["token"].string! onComplete(Result.Success(self.token)) } else { onComplete(Result.Failure(OpenSubtitlesError.StatusError(status.msg))) } case .Failure(let error): onComplete(Result.Failure(OpenSubtitlesError.RequestError(error))) } }) } func searchSubtitle(hash: String, _ size: UInt64, _ lang: String, onComplete: Result<String, OpenSubtitlesError> -> Void) { if self.token == "" { onComplete(Result.Failure(OpenSubtitlesError.NotLoggedIn)) return } let params = ["moviehash": hash, "moviesize": size] as XMLRPCStructure self.request(.SearchSubtitles, [self.token, [params] as XMLRPCArray], onComplete: { response in switch response.result { case .Success(let node): let status = self.status(node) if status.success { let data = node[0]["data"] if let link = self.findSubtitle(data, lang) { onComplete(Result.Success(link)) return } onComplete(Result.Failure(OpenSubtitlesError.Empty)) } else { onComplete(Result.Failure(OpenSubtitlesError.StatusError(status.msg))) } case .Failure(let error): onComplete(Result.Failure(OpenSubtitlesError.RequestError(error))) } }) } private func findSubtitle(subtitles: XMLRPCNode, _ lang: String) -> String? { for i in 0..<subtitles.count! { let sub = subtitles[i] if sub["ISO639"].string! == lang { return sub["SubDownloadLink"].string! } } return nil } private func status(root: XMLRPCNode) -> Status { let status = root[0]["status"].string! let statusCode = Int(status.componentsSeparatedByString(" ")[0])! return Status(code: statusCode, msg: status) } private func request(method: Method, _ params: [Any], onComplete: Response<XMLRPCNode, NSError> -> Void) { AlamofireXMLRPC.request(OpenSubtitlesApi, methodName:method.rawValue, parameters:params).responseXMLRPC(onComplete) } }
mit
4cf9edce2d4b161e8f48e103adb9a4da
32.631068
127
0.575801
4.667116
false
false
false
false
ocrickard/Theodolite
Theodolite/View/Configuration/ViewAttribute.swift
1
2887
// // ViewAttribute.swift // Theodolite // // Created by Oliver Rickard on 10/11/17. // Copyright © 2017 Oliver Rickard. All rights reserved. // import UIKit /** Generic attribute class. Attrs are the actual objects that you create in your component to pass to a receiver that expects Attributes. */ public class Attr<ViewType: UIView, ValueType: Equatable>: Attribute { public convenience init(_ value: ValueType, applicator: @escaping (ViewType) -> (ValueType) -> ()) { self.init( value, identifier: "\(type(of: applicator))", applicator: applicator) } public convenience init(_ value: ValueType, identifier: String, applicator: @escaping (ViewType) -> (ValueType) -> ()) { self.init() self.identifier = identifier self.value = AttributeValue(value) self.applicator = { (view: UIView) in return {(obj: Any?) in applicator(view as! ViewType)(obj as! ValueType) } } } public convenience init(_ value: ValueType, applicator: @escaping (ViewType, ValueType) -> ()) { self.init( value, identifier: "\(type(of: applicator))", applicator: applicator) } public convenience init(_ value: ValueType, identifier: String, applicator: @escaping (ViewType, ValueType) -> ()) { self.init() self.identifier = identifier self.value = AttributeValue(value) self.applicator = { (view: UIView) in return {(obj: Any?) in applicator(view as! ViewType, obj as! ValueType) } } } } /** Base class for all view attributes. Generally receivers should declare receiving this type. */ public class Attribute: Equatable, Hashable { internal var identifier: String internal var value: AttributeValue? internal var applicator: ((UIView) -> (Any?) -> ())? public func hash(into hasher: inout Hasher) { hasher.combine(self.identifier) } public init() { self.identifier = "" self.value = nil self.applicator = nil } func apply(view: UIView) { if let applicator = self.applicator { applicator(view)(self.value?.value) } } func unapply(view: UIView) { /** Do nothing, for subclasses. */} } public func ==(lhs: Attribute, rhs: Attribute) -> Bool { return lhs.identifier == rhs.identifier && lhs.value == rhs.value } /** Implementation detail, generic container for an equatable value. */ public class AttributeValue: Equatable { internal let value: Any internal let equals: (Any) -> Bool // TODO: Is this efficient? public init<E: Equatable>(_ value: E) { self.value = value self.equals = { $0 as? E == value } } } public func ==(lhs: AttributeValue, rhs: AttributeValue) -> Bool { return lhs.equals(rhs.value) }
mit
86ca781c765b96c28467344402960dee
27.019417
115
0.619196
4.188679
false
false
false
false
nathawes/swift
test/Constraints/diag_ambiguities.swift
12
2313
// RUN: %target-typecheck-verify-swift func f0(_ i: Int, _ d: Double) {} // expected-note{{found this candidate}} func f0(_ d: Double, _ i: Int) {} // expected-note{{found this candidate}} f0(1, 2) // expected-error{{ambiguous use of 'f0'}} func f1(_ i: Int16) {} // expected-note{{found this candidate}} func f1(_ i: Int32) {} // expected-note{{found this candidate}} f1(0) // expected-error{{ambiguous use of 'f1'}} infix operator +++ func +++(i: Int, d: Double) {} // expected-note{{found this candidate}} func +++(d: Double, i: Int) {} // expected-note{{found this candidate}} 1 +++ 2 // expected-error{{ambiguous use of operator '+++'}} class C { init(_ action: (Int) -> ()) {} init(_ action: (Int, Int) -> ()) {} } func g(_ x: Int) -> () {} // expected-note{{found this candidate}} func g(_ x: Int, _ y: Int) -> () {} // expected-note{{found this candidate}} C(g) // expected-error{{ambiguous use of 'g'}} func h<T>(_ x: T) -> () {} _ = C(h) // OK - init(_: (Int) -> ()) func rdar29691909_callee(_ o: AnyObject?) -> Any? { return o } // expected-note {{found this candidate}} func rdar29691909_callee(_ o: AnyObject) -> Any { return o } // expected-note {{found this candidate}} func rdar29691909(o: AnyObject) -> Any? { return rdar29691909_callee(o) // expected-error{{ambiguous use of 'rdar29691909_callee'}} } func rdar29907555(_ value: Any!) -> String { return "\(value)" // expected-warning {{string interpolation produces a debug description for an optional value; did you mean to make this explicit?}} // expected-note@-1 {{use 'String(describing:)' to silence this warning}} // expected-note@-2 {{provide a default value to avoid this warning}} } struct SR3715 { var overloaded: Int! func overloaded(_ x: Int) {} func overloaded(_ x: Float) {} func take(_ a: [Any]) {} func test() { take([overloaded]) } } // rdar://35116378 - Here the ambiguity is in the pre-check pass; make sure // we emit a diagnostic instead of crashing. struct Movie {} class MoviesViewController { typealias itemType = Movie // expected-note {{'itemType' declared here}} let itemType = [Movie].self // expected-note {{'itemType' declared here}} var items: [Movie] = [Movie]() func loadData() { _ = itemType // expected-error {{ambiguous use of 'itemType'}} } }
apache-2.0
9e9bd63fb734ff8c3e347e682a531c57
32.042857
152
0.637268
3.421598
false
false
false
false
FuckBoilerplate/RxCache
watchOS/Pods/RxSwift/RxSwift/Observables/Implementations/Generate.swift
6
2318
// // Generate.swift // Rx // // Created by Krunoslav Zaher on 9/2/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // import Foundation class GenerateSink<S, O: ObserverType> : Sink<O> { typealias Parent = Generate<S, O.E> private let _parent: Parent private var _state: S init(parent: Parent, observer: O, cancel: Cancelable) { _parent = parent _state = parent._initialState super.init(observer: observer, cancel: cancel) } func run() -> Disposable { return _parent._scheduler.scheduleRecursive(true) { (isFirst, recurse) -> Void in do { if !isFirst { self._state = try self._parent._iterate(self._state) } if try self._parent._condition(self._state) { let result = try self._parent._resultSelector(self._state) self.forwardOn(.next(result)) recurse(false) } else { self.forwardOn(.completed) self.dispose() } } catch let error { self.forwardOn(.error(error)) self.dispose() } } } } class Generate<S, E> : Producer<E> { fileprivate let _initialState: S fileprivate let _condition: (S) throws -> Bool fileprivate let _iterate: (S) throws -> S fileprivate let _resultSelector: (S) throws -> E fileprivate let _scheduler: ImmediateSchedulerType init(initialState: S, condition: @escaping (S) throws -> Bool, iterate: @escaping (S) throws -> S, resultSelector: @escaping (S) throws -> E, scheduler: ImmediateSchedulerType) { _initialState = initialState _condition = condition _iterate = iterate _resultSelector = resultSelector _scheduler = scheduler super.init() } override func run<O : ObserverType>(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == E { let sink = GenerateSink(parent: self, observer: observer, cancel: cancel) let subscription = sink.run() return (sink: sink, subscription: subscription) } }
mit
15d9e4153b7dd5fecb56b976ccefae1b
31.633803
182
0.557186
4.661972
false
false
false
false
legendecas/Rocket.Chat.iOS
Rocket.Chat.Shared/Managers/MessageTextCacheManager.swift
1
2373
// // MessageTextCacheManager.swift // Rocket.Chat // // Created by Rafael Kellermann Streit on 02/05/17. // Copyright © 2017 Rocket.Chat. All rights reserved. // import UIKit /// A manager that manages all message text rendering cache public class MessageTextCacheManager { let cache = NSCache<NSString, NSAttributedString>() internal func cachedKey(for identifier: String) -> NSString { return NSString(string: "\(identifier)-cachedattrstring") } func clear() { cache.removeAllObjects() } func remove(for message: Message) { guard let identifier = message.identifier else { return } cache.removeObject(forKey: cachedKey(for: identifier)) } @discardableResult func update(for message: Message, style: MessageContainerStyle = .normal) -> NSMutableAttributedString? { guard let identifier = message.identifier else { return nil } let resultText: NSMutableAttributedString let key = cachedKey(for: identifier) let text = NSMutableAttributedString(string: message.textNormalized()) if message.isSystemMessage() { text.setFont(MessageTextFontAttributes.font(for: style, fontStyle: .italic)) text.setFontColor(MessageTextFontAttributes.systemFontColor) } else { text.setFont(MessageTextFontAttributes.font(for: style)) text.setFontColor(MessageTextFontAttributes.fontColor(for: style)) } resultText = NSMutableAttributedString(attributedString: text.transformMarkdown()) resultText.trimCharacters(in: .whitespaces) cache.setObject(resultText, forKey: key) return resultText } func message(for message: Message, style: MessageContainerStyle = .normal) -> NSMutableAttributedString? { guard let identifier = message.identifier else { return nil } let resultText: NSAttributedString let key = cachedKey(for: identifier) if let cachedVersion = cache.object(forKey: key) { resultText = cachedVersion } else { if let result = update(for: message, style: style) { resultText = result } else { resultText = NSAttributedString(string: message.text) } } return NSMutableAttributedString(attributedString: resultText) } }
mit
3dd2152d837df91d12f4749f91079953
33.882353
128
0.671164
5.036093
false
false
false
false
DDSSwiftTech/SwiftGtk
Sources/Application.swift
2
1310
// // Copyright © 2015 Tomas Linhart. All rights reserved. // import CGtk public class Application { let applicationPointer: UnsafeMutablePointer<GtkApplication> private(set) var applicationWindow: ApplicationWindow? private var windowCallback: ((ApplicationWindow) -> Void)? public init(applicationId: String) { applicationPointer = gtk_application_new(applicationId, G_APPLICATION_FLAGS_NONE) } @discardableResult public func run(_ windowCallback: @escaping (ApplicationWindow) -> Void) -> Int { self.windowCallback = windowCallback let handler: @convention(c) (UnsafeMutableRawPointer, UnsafeMutableRawPointer) -> Void = { sender, data in let app = unsafeBitCast(data, to: Application.self) app.activate() } connectSignal(applicationPointer, name: "activate", data: Unmanaged.passUnretained(self).toOpaque(), handler: unsafeBitCast(handler, to: GCallback.self)) let status = g_application_run(applicationPointer.cast(), 0, nil) g_object_unref(applicationPointer) return Int(status) } private func activate() { let window = ApplicationWindow(application: self) windowCallback?(window) window.showAll() self.applicationWindow = window } }
mit
11ecf36657ee7a20526b9ec694c13068
33.447368
161
0.687548
4.658363
false
false
false
false
Frgallah/MasterTransitions
Example/MasterTransitions/NavigationFirstViewController.swift
1
2027
// // NavigationFirstViewController.swift // MasterTransitions // // Created by Frgallah on 4/11/17. // // Copyright (c) 2017 Mohammed Frgallah. All rights reserved. // // Licensed under the MIT license, can be found at: https://github.com/Frgallah/MasterTransitions/blob/master/LICENSE or https://opensource.org/licenses/MIT // // For last updated version of this code check the github page at https://github.com/Frgallah/MasterTransitions // // import UIKit import MasterTransitions class NavigationFirstViewController: UIViewController { var transitionType: TransitionType = .Push2 override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. self.navigationController?.isNavigationBarHidden = true guard let navigationController = self.navigationController else { return } let navigationControllerDelegate = NavigationControllerDelegate.init(navigationController: navigationController, transitionType: transitionType, isInteractive: true) navigationControllerDelegate.duration = 0.6 navigationControllerDelegate.transitionSubType = .RightToLeft navigationControllerDelegate.transitionBackgroundColor = .black } @IBAction func back(_ sender: Any) { self.navigationController?.delegate = nil let _ = self.navigationController?.popViewController(animated: true) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
mit
5db5b1ec03868fff0b717879eb8e225f
31.693548
173
0.698076
5.197436
false
false
false
false
keyOfVv/Cusp
Cusp/Sources/Subscribe.swift
1
5285
// // Subscribe.swift // CuspExample // // Created by keyOfVv on 2/17/16. // Copyright © 2016 com.keyang. All rights reserved. // import Foundation // MARK: SubscribeRequest /// request of subscribe value update of specific characteristic class SubscribeRequest: PeripheralOperationRequest { // MARK: Stored Properties /// a CBCharacteristic object of which the value update to be subscribed var characteristic: Characteristic! /// a closure called when characteristic's value updated var update: ((Data?) -> Void)? // MARK: Initializer fileprivate override init() { super.init() } /** Convenient initializer - parameter characteristic: a CBCharacteristic object of which the value update to be subscribed - parameter peripheral: a CBPeripheral object to which the characteristic belongs - parameter success: a closure called when subscription succeed - parameter failure: a closure called when subscription failed - parameter update: a closure called when characteristic's value updated, after successfully subscribed, the update closure will be wrapped in Subscription object - returns: a SubscribeRequest instance */ convenience init(characteristic: Characteristic, success: ((Response?) -> Void)?, failure: ((CuspError?) -> Void)?, update: ((Data?) -> Void)?) { self.init() self.characteristic = characteristic self.success = success self.failure = failure self.update = update } override var hash: Int { return characteristic.uuid.uuidString.hashValue } override func isEqual(_ object: Any?) -> Bool { if let other = object as? SubscribeRequest { return self.hashValue == other.hashValue } return false } } // MARK: Communicate extension Peripheral { /** Subscribe value update of specific characteristic on specific peripheral - parameter characteristic: a CBCharacteristic object of which the value update to be subscribed. - parameter success: a closure called when subscription succeed. - parameter failure: a closure called when subscription failed. - parameter update: a closure called when characteristic's value updated, after successfully subscribed, the update closure will be wrapped in Subscription object. */ func subscribe(_ characteristic: Characteristic, success: ((Response?) -> Void)?, failure: ((CuspError?) -> Void)?, update: ((Data?) -> Void)?) { // 0. check if ble is available if let error = CuspCentral.default.assertAvailability() { failure?(error) return } // 1. create req object let req = SubscribeRequest(characteristic: characteristic, success: success, failure: failure, update: update) // 2. add req self.requestQ.async(execute: { () -> Void in self.subscribeRequests.insert(req) }) // 3. subscribe characteristic self.operationQ.async(execute: { () -> Void in self.core.setNotifyValue(true, for: characteristic) }) // 4. set time out closure self.operationQ.asyncAfter(deadline: DispatchTime.now() + Double(req.timeoutPeriod)) { () -> Void in if req.timedOut { DispatchQueue.main.async(execute: { () -> Void in failure?(CuspError.timedOut) }) // since req timed out, don't need it any more self.requestQ.async(execute: { () -> Void in self.subscribeRequests.remove(req) }) } } } public func subscribe(characteristic c: String, ofService s: String, success: ((Response?) -> Void)?, failure: ((CuspError?) -> Void)?, update: ((Data?) -> Void)?) { guard s.isValidUUID else { failure?(.invalidServiceUUID); return } guard c.isValidUUID else { failure?(.invalidCharacteristicUUID); return } discoverServices(UUIDStrings: [s], success: { (_) in guard let service = self[s] else { fatalError("Service not found after successfully discovering") } self.discoverCharacteristics(UUIDStrings: [c], ofService: service, success: { (_) in guard let char = service[c] else { fatalError("Characteristic not found after successfully discovering") } self.subscribe(char, success: success, failure: failure, update: update) }, failure: { failure?($0) }) }) { failure?($0) } // if let service = self[s] { // if let char = service[c] { // subscribe(char, success: success, failure: failure, update: update) // } else { // discoverCharacteristics(UUIDStrings: [c], ofService: service, success: { (resp) in // if let char = service[c] { // self.subscribe(char, success: success, failure: failure, update: update) // } else { // failure?(CuspError.characteristicNotFound) // } // }, failure: { (error) in // failure?(error) // }) // } // } else { // discoverServices(UUIDStrings: [s], success: { (resp) in // if let service = self[s] { // self.discoverCharacteristics(UUIDStrings: [c], ofService: service, success: { (resp) in // if let char = service[c] { // self.subscribe(char, success: success, failure: failure, update: update) // } else { // failure?(CuspError.characteristicNotFound) // } // }, failure: { (error) in // failure?(error) // }) // } else { // failure?(CuspError.serviceNotFound) // } // }, failure: { (error) in // failure?(error) // }) // } } }
mit
c5859f32362928d432afb1b1e4fd682c
31.417178
172
0.674868
3.782391
false
false
false
false
biohazardlover/ROer
Roer/ItemsDataSource.swift
1
843
import Foundation class ItemsDataSource: NSObject, DatabaseRecordsViewControllerDataSource { func entityName() -> String { return "Item" } func title() -> String { return "Items".localized } func filter() -> Filter { return Filter(contentsOfURL: Bundle.main.url(forResource: "ItemsFilter", withExtension: "plist")!) } func includeDatabaseRecord(_ databaseRecord: DatabaseRecord, forSearchText searchText: String) -> Bool { let item = databaseRecord as! Item if item.id?.stringValue == searchText || item.localizedName?.localizedCaseInsensitiveContains(searchText) == true { return true } else { return false } } func titleForEmptyDataSet() -> String { return "NoItems".localized } }
mit
fe0820ec2ff11493731e646dcef56293
26.193548
123
0.62159
5.236025
false
false
false
false
sman591/pegg
Pods/SwiftKeychainWrapper/SwiftKeychainWrapper/KeychainWrapper.swift
1
6673
// // KeychainWrapper.swift // KeychainWrapper // // Created by Jason Rendel on 9/23/14. // Copyright (c) 2014 jasonrendel. All rights reserved. // import Foundation let SecMatchLimit: String! = kSecMatchLimit as String let SecReturnData: String! = kSecReturnData as String let SecValueData: String! = kSecValueData as String let SecAttrAccessible: String! = kSecAttrAccessible as String let SecClass: String! = kSecClass as String let SecAttrService: String! = kSecAttrService as String let SecAttrGeneric: String! = kSecAttrGeneric as String let SecAttrAccount: String! = kSecAttrAccount as String public class KeychainWrapper { private struct internalVars { static var serviceName: String = "" } // MARK: Public Properties /*! @var serviceName @abstract Used for the kSecAttrService property to uniquely identify this keychain accessor. @discussion Service Name will default to the app's bundle identifier if it can */ public class var serviceName: String { get { if internalVars.serviceName.isEmpty { internalVars.serviceName = NSBundle.mainBundle().bundleIdentifier ?? "SwiftKeychainWrapper" } return internalVars.serviceName } set(newServiceName) { internalVars.serviceName = newServiceName } } // MARK: Public Methods public class func hasValueForKey(key: String) -> Bool { var keychainData: NSData? = self.dataForKey(key) if let data = keychainData { return true } else { return false } } // MARK: Getting Values public class func stringForKey(keyName: String) -> String? { var keychainData: NSData? = self.dataForKey(keyName) var stringValue: String? if let data = keychainData { stringValue = NSString(data: data, encoding: NSUTF8StringEncoding) as String? } return stringValue } public class func objectForKey(keyName: String) -> NSCoding? { let dataValue: NSData? = self.dataForKey(keyName) var objectValue: NSCoding? if let data = dataValue { objectValue = NSKeyedUnarchiver.unarchiveObjectWithData(data) as NSCoding? } return objectValue; } public class func dataForKey(keyName: String) -> NSData? { var keychainQueryDictionary = self.setupKeychainQueryDictionaryForKey(keyName) // Limit search results to one keychainQueryDictionary[SecMatchLimit] = kSecMatchLimitOne // Specify we want NSData/CFData returned keychainQueryDictionary[SecReturnData] = kCFBooleanTrue // Search // var searchResultRef: Unmanaged<AnyObject>? // var keychainValue: NSData? // // let status: OSStatus = SecItemCopyMatching(keychainQueryDictionary, &searchResultRef) // // if status == noErr { // if let resultRef = searchResultRef { // keychainValue = resultRef.takeUnretainedValue() as? NSData // resultRef.autorelease() // } // } // // return keychainValue; // use the objective c wrapper for now as a work around to a known issue where data retrievale fails // for Swift optimized builds. // http://stackoverflow.com/questions/26355630/swift-keychain-and-provisioning-profiles return KeychainObjcWrapper.dataForDictionary(keychainQueryDictionary) } // MARK: Setting Values public class func setString(value: String, forKey keyName: String) -> Bool { if let data = value.dataUsingEncoding(NSUTF8StringEncoding) { return self.setData(data, forKey: keyName) } else { return false } } public class func setObject(value: NSCoding, forKey keyName: String) -> Bool { let data = NSKeyedArchiver.archivedDataWithRootObject(value) return self.setData(data, forKey: keyName) } public class func setData(value: NSData, forKey keyName: String) -> Bool { var keychainQueryDictionary: NSMutableDictionary = self.setupKeychainQueryDictionaryForKey(keyName) keychainQueryDictionary[SecValueData] = value // Protect the keychain entry so it's only valid when the device is unlocked keychainQueryDictionary[SecAttrAccessible] = kSecAttrAccessibleWhenUnlocked let status: OSStatus = SecItemAdd(keychainQueryDictionary, nil) if status == errSecSuccess { return true } else if status == errSecDuplicateItem { return self.updateData(value, forKey: keyName) } else { return false } } // MARK: Removing Values public class func removeObjectForKey(keyName: String) -> Bool { let keychainQueryDictionary: NSMutableDictionary = self.setupKeychainQueryDictionaryForKey(keyName) // Delete let status: OSStatus = SecItemDelete(keychainQueryDictionary); if status == errSecSuccess { return true } else { return false } } // MARK: Private Methods private class func updateData(value: NSData, forKey keyName: String) -> Bool { let keychainQueryDictionary: NSMutableDictionary = self.setupKeychainQueryDictionaryForKey(keyName) let updateDictionary = [SecValueData:value] // Update let status: OSStatus = SecItemUpdate(keychainQueryDictionary, updateDictionary) if status == errSecSuccess { return true } else { return false } } private class func setupKeychainQueryDictionaryForKey(keyName: String) -> NSMutableDictionary { // Setup dictionary to access keychain and specify we are using a generic password (rather than a certificate, internet password, etc) var keychainQueryDictionary: NSMutableDictionary = [SecClass:kSecClassGenericPassword] // Uniquely identify this keychain accessor keychainQueryDictionary[SecAttrService] = KeychainWrapper.serviceName // Uniquely identify the account who will be accessing the keychain var encodedIdentifier: NSData? = keyName.dataUsingEncoding(NSUTF8StringEncoding) keychainQueryDictionary[SecAttrGeneric] = encodedIdentifier keychainQueryDictionary[SecAttrAccount] = encodedIdentifier return keychainQueryDictionary } }
mit
e590bd99fd4d65026c2a4d74f24e974d
35.07027
142
0.649783
5.469672
false
false
false
false
NSSimpleApps/WatchConnector
WatchConnector/WatchConnector WatchKit App Extension/ExtensionDelegate.swift
1
1750
// // ExtensionDelegate.swift // WatchConnectorWatch Extension // // Created by NSSimpleApps on 07.03.16. // Copyright © 2016 NSSimpleApps. All rights reserved. // import WatchKit class ExtensionDelegate: NSObject, WKExtensionDelegate { func applicationDidFinishLaunching() { let connector = WatchConnector.shared connector.addObserver(self, selector: #selector(self.handleConnectorNotification(_:)), name: .WCApplicationContextDidChange) connector.addObserver(self, selector: #selector(self.handleConnectorNotification(_:)), name: .WCDidReceiveUserInfo) connector.addObserver(self, selector: #selector(self.handleConnectorNotification(_:)), name: .WCSessionReachabilityDidChange) connector.addObserver(self, selector: #selector(self.handleConnectorNotification(_:)), name: .WCDidReceiveFile) connector.addObserver(self, selector: #selector(self.handleConnectorNotification(_:)), name: .WCDidFinishFileTransfer) connector.addObserver(self, selector: #selector(self.handleConnectorNotification(_:)), name: .WCSessionActivationDidComplete) WatchConnector.shared.activateSession() } @objc func handleConnectorNotification(_ notification: Notification) { print(notification) print("============================================================") } }
mit
f01f2f919bf316d2fa8c49226bb317a9
38.75
88
0.5506
6.336957
false
false
false
false
weikz/Mr-Ride-iOS
Mr-Ride-iOS/MapViewController.swift
1
8001
// // MapViewController.swift // Mr-Ride-iOS // // Created by 張瑋康 on 2016/6/14. // Copyright © 2016年 Appworks School Weikz. All rights reserved. // import UIKit import GoogleMaps class MapViewController: UIViewController, UIPickerViewDataSource { var toilets: [ToiletModel] = [] var bikes: [BikeModel] = [] // Picker View Property enum PickerViewStatus { case Toilets, Youbikes } var pickerViewStatus: PickerViewStatus = .Toilets @IBOutlet weak var pickerViewBackground: UIView! @IBOutlet weak var pickerViewButton: UIButton! @IBOutlet weak var sideMenuButton: UIBarButtonItem! // Info View Property @IBOutlet weak var infoView: UIView! @IBOutlet weak var districtLabel: UILabel! @IBOutlet weak var stationLabel: UILabel! @IBOutlet weak var locationLabel: UILabel! @IBOutlet weak var estimatedTimeLabel: UILabel! var pickerView = UIPickerView() var pickerViewDataSource = ["Toilet", "YouBike"] // Map View Property @IBOutlet weak var mapView: GMSMapView! var locationManager = CLLocationManager() @IBAction func pickerViewButton(sender: UIButton) { pickerViewStatus = .Toilets pickerViewBackground.hidden = false } @IBAction func pickerViewDoneButton(sender: AnyObject) { pickerViewStatus = .Youbikes pickerViewBackground.hidden = true } } // MARK: - View Life Cycle extension MapViewController { override func viewDidLoad() { super.viewDidLoad() setupMap() setupPickerView() setupSideMenu() getToilets() setupToiletMarker() } } // MARK : - Setup extension MapViewController { func setupMap(){ locationManager.delegate = self locationManager.requestWhenInUseAuthorization() mapView.delegate = self pickerView.delegate = self infoView.hidden = true pickerViewStatus = .Toilets locationManager.startUpdatingLocation() } func setupPickerView() { self.pickerView.dataSource = self self.pickerView.delegate = self self.pickerView.backgroundColor = UIColor.whiteColor() self.pickerView.frame = CGRectMake(0, 44, 375, 217) pickerViewBackground.addSubview(pickerView) pickerViewBackground.hidden = true } func setupSideMenu() { if self.revealViewController() != nil { sideMenuButton.target = self.revealViewController() sideMenuButton.action = "revealToggle:" self.view.addGestureRecognizer(self.revealViewController().panGestureRecognizer()) } } } // MARK: - Action extension MapViewController { func getToilets() { let manager = DataTaipeiManager() manager.getToilet({ [weak self] toilets in guard let weakSelf = self else { return } weakSelf.toilets = toilets weakSelf.setupToiletMarker() }, failure: {error in print(error)}) } func setupToiletMarker() { mapView.clear() var toiletIndex = 0 for toilet in toilets { let position = toilet.coordinate let marker = GMSMarker(position: position) marker.iconView = setupMarkerBackground("icon-toilet") marker.title = "\(toilet.name)" marker.map = mapView marker.userData = toiletIndex toiletIndex += 1 } } func getBikes() { let manager = DataTaipeiManager() manager.getBike({ [weak self] bikes in guard let weakSelf = self else { return } weakSelf.bikes = bikes weakSelf.setupBikeMarker() }, failure: { error in print(error)}) } func setupBikeMarker() { mapView.clear() var bikeIndex = 0 for bike in bikes { let position = bike.coordinate let marker = GMSMarker(position: position) marker.iconView = setupMarkerBackground("icon-station") marker.title = "\(bike.name)" marker.map = mapView marker.userData = bikeIndex bikeIndex += 1 } } func setupMarkerBackground(icon: String) -> UIView { let iconImage = UIImage(named: icon) let tintedImage = iconImage?.imageWithRenderingMode(UIImageRenderingMode.AlwaysTemplate) let iconImageView = UIImageView(image: tintedImage!) iconImageView.tintColor = .MRDarkSlateBlueColor() let markerBackground = UIView() markerBackground.backgroundColor = .whiteColor() markerBackground.frame = CGRect(x: 0, y: 0, width: 35, height: 35) markerBackground.layer.cornerRadius = markerBackground.frame.width / 2 markerBackground.clipsToBounds = true markerBackground.addSubview(iconImageView) iconImageView.center = markerBackground.center return markerBackground } } // MARK: - Map View Delegate extension MapViewController: GMSMapViewDelegate { func mapView(mapView: GMSMapView, didTapMarker marker: GMSMarker) -> Bool { infoView.hidden = false pickerViewBackground.hidden = true switch pickerViewStatus { case .Youbikes: guard let youbike = marker.userData as? Int else { return false } districtLabel.hidden = false districtLabel.text = bikes[youbike].district districtLabel.layer.borderColor = UIColor.whiteColor().CGColor districtLabel.layer.borderWidth = 0.7 locationLabel.hidden = false stationLabel.text = bikes[youbike].name locationLabel.text = bikes[youbike].location estimatedTimeLabel.text = "5 mins" marker.userData = youbike case .Toilets: guard let toilet = marker.userData as? Int else { return false } districtLabel.hidden = true stationLabel.text = toilets[toilet].name locationLabel.hidden = true estimatedTimeLabel.text = "5 mins" } return false } func mapView(mapView: GMSMapView, didTapAtCoordinate coordinate: CLLocationCoordinate2D) { infoView.hidden = true pickerViewBackground.hidden = true } } // MARK: - UIPickerViewDelegate extension MapViewController: UIPickerViewDelegate { func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int { return 1 } func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { return pickerViewDataSource.count } func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String { return pickerViewDataSource[row] } func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) { switch row { case 0: setupToiletMarker() case 1: getBikes() setupBikeMarker() default: break } } } // MARK: - CLLocationManager extension MapViewController: CLLocationManagerDelegate { func locationManager(manager: CLLocationManager, didChangeAuthorizationStatus status: CLAuthorizationStatus) { if status == .AuthorizedWhenInUse { locationManager.startUpdatingLocation() mapView.myLocationEnabled = true mapView.settings.myLocationButton = true } } func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { if let location = locations.first { mapView.camera = GMSCameraPosition(target: location.coordinate, zoom: 15, bearing: 0, viewingAngle: 0) } } }
mit
2516717f91a5a9644c42b8b7f5c9e8c4
29.276515
114
0.625501
5.257895
false
false
false
false
tranhieutt/Swiftz
Swiftz/JSON.swift
1
10002
// // JSON.swift // Swiftz // // Created by Maxwell Swadling on 5/06/2014. // Copyright (c) 2014 Maxwell Swadling. All rights reserved. // import Foundation public enum JSONValue : CustomStringConvertible { case JSONArray([JSONValue]) case JSONObject(Dictionary<String, JSONValue>) case JSONNumber(Double) case JSONString(String) case JSONBool(Bool) case JSONNull() private func values() -> NSObject { switch self { case let .JSONArray(xs): return NSArray(array: xs.map { $0.values() }) case let .JSONObject(xs): return Dictionary.fromList(xs.map({ k, v in return (NSString(string: k), v.values()) })) case let .JSONNumber(n): return NSNumber(double: n) case let .JSONString(s): return NSString(string: s) case let .JSONBool(b): return NSNumber(bool: b) case .JSONNull(): return NSNull() } } // we know this is safe because of the NSJSONSerialization docs private static func make(a : NSObject) -> JSONValue { switch a { case let xs as NSArray: return .JSONArray((xs as [AnyObject]).map { self.make($0 as! NSObject) }) case let xs as NSDictionary: return JSONValue.JSONObject(Dictionary.fromList((xs as [NSObject: AnyObject]).map({ (k: NSObject, v: AnyObject) in return (String(k as! NSString), self.make(v as! NSObject)) }))) case let xs as NSNumber: // TODO: number or bool?... return .JSONNumber(Double(xs.doubleValue)) case let xs as NSString: return .JSONString(String(xs)) case _ as NSNull: return .JSONNull() default: return error("Non-exhaustive pattern match performed."); } } public func encode() -> NSData? { do { // TODO: check s is a dict or array return try NSJSONSerialization.dataWithJSONObject(self.values(), options: NSJSONWritingOptions(rawValue: 0)) } catch _ { return nil } } // TODO: should this be optional? public static func decode(s : NSData) -> JSONValue? { let r : AnyObject? do { r = try NSJSONSerialization.JSONObjectWithData(s, options: NSJSONReadingOptions(rawValue: 0)) } catch _ { r = nil } if let json: AnyObject = r { return make(json as! NSObject) } else { return .None } } public static func decode(s : String) -> JSONValue? { return JSONValue.decode(s.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!) } public var description : String { get { switch self { case .JSONNull(): return "JSONNull()" case let .JSONBool(b): return "JSONBool(\(b))" case let .JSONString(s): return "JSONString(\(s))" case let .JSONNumber(n): return "JSONNumber(\(n))" case let .JSONObject(o): return "JSONObject(\(o))" case let .JSONArray(a): return "JSONArray(\(a))" } } } } // you'll have more fun if you match tuples // Equatable public func ==(lhs : JSONValue, rhs : JSONValue) -> Bool { switch (lhs, rhs) { case (.JSONNull(), .JSONNull()): return true case let (.JSONBool(l), .JSONBool(r)) where l == r: return true case let (.JSONString(l), .JSONString(r)) where l == r: return true case let (.JSONNumber(l), .JSONNumber(r)) where l == r: return true case let (.JSONObject(l), .JSONObject(r)) where l.elementsEqual(r, isEquivalent: { (v1: (String, JSONValue), v2: (String, JSONValue)) in v1.0 == v2.0 && v1.1 == v2.1 }): return true case let (.JSONArray(l), .JSONArray(r)) where l.elementsEqual(r, isEquivalent: { $0 == $1 }): return true default: return false } } public func !=(lhs : JSONValue, rhs : JSONValue) -> Bool { return !(lhs == rhs) } // someday someone will ask for this //// Comparable //func <=(lhs: JSValue, rhs: JSValue) -> Bool { // return false; //} // //func >(lhs: JSValue, rhs: JSValue) -> Bool { // return !(lhs <= rhs) //} // //func >=(lhs: JSValue, rhs: JSValue) -> Bool { // return (lhs > rhs || lhs == rhs) //} // //func <(lhs: JSValue, rhs: JSValue) -> Bool { // return !(lhs >= rhs) //} public func <? <A : JSONDecodable where A == A.J>(lhs : JSONValue, rhs : JSONKeypath) -> A? { switch lhs { case let .JSONObject(d): return resolveKeypath(d, rhs: rhs).flatMap(A.fromJSON) default: return .None } } public func <? <A : JSONDecodable where A == A.J>(lhs : JSONValue, rhs : JSONKeypath) -> [A]? { switch lhs { case let .JSONObject(d): return resolveKeypath(d, rhs: rhs).flatMap(JArrayFrom<A, A>.fromJSON) default: return .None } } public func <? <A : JSONDecodable where A == A.J>(lhs : JSONValue, rhs : JSONKeypath) -> [String:A]? { switch lhs { case let .JSONObject(d): return resolveKeypath(d, rhs: rhs).flatMap(JDictionaryFrom<A, A>.fromJSON) default: return .None } } public func <! <A : JSONDecodable where A == A.J>(lhs : JSONValue, rhs : JSONKeypath) -> A { if let r : A = (lhs <? rhs) { return r } return error("Cannot find value at keypath \(rhs) in JSON object \(rhs).") } public func <! <A : JSONDecodable where A == A.J>(lhs : JSONValue, rhs : JSONKeypath) -> [A] { if let r : [A] = (lhs <? rhs) { return r } return error("Cannot find array at keypath \(rhs) in JSON object \(rhs).") } public func <! <A : JSONDecodable where A == A.J>(lhs : JSONValue, rhs : JSONKeypath) -> [String:A] { if let r : [String:A] = (lhs <? rhs) { return r } return error("Cannot find object at keypath \(rhs) in JSON object \(rhs).") } // traits public protocol JSONDecodable { typealias J = Self static func fromJSON(x : JSONValue) -> J? } public protocol JSONEncodable { typealias J static func toJSON(x : J) -> JSONValue } // J mate public protocol JSON : JSONDecodable, JSONEncodable { } // instances extension Bool : JSON { public static func fromJSON(x : JSONValue) -> Bool? { switch x { case let .JSONBool(n): return n case .JSONNumber(0): return false case .JSONNumber(1): return true default: return Optional.None } } public static func toJSON(xs : Bool) -> JSONValue { return JSONValue.JSONNumber(Double(xs)) } } extension Int : JSON { public static func fromJSON(x : JSONValue) -> Int? { switch x { case let .JSONNumber(n): return Int(n) default: return Optional.None } } public static func toJSON(xs : Int) -> JSONValue { return JSONValue.JSONNumber(Double(xs)) } } extension Double : JSON { public static func fromJSON(x : JSONValue) -> Double? { switch x { case let .JSONNumber(n): return n default: return Optional.None } } public static func toJSON(xs : Double) -> JSONValue { return JSONValue.JSONNumber(xs) } } extension NSNumber : JSON { public class func fromJSON(x : JSONValue) -> NSNumber? { switch x { case let .JSONNumber(n): return NSNumber(double: n) default: return Optional.None } } public class func toJSON(xs : NSNumber) -> JSONValue { return JSONValue.JSONNumber(Double(xs)) } } extension String : JSON { public static func fromJSON(x : JSONValue) -> String? { switch x { case let .JSONString(n): return n default: return Optional.None } } public static func toJSON(xs : String) -> JSONValue { return JSONValue.JSONString(xs) } } // or unit... extension NSNull : JSON { public class func fromJSON(x : JSONValue) -> NSNull? { switch x { case .JSONNull(): return NSNull() default: return Optional.None } } public class func toJSON(xs : NSNull) -> JSONValue { return JSONValue.JSONNull() } } // container types should be split public struct JArrayFrom<A, B : JSONDecodable where B.J == A> : JSONDecodable { public typealias J = [A] public static func fromJSON(x : JSONValue) -> J? { switch x { case let .JSONArray(xs): let r = xs.map(B.fromJSON) let rp = mapFlatten(r) if r.count == rp.count { return rp } else { return nil } default: return Optional.None } } } public struct JArrayTo<A, B : JSONEncodable where B.J == A> : JSONEncodable { public typealias J = [A] public static func toJSON(xs: J) -> JSONValue { return JSONValue.JSONArray(xs.map(B.toJSON)) } } public struct JArray<A, B : JSON where B.J == A> : JSON { public typealias J = [A] public static func fromJSON(x : JSONValue) -> J? { switch x { case let .JSONArray(xs): let r = xs.map(B.fromJSON) let rp = mapFlatten(r) if r.count == rp.count { return rp } else { return nil } default: return Optional.None } } public static func toJSON(xs : J) -> JSONValue { return JSONValue.JSONArray(xs.map(B.toJSON)) } } public struct JDictionaryFrom<A, B : JSONDecodable where B.J == A> : JSONDecodable { public typealias J = Dictionary<String, A> public static func fromJSON(x : JSONValue) -> J? { switch x { case let .JSONObject(xs): return Dictionary.fromList(xs.map({ k, x in return (k, B.fromJSON(x)!) })) default: return Optional.None } } } public struct JDictionaryTo<A, B : JSONEncodable where B.J == A> : JSONEncodable { public typealias J = Dictionary<String, A> public static func toJSON(xs : J) -> JSONValue { return JSONValue.JSONObject(Dictionary.fromList(xs.map({ k, x -> (String, JSONValue) in return (k, B.toJSON(x)) }))) } } public struct JDictionary<A, B : JSON where B.J == A> : JSON { public typealias J = Dictionary<String, A> public static func fromJSON(x : JSONValue) -> J? { switch x { case let .JSONObject(xs): return Dictionary<String, A>.fromList(xs.map({ k, x in return (k, B.fromJSON(x)!) })) default: return Optional.None } } public static func toJSON(xs : J) -> JSONValue { return JSONValue.JSONObject(Dictionary.fromList(xs.map({ k, x in return (k, B.toJSON(x)) }))) } } /// MARK: Implementation Details private func resolveKeypath(lhs : Dictionary<String, JSONValue>, rhs : JSONKeypath) -> JSONValue? { if rhs.path.isEmpty { return .None } switch rhs.path.match { case .Nil: return .None case let .Cons(hd, tl): if let o = lhs[hd] { switch o { case let .JSONObject(d) where rhs.path.count > 1: return resolveKeypath(d, rhs: JSONKeypath(tl)) default: return o } } return .None } }
bsd-3-clause
5a5e672bfea5931ea39ab7c12247f35e
22.152778
129
0.65077
3.146272
false
false
false
false
ming1016/smck
smck/Parser/SMLangAST.swift
1
1930
// // HtmlAST.swift // smck // // Created by Daiming on 2017/4/13. // Copyright © 2017年 Starming. All rights reserved. // import Foundation /* grammer Backus–Naur form(BNF) https://en.wikipedia.org/wiki/Backus-Naur_form <prototype> ::= <identifier> "(" <params> ")" <params> ::= <identifier> | <identifier>, <params> <definition> ::= "def" <prototype> <expr> ";" <extern> ::= "extern" <prototype> ";" <operator> ::= "+" | "-" | "*" | "/" | "%" <expr> ::= <binary> | <call> | <identifier> | <number> | <ifelse> | "(" <expr> ")" <binary> ::= <expr> <operator> <expr> <call> ::= <identifier> "(" <arguments> ")" <ifelse> ::= "if" <expr> "then" <expr> "else" <expr> <arguments> ::= <expr> | <expr> "," <arguments> */ struct SMLangPrototype { let name: String let params: [String] } indirect enum SMLangExpr { case number(Double) case variable(String) case binary(SMLangExpr, SMLangBinaryOperator, SMLangExpr) case call(String, [SMLangExpr]) case ifelse(SMLangExpr, SMLangExpr, SMLangExpr) } struct SMLangDefinition { let prototype: SMLangPrototype let expr: SMLangExpr } class SMLangFile { private(set) var externs = [SMLangPrototype]() private(set) var definitions = [SMLangDefinition]() private(set) var expressions = [SMLangExpr]() private(set) var prototypeMap = [String: SMLangPrototype]() func prototype(name:String) -> SMLangPrototype? { return prototypeMap[name] } func addExpression(_ expression:SMLangExpr) { expressions.append(expression) } func addExtern(_ prototype:SMLangPrototype) { externs.append(prototype) prototypeMap[prototype.name] = prototype } func addDefinition(_ definition:SMLangDefinition) { definitions.append(definition) prototypeMap[definition.prototype.name] = definition.prototype } }
apache-2.0
a54f7a34616bc7be2a824980a96c04c5
27.308824
89
0.625455
3.365385
false
false
false
false
trujillo138/MyExpenses
MyExpenses/MyExpenses/Scenes/ExpensePeriod/ExpensePeriodViewController.swift
1
11218
// // ExpensePeriodViewController.swift // MyExpenses // // Created by Tomas Trujillo on 6/26/17. // Copyright © 2017 TOMApps. All rights reserved. // import UIKit protocol ExpensePeriodPreviewActionListener: class { func exportPeriod(_ period: ExpensePeriod) func editPeriod(_ period: ExpensePeriod) } class ExpensePeriodViewController: UIViewController, UITableViewDelegate { //MARK: Properties var period: ExpensePeriod? var stateController: StateController? weak var delegate: ExpensePeriodPreviewActionListener? private let expenseCellIdentifier = "Expense cell" private let viewExpenseSegueIdentifier = "View expense" private let addExpenseSegueIdentifier = "Add expense" private let presentFilterOptionsSegueIdentifier = "PresentFilterOptions" private var dataSource: ExpensesDataSource? var expenses: [Expense] { return self.dataSource?.expenses ?? [Expense]() } private var orderListBy: ExpensePeriodSortOption? { didSet { guard let _ = orderListBy else { return } self.orderListByAscending = true self.orderAscendingButton.isEnabled = true self.refreshDataSource() self.expensesTable.reloadData() } } private var orderListByAscending = true { didSet { refreshDataSource() self.expensesTable.reloadData() } } private var filterListBy: ExpensePeriodFilterOption? { didSet { guard let _ = filterListBy else { return } self.refreshDataSource() self.expensesTable.reloadData() } } //MARK: Outlets @IBOutlet fileprivate weak var expensesTable: UITableView! @IBOutlet private weak var orderAscendingButton: UIBarButtonItem! @IBOutlet private weak var totalLabel: UILabel! @IBOutlet private weak var sortBarButton: UIBarButtonItem! //MARK: ViewController Lifecycle override func viewDidLoad() { super.viewDidLoad() title = period?.name registerTableViewCell() configureDataSource() configureDelegate() registerForPreviewing(with: self, sourceView: view) } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) refreshDataSource() expensesTable.reloadData() MyExpensesNotifications.NotifyHideAddButton() addFooterToTable() } private func addFooterToTable() { let footerView = UIView(frame: CGRect(x: 0.0, y: 0.0, width: view.frame.width, height: 30.0)) footerView.backgroundColor = UIColor.clear expensesTable.tableFooterView = footerView } private func refreshDataSource() { period = stateController?.getUpdatedVersionForPeriodWith(id: period?.idExpensePeriod) guard let expensePeriod = period else { return } if let orderAttrib = orderListBy { dataSource?.sortAttribute = orderAttrib dataSource?.ascending = orderListByAscending } if let filterAttrib = filterListBy { dataSource?.filterAttribute = filterAttrib } dataSource?.expensePeriod = expensePeriod calculatePeriodTotal() } private func calculatePeriodTotal() { let total = expenses.reduce(0) { x, y in x + y.amount } totalLabel.text = "\(period?.currency.rawValue ?? "") \(total.currencyFormat)" } private func registerTableViewCell() { expensesTable.register(UINib(nibName: "ExpenseCell", bundle: nil), forCellReuseIdentifier: expenseCellIdentifier) } private func configureDataSource() { guard let expensePeriod = period else { return } let expenseDataSource = ExpensesDataSource(expensePeriod: expensePeriod, cellIdentifier: expenseCellIdentifier) expensesTable.dataSource = expenseDataSource dataSource = expenseDataSource } private func configureDelegate() { expensesTable.delegate = self } //MARK: Tableview Delegate func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let cell = tableView.cellForRow(at: indexPath) performSegue(withIdentifier: viewExpenseSegueIdentifier, sender: cell) } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 100 } func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? { let action = UITableViewRowAction(style: .destructive, title: LStrings.ExpensePeriod.DeleteExpenseLabel) { _, _ in self.deleteExpense(from: tableView, at: indexPath) } return [action] } func deleteExpense(from tableView: UITableView, at indexPath: IndexPath) { guard let expensePeriod = self.period else { return } self.stateController?.deleteFrom(expensePeriod, expense: self.expenses[indexPath.row]) self.refreshDataSource() tableView.deleteRows(at: [indexPath], with: .fade) } //MARK: Actions @IBAction func filterButtonPressed(_ sender: Any) { performSegue(withIdentifier: presentFilterOptionsSegueIdentifier, sender: nil) } @IBAction func orderButtonPressed(_ sender: Any) { let orderActionSheetController = UIAlertController(title: LStrings.ExpensePeriod.SortTitleMessage, message: nil, preferredStyle: .actionSheet) orderActionSheetController.addAction(UIAlertAction(title: LStrings.Alerts.CancelButtonLabel, style: .cancel, handler: nil)) orderActionSheetController.addAction(UIAlertAction(title: LStrings.ExpensePeriod.SortOptionExpenseDate, style: .default, handler: { _ in self.orderListBy = .date })) orderActionSheetController.addAction(UIAlertAction(title: LStrings.ExpensePeriod.SortOptionExpenseName, style: .default, handler: { _ in self.orderListBy = .name })) orderActionSheetController.addAction(UIAlertAction(title: LStrings.ExpensePeriod.SortOptionExpenseAmount, style: .default, handler: { _ in self.orderListBy = .amount })) orderActionSheetController.addAction(UIAlertAction(title: LStrings.ExpensePeriod.SortOptionExpenseType, style: .default, handler: { _ in self.orderListBy = .type })) if UIDevice.isIpad() { orderActionSheetController.popoverPresentationController?.barButtonItem = sortBarButton } present(orderActionSheetController, animated: true, completion: nil) } @IBAction func changeAscensionOrderButtonPressed(_ sender: Any) { orderListByAscending = !orderListByAscending } @IBAction func selectedFilteroption(segue: UIStoryboardSegue) { guard let filterController = segue.source as? ExpenseFilterOptionViewController else { return } if filterController.toValue != nil || filterController.fromValue != nil { dataSource?.ascendingValue = filterController.fromValue dataSource?.descendingValue = filterController.toValue filterListBy = filterController.selectedFilterOption } } //MARK: Navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { guard let segueidentifier = segue.identifier else { return } if segueidentifier == viewExpenseSegueIdentifier { guard let dvc = segue.destination as? ExpenseViewController, let cell = sender as? UITableViewCell, let indexPath = expensesTable.indexPath(for: cell) else { return } let expense = expenses[indexPath.row] dvc.stateController = stateController dvc.expensePeriod = period dvc.expense = expense } else if segueidentifier == addExpenseSegueIdentifier { guard let navController = segue.destination as? UINavigationController, let dvc = navController.viewControllers.first as? ExpenseViewController else { return } dvc.stateController = stateController dvc.expensePeriod = period } else if segueidentifier == presentFilterOptionsSegueIdentifier { guard let navController = segue.destination as? UINavigationController, let dvc = navController.viewControllers.first as? ExpenseFilterOptionViewController else { return } dvc.maximumDate = period?.maxExpenseDateForPeriod dvc.minimumDate = period?.minExpenseDateForPeriod } } } extension ExpensePeriodViewController: UIViewControllerPreviewingDelegate { func previewingContext(_ previewingContext: UIViewControllerPreviewing, viewControllerForLocation location: CGPoint) -> UIViewController? { let newLocation = view.convert(location, to: expensesTable) guard let indexPath = expensesTable.indexPathForRow(at: newLocation), let cell = expensesTable.cellForRow(at: indexPath), let expenseController = storyboard?.instantiateExpenseViewController() else { return nil } let frame = expensesTable.convert(cell.frame, to: view) expenseController.expense = expenses[indexPath.row] expenseController.stateController = stateController expenseController.expensePeriod = period expenseController.previewActionsDelegate = self previewingContext.sourceRect = frame return expenseController } func previewingContext(_ previewingContext: UIViewControllerPreviewing, commit viewControllerToCommit: UIViewController) { guard let expenseController = viewControllerToCommit as? ExpenseViewController else { return } navigationController?.pushViewController(expenseController, animated: true) } } extension ExpensePeriodViewController: ExpensePreviewActionListener { func deleteExpense(expense: Expense) { var index = -1 for (i, exp) in expenses.enumerated() { if exp.idExpense == expense.idExpense { index = i break } } deleteExpense(from: expensesTable, at: IndexPath(row: index, section: 0)) } } extension ExpensePeriodViewController { override var previewActionItems: [UIPreviewActionItem] { let exportAction = UIPreviewAction(title: LStrings.ExpensePeriod.ExportExpensePeriodMenuItem, style: .default) { _, _ in guard let expensePeriod = self.period else { return } self.delegate?.exportPeriod(expensePeriod) } let editAction = UIPreviewAction(title: LStrings.User.EditButtonLabel, style: .default) { _, _ in guard let expensePeriod = self.period else { return } self.delegate?.editPeriod(expensePeriod) } return [exportAction, editAction] } }
apache-2.0
64fa7348b971576fe0cba3af8b4a6602
39.641304
183
0.667915
5.485086
false
false
false
false
soleiltw/ios-swift-basic
Workshop/Taipei-City-Water-Quality/Taipei-City-Water-Quality/ViewController/ViewController.swift
1
6461
// // ViewController.swift // Taipei-City-Water-Quality // // Created by Edward Chiang on 21/10/2017. // Copyright © 2017 Soleil Software Studio Inc. All rights reserved. // import Foundation import MapKit import UIKit class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, MKMapViewDelegate { // Networking let openDataURL : URL = URL(string: "http://data.taipei/opendata/datalist/apiAccess?scope=resourceAquire&rid=190796c8-7c56-42e0-8068-39242b8ec927")! // Swift Basic var stations = [Station]() // UIKit @IBOutlet weak var topBackgroundView: UIView! @IBOutlet weak var tableView: UITableView! // MapKit @IBOutlet weak var mapView: MKMapView! // UIKit var refreshControl : UIRefreshControl? override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. // UIKit // Handle display self.topBackgroundView.layer.shadowColor = UIColor.lightGray.cgColor self.topBackgroundView.layer.shadowOffset = CGSize.init(width: 0, height: 1) self.topBackgroundView.layer.shadowOpacity = 1 self.topBackgroundView.clipsToBounds = false if refreshControl == nil { refreshControl = UIRefreshControl() } refreshControl?.attributedTitle = NSAttributedString(string: "Pull to refresh") refreshControl?.addTarget(self, action: #selector(reload(sender:)) , for: .valueChanged) self.tableView.rowHeight = UITableViewAutomaticDimension self.tableView.estimatedRowHeight = 145 // Add Refresh Control to Table View if #available(iOS 10.0, *) { self.tableView.refreshControl = refreshControl } else { self.tableView.addSubview(refreshControl!) } self.reload(sender: self.refreshControl!) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @objc func reload(sender : AnyObject) { // Networking let urlRequest = URLRequest(url: openDataURL as URL, cachePolicy: .returnCacheDataElseLoad, timeoutInterval: 30) let task = URLSession.shared.dataTask(with: urlRequest) { (data, urlResponse, error) in if let data = data { do { // Serialized from data into Dictionary let dic : Dictionary = try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.mutableContainers) as! Dictionary<String, AnyObject> // Get result from json content let result = dic["result"] // Get the results core value we want let results : Array = result!["results"] as! Array<Dictionary<String, AnyObject>> self.stations.removeAll() results.forEach({ (object) -> () in let station : Station = Station.populate(dictionary: object) self.stations.append(station) // MapKit // Drop a pin at user's Current Location let stationAnnotation: MKPointAnnotation = MKPointAnnotation() stationAnnotation.coordinate = CLLocationCoordinate2DMake(Double(station.latitude)!, Double(station.longitude)!); stationAnnotation.title = station.codeName if (station.checkPh() == .normal) && (station.checkCl() == .normal) && (station.checkCntu() == .normal) { stationAnnotation.subtitle = "Normal" } self.mapView.addAnnotation(stationAnnotation) }) // UIKit DispatchQueue.main.async { self.tableView.reloadData() self.refreshControl?.endRefreshing() } } catch { } } } task.resume() } @IBAction func segmentedValueChanged(_ sender: Any) { // UIKit let segmentControl : UISegmentedControl = sender as! UISegmentedControl switch segmentControl.selectedSegmentIndex { case 1: self.tableView.isHidden = true self.mapView.isHidden = false self.mapView.showAnnotations(self.mapView.annotations, animated: true) break default: self.tableView.isHidden = false self.mapView.isHidden = true break } } // MARK: - UITableViewDataSource func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.stations.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "StationInfoCell", for: indexPath) let station : Station = self.stations[indexPath.row] let stationCell : StationViewCell = cell as! StationViewCell stationCell.quaIdLabel.text = station.quaId.trim() stationCell.codeNameLabel.text = station.codeName.trim() stationCell.phValueLabel.text = station.quaPh stationCell.mglValueLabel.text = station.quaCl stationCell.ntuValueLabel.text = station.quaCntu if station.checkCntu() == .normal { stationCell.ntuValueLabel.textColor = UIColor.blue } if station.checkCl() == .normal { stationCell.mglValueLabel.textColor = UIColor.blue } if station.checkPh() == .normal { stationCell.phValueLabel.textColor = UIColor.blue } return cell } func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { if (self.stations.count > 0) { return "\(self.stations[0].updateDate) \(self.stations[0].updateTime)" } return nil } }
mit
0669c6ebc8d55183278d2d3fd8e8f67f
37.452381
182
0.588854
5.392321
false
false
false
false
DivineDominion/mac-appdev-code
CoreDataOnly/BoxId.swift
1
556
import Foundation public struct BoxId: Identifiable { public let identifier: IntegerId public init(_ identifier: IntegerId) { self.identifier = identifier } init(fromNumber number: NSNumber) { self.identifier = number.int64Value } } extension BoxId: CustomDebugStringConvertible { public var debugDescription: String { return "BoxId: \(identifier)" } } extension BoxId: Equatable { } public func ==(lhs: BoxId, rhs: BoxId) -> Bool { return lhs.identifier == rhs.identifier }
mit
8bcb1bb2e3879db28ca622241e0167b4
19.592593
48
0.652878
4.34375
false
false
false
false
safx/TypetalkApp
TypetalkApp/DataSources/MessagesDataSource.swift
1
4224
// // MessagesDataSource.swift // TypetalkApp // // Created by Safx Developer on 2014/11/09. // Copyright (c) 2014年 Safx Developers. All rights reserved. // import TypetalkKit import RxSwift import ObservableArray class MessagesDataSource { typealias Event = ObservableArray<Post>.EventType let team = Variable(Team()) let topic = Variable(Topic()) let bookmark = Variable(Bookmark()) var posts = ObservableArray<Post>() let hasNext = Variable(false) let bookmarkIndex = Variable<Int>(0) var observing = false let disposeBag = DisposeBag() // MARK: - Model ops func fetch(topicId: TopicID) { posts.removeAll() fetch_impl(topicId, from: nil) // FIXME: use queue if !observing { observing = true startObserving() } } func fetchMore(topicId: TopicID) { let len = posts.count let from: PostID? = len == 0 ? nil : posts[0].id fetch_impl(topicId, from: from) } private func fetch_impl(topicId: TopicID, from: PostID?) { let s = TypetalkAPI.rx_sendRequest(GetMessages(topicId: topicId, count:100, from: from)) s.subscribe( onNext: { res in let firstFetch = self.posts.count == 0 _ = res.team.flatMap { self.team.value = $0 } self.topic.value = res.topic self.posts.insertContentsOf(res.posts, atIndex: 0) self.hasNext.value = res.hasNext if firstFetch { self.bookmark.value = res.bookmark self.updateBookmarkIndex(self.bookmark.value.postId) // FIXME: change automatically } }, onError: { err in print("E \(err)") }, onCompleted:{ () in } ) .addDisposableTo(disposeBag) } private func startObserving() { TypetalkAPI.rx_streamimg .subscribeNext { event in switch event { case .PostMessage(let res): self.appendMessage(res.post!) case .DeleteMessage(let res): self.deleteMessage(res.post!) case .LikeMessage(let res): self.addLikeMessage(res.like) case .UnlikeMessage(let res): self.removeLikeMessage(res.like) case .SaveBookmark(let res): self.updateBookmark(res.unread) default: () } } .addDisposableTo(disposeBag) } private func appendMessage(post: Post) { if post.topicId == topic.value.id { posts.append(post) } } private func find(topicId: TopicID, postId: PostID, closure: (Post, Int) -> ()) { if topicId != topic.value.id { return } for i in 0..<posts.count { if posts[i].id == postId { closure(posts[i], i) return } } } private func deleteMessage(post: Post) { find(post.topicId, postId: post.id) { post, i in self.posts.removeAtIndex(i) () } } private func addLikeMessage(like: Like) { find(like.topicId, postId: like.postId) { post, i in self.posts[i] = self.posts[i] + like } } private func removeLikeMessage(like: Like) { find(like.topicId, postId: like.postId) { post, i in self.posts[i] = self.posts[i] - like } } private func updateBookmark(unread: Unread) { if unread.topicId == topic.value.id { let b = Bookmark(postId: unread.postId, updatedAt: bookmark.value.updatedAt) bookmark.value = b updateBookmarkIndex(b.postId) // FIXME: change automatically } } private func updateBookmarkIndex(postId: PostID) { find(topic.value.id, postId: postId) { post, idx in self.bookmarkIndex.value = idx } } // MARK: Acting to REST client func postMessage(message: String) -> Observable<PostMessage.Response> { let id = topic.value.id return TypetalkAPI.rx_sendRequest(PostMessage(topicId: id, message: message, replyTo: nil, fileKeys: [], talkIds: [])) } }
mit
00e113d83ad01f7e56d6518ad8de91ed
28.732394
126
0.56703
4.222
false
false
false
false
gautier-gdx/Hexacon
Example/Pods/Hexacon/Hexacon/HexagonalPattern.swift
1
3857
// // HegagonalDirection.swift // Hexacon // // Created by Gautier Gdx on 06/02/16. // Copyright © 2016 Gautier. All rights reserved. // import UIKit final class HexagonalPattern { // MARK: - typeAlias typealias HexagonalPosition = (center: CGPoint,ring: Int) // MARK: - data internal var repositionCenter: ((CGPoint, Int, Int) -> ())? private var position: HexagonalPosition! { didSet { //while our position is bellow the size we can continue guard positionIndex < size else { reachedLastPosition = true return } //each time a new center is set we are sending it back to the scrollView repositionCenter?(position.center, position.ring, positionIndex) positionIndex += 1 } } private var directionFromCenter: HexagonalDirection private var reachedLastPosition = false private var positionIndex = 0 private let sideNumber: Int = 6 //properties private let size: Int private let itemSpacing: CGFloat private let maxRadius: Int // MARK: - init init(size: Int, itemSpacing: CGFloat, itemSize: CGFloat) { self.size = size self.itemSpacing = itemSpacing + itemSize - 8 maxRadius = size/6 + 1 directionFromCenter = .Right } // MARK: - instance methods /** calculate the theorical size of the grid - returns: the size of the grid */ func sizeForGridSize() -> CGFloat { return 2*itemSpacing*CGFloat(maxRadius) } /** create the grid with a circular pattern beginning from the center in each loop we are sending back a center for a new View */ func createGrid(FromCenter newCenter: CGPoint) { //initializing the algorythm start(newCenter: newCenter) //for each radius for radius in 0...maxRadius { guard reachedLastPosition == false else { continue } //we are creating a ring createRing(withRadius: radius) //then jumping to the next one jumpToNextRing() } } // MARK: - configuration methods private func neighbor(origin origin: CGPoint,direction: HexagonalDirection) -> CGPoint { //take the current direction let direction = direction.direction() //then multiply it to find the new center return CGPoint(x: origin.x + itemSpacing*direction.x,y: origin.y + itemSpacing*direction.y) } private func start(newCenter: CGPoint) { //initializing with the center given position = (center: newCenter,ring: 0) //then jump on the first ring position = (center: neighbor(origin: position.center,direction: .LeftDown),ring: 1) } private func createRing(withRadius radius: Int) { //for each side of the ring for _ in 0...(sideNumber - 1) { //in each posion in the side for directionIndex in 0...radius { //stop if we are at the end of the ring guard !(directionIndex == radius && directionFromCenter == .RightDown) else { continue } //or add a new point position = (center: neighbor(origin: position.center,direction: directionFromCenter),ring: radius + 1) } //then move to another position directionFromCenter.move() } } private func jumpToNextRing() { //the next ring is always two position bellow the previous one position = (center: CGPoint(x: position.center.x ,y: position.center.y + 2*itemSpacing),ring: position.ring + 1) } }
mit
b7bdb5610b7c15498c75488559ce5c08
29.362205
120
0.588693
4.838143
false
false
false
false
kotoole1/Paranormal
Paranormal/Paranormal/ToolSettings.swift
1
2072
import Foundation public class ToolSettings { weak var document : Document? init(){ } public var colorAsAngles : (direction:Float, pitch:Float) = (0.0,0.0) { didSet { updateToolSettingsView() } } public func updateToolSettingsView() { let panelVC = document?.singleWindowController?.panelsViewController panelVC?.toolSettingsViewController?.updateSettingsSliders() } public var colorAsNSColor : NSColor { let dir = colorAsAngles.direction * Float(M_PI) / 180.0 let pitt = colorAsAngles.pitch * Float(M_PI) / 180.0 let x = sin(dir) * sin(pitt) * 0.5 + 0.5 let y = cos(dir) * sin(pitt) * 0.5 + 0.5 let z = cos(pitt) * 0.5 + 0.5 return NSColor(red: CGFloat(x), green: CGFloat(y), blue: CGFloat(z), alpha: 1.0) } public func setColorAsNSColor(color : NSColor) { let normalZero : Float = 127.0 / 255.0; func transform(component : Float) -> Float { let n = 2.0 * (component - normalZero) if (abs(n) < 1e-8) { return 1e-8 }; return n } let x = transform(Float(color.redComponent)) let y = transform(Float(color.greenComponent)) let z = transform(Float(color.blueComponent)) var degree = atan2(x, y)*180.0/Float(M_PI) var pitch = atan2(sqrt(x*x + y*y),z)*180.0/Float(M_PI) degree = ((degree > 0) ? degree : (degree+360)) colorAsAngles = (round(degree*1e6)/1e6, round(pitch*1e6)/1e6) } public var size : Float = 30.0 { didSet { updateToolSettingsView() } } public var strength : Float = 1.0 { didSet { updateToolSettingsView() } } public var hardness : Float = 0.9 { didSet { updateToolSettingsView() } } //For smooth tool, though currently not used. public var gaussianRadius : Float = 30 { didSet { updateToolSettingsView() } } }
mit
ea0e4841f06dfe6d200183eb611e958d
28.183099
76
0.553571
3.706619
false
false
false
false
darina/omim
iphone/Maps/Classes/Components/Modal/PromoBookingPresentationController.swift
6
1444
final class PromoBookingPresentationController: DimmedModalPresentationController { let sideMargin: CGFloat = 32.0 let maxWidth: CGFloat = 310.0 override var frameOfPresentedViewInContainerView: CGRect { let f = super.frameOfPresentedViewInContainerView let estimatedWidth = min(maxWidth, f.width - (sideMargin * 2.0)) let s = presentedViewController.view.systemLayoutSizeFitting(CGSize(width: estimatedWidth, height: f.height), withHorizontalFittingPriority: .required, verticalFittingPriority: .defaultLow) let r = CGRect(x: (f.width - s.width) / 2, y: (f.height - s.height) / 2, width: s.width, height: s.height) return r } override func containerViewWillLayoutSubviews() { presentedView?.frame = frameOfPresentedViewInContainerView } override func presentationTransitionWillBegin() { super.presentationTransitionWillBegin() presentedViewController.view.layer.cornerRadius = 8 presentedViewController.view.clipsToBounds = true guard let containerView = containerView, let presentedView = presentedView else { return } containerView.addSubview(presentedView) presentedView.frame = frameOfPresentedViewInContainerView } override func dismissalTransitionDidEnd(_ completed: Bool) { super.presentationTransitionDidEnd(completed) guard let presentedView = presentedView else { return } if completed { presentedView.removeFromSuperview() } } }
apache-2.0
9380664a62c1a2be0dccbc3256e1d6c7
42.757576
193
0.763158
5.428571
false
false
false
false
cburrows/swift-protobuf
Sources/SwiftProtobuf/TextFormatEncoder.swift
1
9545
// Sources/SwiftProtobuf/TextFormatEncoder.swift - Text format encoding support // // Copyright (c) 2014 - 2019 Apple Inc. and the project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See LICENSE.txt for license information: // https://github.com/apple/swift-protobuf/blob/main/LICENSE.txt // // ----------------------------------------------------------------------------- /// /// Text format serialization engine. /// // ----------------------------------------------------------------------------- import Foundation private let asciiSpace = UInt8(ascii: " ") private let asciiColon = UInt8(ascii: ":") private let asciiComma = UInt8(ascii: ",") private let asciiMinus = UInt8(ascii: "-") private let asciiBackslash = UInt8(ascii: "\\") private let asciiDoubleQuote = UInt8(ascii: "\"") private let asciiZero = UInt8(ascii: "0") private let asciiOpenCurlyBracket = UInt8(ascii: "{") private let asciiCloseCurlyBracket = UInt8(ascii: "}") private let asciiOpenSquareBracket = UInt8(ascii: "[") private let asciiCloseSquareBracket = UInt8(ascii: "]") private let asciiNewline = UInt8(ascii: "\n") private let asciiUpperA = UInt8(ascii: "A") private let tabSize = 2 private let tab = [UInt8](repeating: asciiSpace, count: tabSize) /// TextFormatEncoder has no public members. internal struct TextFormatEncoder { private var data = [UInt8]() private var indentString: [UInt8] = [] var stringResult: String { get { return String(bytes: data, encoding: String.Encoding.utf8)! } } internal mutating func append(staticText: StaticString) { let buff = UnsafeBufferPointer(start: staticText.utf8Start, count: staticText.utf8CodeUnitCount) data.append(contentsOf: buff) } internal mutating func append(name: _NameMap.Name) { data.append(contentsOf: name.utf8Buffer) } internal mutating func append(bytes: [UInt8]) { data.append(contentsOf: bytes) } private mutating func append(text: String) { data.append(contentsOf: text.utf8) } init() {} internal mutating func indent() { data.append(contentsOf: indentString) } mutating func emitFieldName(name: UnsafeRawBufferPointer) { indent() data.append(contentsOf: name) } mutating func emitFieldName(name: StaticString) { let buff = UnsafeRawBufferPointer(start: name.utf8Start, count: name.utf8CodeUnitCount) emitFieldName(name: buff) } mutating func emitFieldName(name: [UInt8]) { indent() data.append(contentsOf: name) } mutating func emitExtensionFieldName(name: String) { indent() data.append(asciiOpenSquareBracket) append(text: name) data.append(asciiCloseSquareBracket) } mutating func emitFieldNumber(number: Int) { indent() appendUInt(value: UInt64(number)) } mutating func startRegularField() { append(staticText: ": ") } mutating func endRegularField() { data.append(asciiNewline) } // In Text format, a message-valued field writes the name // without a trailing colon: // name_of_field {key: value key2: value2} mutating func startMessageField() { append(staticText: " {\n") indentString.append(contentsOf: tab) } mutating func endMessageField() { indentString.removeLast(tabSize) indent() append(staticText: "}\n") } mutating func startArray() { data.append(asciiOpenSquareBracket) } mutating func arraySeparator() { append(staticText: ", ") } mutating func endArray() { data.append(asciiCloseSquareBracket) } mutating func putEnumValue<E: Enum>(value: E) { if let name = value.name { data.append(contentsOf: name.utf8Buffer) } else { appendInt(value: Int64(value.rawValue)) } } mutating func putFloatValue(value: Float) { if value.isNaN { append(staticText: "nan") } else if !value.isFinite { if value < 0 { append(staticText: "-inf") } else { append(staticText: "inf") } } else { data.append(contentsOf: value.debugDescription.utf8) } } mutating func putDoubleValue(value: Double) { if value.isNaN { append(staticText: "nan") } else if !value.isFinite { if value < 0 { append(staticText: "-inf") } else { append(staticText: "inf") } } else { data.append(contentsOf: value.debugDescription.utf8) } } private mutating func appendUInt(value: UInt64) { if value >= 1000 { appendUInt(value: value / 1000) } if value >= 100 { data.append(asciiZero + UInt8((value / 100) % 10)) } if value >= 10 { data.append(asciiZero + UInt8((value / 10) % 10)) } data.append(asciiZero + UInt8(value % 10)) } private mutating func appendInt(value: Int64) { if value < 0 { data.append(asciiMinus) // This is the twos-complement negation of value, // computed in a way that won't overflow a 64-bit // signed integer. appendUInt(value: 1 + ~UInt64(bitPattern: value)) } else { appendUInt(value: UInt64(bitPattern: value)) } } mutating func putInt64(value: Int64) { appendInt(value: value) } mutating func putUInt64(value: UInt64) { appendUInt(value: value) } mutating func appendUIntHex(value: UInt64, digits: Int) { if digits == 0 { append(staticText: "0x") } else { appendUIntHex(value: value >> 4, digits: digits - 1) let d = UInt8(truncatingIfNeeded: value % 16) data.append(d < 10 ? asciiZero + d : asciiUpperA + d - 10) } } mutating func putUInt64Hex(value: UInt64, digits: Int) { appendUIntHex(value: value, digits: digits) } mutating func putBoolValue(value: Bool) { append(staticText: value ? "true" : "false") } mutating func putStringValue(value: String) { data.append(asciiDoubleQuote) for c in value.unicodeScalars { switch c.value { // Special two-byte escapes case 8: append(staticText: "\\b") case 9: append(staticText: "\\t") case 10: append(staticText: "\\n") case 11: append(staticText: "\\v") case 12: append(staticText: "\\f") case 13: append(staticText: "\\r") case 34: append(staticText: "\\\"") case 92: append(staticText: "\\\\") case 0...31, 127: // Octal form for C0 control chars data.append(asciiBackslash) data.append(asciiZero + UInt8(c.value / 64)) data.append(asciiZero + UInt8(c.value / 8 % 8)) data.append(asciiZero + UInt8(c.value % 8)) case 0...127: // ASCII data.append(UInt8(truncatingIfNeeded: c.value)) case 0x80...0x7ff: data.append(0xc0 + UInt8(c.value / 64)) data.append(0x80 + UInt8(c.value % 64)) case 0x800...0xffff: data.append(0xe0 + UInt8(truncatingIfNeeded: c.value >> 12)) data.append(0x80 + UInt8(truncatingIfNeeded: (c.value >> 6) & 0x3f)) data.append(0x80 + UInt8(truncatingIfNeeded: c.value & 0x3f)) default: data.append(0xf0 + UInt8(truncatingIfNeeded: c.value >> 18)) data.append(0x80 + UInt8(truncatingIfNeeded: (c.value >> 12) & 0x3f)) data.append(0x80 + UInt8(truncatingIfNeeded: (c.value >> 6) & 0x3f)) data.append(0x80 + UInt8(truncatingIfNeeded: c.value & 0x3f)) } } data.append(asciiDoubleQuote) } mutating func putBytesValue(value: Data) { data.append(asciiDoubleQuote) value.withUnsafeBytes { (body: UnsafeRawBufferPointer) in if let p = body.baseAddress, body.count > 0 { for i in 0..<body.count { let c = p[i] switch c { // Special two-byte escapes case 8: append(staticText: "\\b") case 9: append(staticText: "\\t") case 10: append(staticText: "\\n") case 11: append(staticText: "\\v") case 12: append(staticText: "\\f") case 13: append(staticText: "\\r") case 34: append(staticText: "\\\"") case 92: append(staticText: "\\\\") case 32...126: // printable ASCII data.append(c) default: // Octal form for non-printable chars data.append(asciiBackslash) data.append(asciiZero + UInt8(c / 64)) data.append(asciiZero + UInt8(c / 8 % 8)) data.append(asciiZero + UInt8(c % 8)) } } } } data.append(asciiDoubleQuote) } }
apache-2.0
ae44596758f1a78ccaa3396ab7409102
31.246622
104
0.550026
4.398618
false
false
false
false
zskyfly/twitter
twitter/ProfileViewController.swift
1
1486
// // ProfileViewController.swift // twitter // // Created by Zachary Matthews on 2/26/16. // Copyright © 2016 zskyfly productions. All rights reserved. // import UIKit class ProfileViewController: UIViewController { var user: User? @IBOutlet weak var userProfileView: UserProfileView! override func viewDidLoad() { super.viewDidLoad() configureViewContent() // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) // UIView.animateWithDuration(3.0, animations: { () -> Void in // self.navigationController?.navigationBarHidden = true // self.navigationController?.setNavigationBarHidden(true, animated: true) // }, completion: nil) } // override func prefersStatusBarHidden() -> Bool { // return navigationController?.navigationBarHidden == true // } // // override func preferredStatusBarUpdateAnimation() -> UIStatusBarAnimation { // return UIStatusBarAnimation.Slide // } func configureViewContent() { if let user = self.user { userProfileView.user = user // navigationController?.hidesBarsOnTap = true } else { userProfileView.user = User._currentUser } } }
apache-2.0
e27def15d519e10288057d0348976d48
27.557692
85
0.654545
5.103093
false
false
false
false
superk589/ZKDrawerController
Sources/ZKDrawerShadowView.swift
1
1277
// // ZKDrawerShadowView.swift // ZKDrawerController // // Created by zzk on 2017/1/8. // Copyright © 2017年 zzk. All rights reserved. // import UIKit class ZKDrawerShadowView: UIView { enum Direction { case left case right } var direction: Direction = .left override init(frame: CGRect) { super.init(frame: frame) self.backgroundColor = UIColor.clear } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func draw(_ rect: CGRect) { let locations:[CGFloat] = (direction == .left ? [0, 1] : [1, 0]) let colorSpace = CGColorSpaceCreateDeviceRGB() let colors = [UIColor.black.withAlphaComponent(0.5).cgColor, UIColor.black.withAlphaComponent(0).cgColor] let gradient = CGGradient.init(colorsSpace: colorSpace, colors: colors as CFArray, locations: locations) let startPoint = CGPoint.init(x: 0, y: 0) let endPoint = CGPoint.init(x: rect.size.width, y: 0) let context = UIGraphicsGetCurrentContext() context?.drawLinearGradient(gradient!, start: startPoint, end: endPoint, options: CGGradientDrawingOptions.init(rawValue: 0)) } }
mit
c3da10b3b2cd9e7c71403dfce979b3af
28.627907
133
0.638932
4.363014
false
false
false
false
abelsanchezali/ViewBuilder
Source/Extensions/UIButton+Properties.swift
1
1949
// // UIButton+Properties.swift // ViewBuilder // // Created by Abel Sanchez on 7/7/16. // Copyright © 2016 Abel Sanchez. All rights reserved. // import UIKit public extension UIButton { @objc var titleString: StringForState? { set { guard let title = newValue else { return } setTitle(title.value, for: title.state) } get { return StringForState(value: self.title(for: self.state), state: self.state); } } @objc var titleAttributed: AttributedForState? { set { guard let attributed = newValue else { return } setAttributedTitle(attributed.value, for: attributed.state) } get { return AttributedForState(value: self.attributedTitle(for: self.state), state: self.state); } } @objc var titleColor: ColorForState? { set { guard let color = newValue else { return } setTitleColor(color.value, for: color.state) } get { return nil } } @objc var image: ImageForState? { set { guard let image = newValue else { return } setImage(image.value, for: image.state) } get { return nil } } @objc var backgroundImage: ImageForState? { set { guard let image = newValue else { return } setBackgroundImage(image.value, for: image.state) } get { return nil } } @objc var titleShadowColor: ColorForState? { set { guard let color = newValue else { return } setTitleShadowColor(color.value, for: color.state) } get { return nil } } }
mit
3419c999d1d7c4b028e367d560011410
22.190476
103
0.49384
4.857855
false
false
false
false
airbnb/lottie-ios
Sources/Private/Utility/Primitives/BezierPathRoundExtension.swift
2
4822
// // BezierPathRoundExtension.swift // Lottie // // Created by Duolingo on 11/1/22. // import CoreGraphics import Foundation // Adapted to Swift from lottie-web & lottie-android: // Rounded corner algorithm: // Iterate through each vertex. // If a vertex is a sharp corner, it rounds it. // If a vertex has control points, it is already rounded, so it does nothing. // // To round a vertex: // Split the vertex into two. // Move vertex 1 directly towards the previous vertex. // Set vertex 1's in control point to itself so it is not rounded on that side. // Extend vertex 1's out control point towards the original vertex. // // Repeat for vertex 2: // Move vertex 2 directly towards the next vertex. // Set vertex 2's out point to itself so it is not rounded on that side. // Extend vertex 2's in control point towards the original vertex. // // The distance that the vertices and control points are moved are relative to the // shape's vertex distances and the roundedness set in the animation. extension CompoundBezierPath { // Round corners of a compound bezier func roundCorners(radius: CGFloat) -> CompoundBezierPath { var newPaths = [BezierPath]() for path in paths { newPaths.append( path.roundCorners(radius: radius)) } return CompoundBezierPath(paths: newPaths) } } extension BezierPath { // Computes a new `BezierPath` with each corner rounded based on the given `radius` func roundCorners(radius: CGFloat) -> BezierPath { var newPath = BezierPath() var uniquePath = BezierPath() var currentVertex: CurveVertex var closestVertex: CurveVertex var distance: CGFloat var newPosPerc: CGFloat var closestIndex: Int var iX: CGFloat var iY: CGFloat var vX: CGFloat var vY: CGFloat var oX: CGFloat var oY: CGFloat var startIndex = 0 let TANGENT_LENGTH = 0.5519 // If start and end are the same we close the path if elements[0].vertex.point == elements[elements.count - 1].vertex.point, elements[0].vertex.inTangent == elements[elements.count - 1].vertex.inTangent, elements[0].vertex.outTangent == elements[elements.count - 1].vertex.outTangent { startIndex = 1 newPath.close() } guard elements.count - startIndex > 1 else { return self } for i in startIndex..<elements.count { uniquePath.addVertex(elements[i].vertex) } for elementIndex in 0..<uniquePath.elements.count { currentVertex = uniquePath.elements[elementIndex].vertex guard currentVertex.point.x == currentVertex.outTangent.x, currentVertex.point.y == currentVertex.outTangent.y, currentVertex.point.x == currentVertex.inTangent.x, currentVertex.point.y == currentVertex.inTangent.y else { newPath.addVertex(currentVertex) continue } // Do not round start and end if not closed if !newPath.closed, elementIndex == 0 || elementIndex == uniquePath.elements.count - 1 { newPath.addVertex(currentVertex) } else { closestIndex = elementIndex - 1 if closestIndex < 0 { closestIndex = uniquePath.elements.count - 1 } closestVertex = uniquePath.elements[closestIndex].vertex distance = currentVertex.point.distanceTo(closestVertex.point) newPosPerc = distance != 0 ? min(distance / 2, radius) / distance : 0 iX = currentVertex.point.x + (closestVertex.point.x - currentVertex.point.x) * newPosPerc vX = iX iY = currentVertex.point.y - (currentVertex.point.y - closestVertex.point.y) * newPosPerc vY = iY oX = vX - (vX - currentVertex.point.x) * TANGENT_LENGTH oY = vY - (vY - currentVertex.point.y) * TANGENT_LENGTH newPath.addVertex( CurveVertex( CGPoint(x: iX, y: iY), CGPoint(x: vX, y: vY), CGPoint(x: oX, y: oY))) closestIndex = (elementIndex + 1) % uniquePath.elements.count closestVertex = uniquePath.elements[closestIndex].vertex distance = currentVertex.point.distanceTo(closestVertex.point) newPosPerc = distance != 0 ? min(distance / 2, radius) / distance : 0 oX = currentVertex.point.x + (closestVertex.point.x - currentVertex.point.x) * newPosPerc vX = oX oY = currentVertex.point.y + (closestVertex.point.y - currentVertex.point.y) * newPosPerc vY = oY iX = vX - (vX - currentVertex.point.x) * TANGENT_LENGTH iY = vY - (vY - currentVertex.point.y) * TANGENT_LENGTH newPath.addVertex( CurveVertex( CGPoint(x: iX, y: iY), CGPoint(x: vX, y: vY), CGPoint(x: oX, y: oY))) } } return newPath } }
apache-2.0
0107227807199043812b0b4f391f91e1
31.802721
97
0.649316
3.873092
false
false
false
false
marty-suzuki/HoverConversion
HoverConversionSample/HoverConversionSample/Request/UsersLookUpRequest.swift
1
1062
// // UsersLookUpRequest.swift // HoverConversionSample // // Created by 鈴木大貴 on 2016/09/08. // Copyright © 2016年 szk-atmosphere. All rights reserved. // import Foundation import TwitterKit struct UsersLookUpRequest: TWTRGetRequestable { typealias ResponseType = [TWTRUser] typealias ParseResultType = [[String : NSObject]] let path: String = "/1.1/users/lookup.json" let screenNames: [String] var parameters: [AnyHashable: Any]? { let screenNameValue: String = screenNames.joined(separator: ",") let parameters: [AnyHashable: Any] = [ "screen_name" : screenNameValue, "include_entities" : "true" ] return parameters } static func decode(_ data: Data) -> TWTRResult<ResponseType> { switch UsersLookUpRequest.parseData(data) { case .success(let parsedData): return .success(parsedData.flatMap { TWTRUser(jsonDictionary: $0) }) case .failure(let error): return .failure(error) } } }
mit
4d9876a8bd6cba91f6c94f500c3dc3d3
27.405405
80
0.630828
4.121569
false
false
false
false
zoeyzhong520/InformationTechnology
InformationTechnology/InformationTechnology/Classes/Resources资源/标签栏/topCell.swift
1
1529
// // topCell.swift // InformationTechnology // // Created by zzj on 16/11/13. // Copyright © 2016年 zzj. All rights reserved. // import UIKit class topCell: UITableViewCell { @IBOutlet weak var avatarImgView: UIImageView! @IBOutlet weak var loginLabel: UILabel! //点击事件 @IBAction func clickBtn(sender: UIButton) { } @IBOutlet weak var historyImg: UIImageView! @IBOutlet weak var commentImg: UIImageView! @IBOutlet weak var messageImg: UIImageView! @IBOutlet weak var collectImg: UIImageView! @IBOutlet weak var historyLabel: UILabel! @IBOutlet weak var commentLabel: UILabel! @IBOutlet weak var messageLabel: UILabel! @IBOutlet weak var collectLabel: UILabel! override func awakeFromNib() { super.awakeFromNib() // Initialization code } //创建cell的方法 class func createTopCellFor(tableView:UITableView, atIndexPath indexPath:NSIndexPath) -> topCell { let cellId = "topCellId" var cell = tableView.dequeueReusableCellWithIdentifier(cellId) as? topCell if cell == nil { cell = NSBundle.mainBundle().loadNibNamed("topCell", owner: nil, options: nil).last as? topCell } return cell! } override func setSelected(selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } }
mit
716e0ed453c8411c382b3ed57b4e7889
23.322581
107
0.636605
4.848875
false
false
false
false
alexsosn/ConvNetSwift
ConvNetSwift/convnet-swift/Layers/LayersDropout/LayersDropout.swift
1
3210
// An inefficient dropout layer // Note this is not most efficient implementation since the layer before // computed all these activations and now we're just going to drop them :( // same goes for backward pass. Also, if we wanted to be efficient at test time // we could equivalently be clever and upscale during train and copy pointers during test // todo: make more efficient. import Foundation struct DropoutLayerOpt: LayerInOptProtocol, DropProbProtocol { var layerType: LayerType = .Dropout var inDepth: Int = 0 var inSx: Int = 0 var inSy: Int = 0 var dropProb: Double? = 0.5 init(dropProb: Double) { self.dropProb = dropProb } } class DropoutLayer: InnerLayer { var outSx: Int = 0 var outSy: Int = 0 var outDepth: Int = 0 var layerType: LayerType var dropped: [Bool] = [] var dropProb: Double = 0.0 var inAct: Vol? var outAct: Vol? init(opt: DropoutLayerOpt) { // computed outSx = opt.inSx outSy = opt.inSy outDepth = opt.inDepth layerType = .Dropout dropProb = opt.dropProb ?? 0.0 dropped = ArrayUtils.zerosBool(outSx*outSy*outDepth) } // default is prediction mode func forward(_ V: inout Vol, isTraining: Bool = false) -> Vol { inAct = V let V2 = V.clone() let N = V.w.count dropped = ArrayUtils.zerosBool(N) if isTraining { // do dropout for i in 0 ..< N { if RandUtils.random_js()<dropProb { V2.w[i]=0 dropped[i] = true } // drop! } } else { // scale the activations during prediction for i in 0 ..< N { V2.w[i]*=(1-dropProb) } } outAct = V2 return outAct! // dummy identity function for now } func backward() -> () { guard let V = inAct, // we need to set dw of this let chainGrad = outAct else { return } let N = V.w.count V.dw = ArrayUtils.zerosDouble(N) // zero out gradient wrt data for i in 0 ..< N { if !(dropped[i]) { V.dw[i] = chainGrad.dw[i] // copy over the gradient } } } func getParamsAndGrads() -> [ParamsAndGrads] { return [] } func assignParamsAndGrads(_ paramsAndGrads: [ParamsAndGrads]) { } func toJSON() -> [String: AnyObject] { var json: [String: AnyObject] = [:] json["outDepth"] = outDepth as AnyObject? json["outSx"] = outSx as AnyObject? json["outSy"] = outSy as AnyObject? json["layerType"] = layerType.rawValue as AnyObject? json["dropProb"] = dropProb as AnyObject? return json } // // func fromJSON(json) -> () { // outDepth = json["outDepth"] // outSx = json["outSx"] // outSy = json["outSy"] // layerType = json["layerType"]; // dropProb = json["dropProb"] // } }
mit
bb10899624b3b01b8b790dcdf9eecb25
27.660714
89
0.523053
4.196078
false
false
false
false
suragch/aePronunciation-iOS
aePronunciation/MyUserDefaults.swift
1
4025
import UIKit class MyUserDefaults { static let TEST_NAME_KEY = "testName" static let NUMBER_OF_QUESTIONS_KEY = "numberOfQuestions" static let TEST_MODE_KEY = "testMode" static let VOWEL_ARRAY_KEY = "vowelArray" static let CONSONANT_ARRAY_KEY = "consonantArray" static let PRACTICE_MODE_IS_SINGLE_KEY = "practiceMode" static let TIME_LEARN_SINGLE_KEY = "timeLearnSingle" static let TIME_LEARN_DOUBLE_KEY = "timeLearnDouble" static let TIME_PRACTICE_SINGLE_KEY = "timePracticeSingle" static let TIME_PRACTICE_DOUBLE_KEY = "timePracticeDouble" static let TIME_TEST_SINGLE_KEY = "timeTestSingle" static let TIME_TEST_DOUBLE_KEY = "timeTestDouble" static let defaultNumberOfTestQuestions = 50; static let defaultTestMode = SoundMode.single private static let defaults = UserDefaults.standard static var storedPracticeMode: SoundMode { get { let isSingle = defaults.bool(forKey: PRACTICE_MODE_IS_SINGLE_KEY) if isSingle {return SoundMode.single} return SoundMode.double } } // just to be called one time in the AppDelegate class func registerDefaults() { //let defaults = UserDefaults.standard let defaultValues : [String : Any] = [ TEST_NAME_KEY : "", NUMBER_OF_QUESTIONS_KEY : defaultNumberOfTestQuestions, TEST_MODE_KEY : SoundMode.single.rawValue ] defaults.register(defaults: defaultValues) } class func getTestSetupPreferences() -> (name: String, number: Int, mode: SoundMode) { //let defaults = UserDefaults.standard let name = defaults.string(forKey: TEST_NAME_KEY) ?? "" let number = defaults.integer(forKey: NUMBER_OF_QUESTIONS_KEY) let soundModeRaw = defaults.string(forKey: TEST_MODE_KEY) var mode = SoundMode.single if soundModeRaw == SoundMode.double.rawValue { mode = SoundMode.double } return (name, number, mode) } class func saveTestSetupPreferences(name: String, number: Int, mode: SoundMode) { //let defaults = UserDefaults.standard defaults.set(name, forKey: TEST_NAME_KEY) defaults.set(number, forKey: NUMBER_OF_QUESTIONS_KEY) defaults.set(mode.rawValue, forKey: TEST_MODE_KEY) } class func addTime(for currentType: StudyTimer.StudyType, time: TimeInterval) { let key: String switch currentType { case .learnSingle: key = TIME_LEARN_SINGLE_KEY case .learnDouble: key = TIME_LEARN_DOUBLE_KEY case .practiceSingle: key = TIME_PRACTICE_SINGLE_KEY case .practiceDouble: key = TIME_PRACTICE_DOUBLE_KEY case .testSingle: key = TIME_TEST_SINGLE_KEY case .testDouble: key = TIME_TEST_DOUBLE_KEY } let formerTime = defaults.double(forKey: key) let updatedTime = formerTime + time defaults.set(updatedTime, forKey: key) } class func getSecondsLearningSingles() -> Int { return getTimeInSeconds(forKey: TIME_LEARN_SINGLE_KEY) } class func getSecondsLearningDoubles() -> Int { return getTimeInSeconds(forKey: TIME_LEARN_DOUBLE_KEY) } class func getSecondsPracticingSingles() -> Int { return getTimeInSeconds(forKey: TIME_PRACTICE_SINGLE_KEY) } class func getSecondsPracticingDoubles() -> Int { return getTimeInSeconds(forKey: TIME_PRACTICE_DOUBLE_KEY) } class func getSecondsTestingSingles() -> Int { return getTimeInSeconds(forKey: TIME_TEST_SINGLE_KEY) } class func getSecondsTestingDoubles() -> Int { return getTimeInSeconds(forKey: TIME_TEST_DOUBLE_KEY) } private class func getTimeInSeconds(forKey key: String) -> Int { return defaults.integer(forKey: key) } }
unlicense
f44a66b7c61ed8950dd861e6a5772a34
34.619469
85
0.635031
4.205852
false
true
false
false
nguyenantinhbk77/practice-swift
File Management/Enumerating Files and Folders/Enumerating Files and Folders/AppDelegate.swift
2
3386
// // AppDelegate.swift // Enumerating Files and Folders // // Created by Domenico on 27/05/15. // License MIT. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func contentsOfAppBundle() -> [NSURL]{ let propertiesToGet = [ NSURLIsDirectoryKey, NSURLIsReadableKey, NSURLCreationDateKey, NSURLContentAccessDateKey, NSURLContentModificationDateKey ] var error:NSError? let fileManager = NSFileManager() let bundleUrl = NSBundle.mainBundle().bundleURL let result = fileManager.contentsOfDirectoryAtURL(bundleUrl, includingPropertiesForKeys: propertiesToGet, options: nil, error: &error) as! [NSURL] if let theError = error{ println("An error occurred") } return result } func stringValueOfBoolProperty(property: String, url: NSURL) -> String{ var value:AnyObject? var error:NSError? if url.getResourceValue( &value, forKey: property, error: &error) && value != nil{ let number = value as! NSNumber return number.boolValue ? "YES" : "NO" } return "NO" } func isUrlDirectory(url: NSURL) -> String{ return stringValueOfBoolProperty(NSURLIsDirectoryKey, url: url) } func isUrlReadable(url: NSURL) -> NSString{ return stringValueOfBoolProperty(NSURLIsReadableKey, url: url) } func dateOfType(type: String, url: NSURL) -> NSDate?{ var value:AnyObject? var error:NSError? if url.getResourceValue( &value, forKey: type, error: &error) && value != nil{ return value as? NSDate } return nil } func printUrlPropertiesToConsole(url: NSURL){ println("URL name = \(url.lastPathComponent)") println("Is a Directory? \(isUrlDirectory(url))") println("Is Readable? \(isUrlReadable(url))") if let creationDate = dateOfType(NSURLCreationDateKey, url: url){ println("Creation Date = \(creationDate)") } if let accessDate = dateOfType(NSURLContentAccessDateKey, url: url){ println("Access Date = \(accessDate)") } if let modificationDate = dateOfType(NSURLContentModificationDateKey, url: url){ println("Modification Date = \(modificationDate)") } println("-----------------------------------") } func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject : AnyObject]?) -> Bool { let appBundleContents = contentsOfAppBundle() for url in appBundleContents{ printUrlPropertiesToConsole(url) } self.window = UIWindow(frame: UIScreen.mainScreen().bounds) // Override point for customization after application launch. self.window!.backgroundColor = UIColor.whiteColor() self.window!.makeKeyAndVisible() return true } }
mit
cf01403d179eb94a34a5c6d27bec183d
28.443478
87
0.564678
5.523654
false
false
false
false
Gaea-iOS/FoundationExtension
FoundationExtension/Classes/Foundation/Timer+Weak.swift
1
2180
// // Timer+Weak.swift // Pods // // Created by 王小涛 on 2017/5/5. // // import Foundation private class WeakTimerProxy { private weak var _target: AnyObject? private let _block: (Timer) -> Void init(target: AnyObject, block: @escaping (Timer) -> Void) { _target = target _block = block } @objc func timerDidfire(timer: Timer) { if let _ = _target { _block(timer) }else { timer.invalidate() } } } public extension Timer { static func with(timeInterval: TimeInterval, target: AnyObject, block: @escaping (Timer) -> Void, userInfo: Any?, repeats: Bool) -> Timer { let proxy = WeakTimerProxy(target: target, block: block) return Timer(timeInterval: timeInterval, target: proxy, selector: #selector(WeakTimerProxy.timerDidfire(timer:)), userInfo: userInfo, repeats: repeats) } @discardableResult static func after(interval: TimeInterval, target: AnyObject, block: @escaping (Timer) -> Void) -> Timer { let timer = Timer.with(timeInterval: interval, target: target, block: block, userInfo: nil, repeats: false) timer.start() return timer } @discardableResult static func every(interval: TimeInterval, target: AnyObject, block: @escaping (Timer) -> Void) -> Timer { let timer = Timer.with(timeInterval: interval, target: target, block: block, userInfo: nil, repeats: true) timer.start() return timer } /// Schedule this timer on the run loop /// /// By default, the timer is scheduled on the current run loop for the default mode. /// Specify `runLoop` or `modes` to override these defaults. func start(runLoop: RunLoop = RunLoop.current, modes: RunLoop.Mode...) { // Common Modes包含default modes,modal modes,event Tracking modes. // 从NSTimer的失效性谈起(一):关于NSTimer和NSRunLoop // https://yq.aliyun.com/articles/17710 let modes = modes.isEmpty ? [RunLoop.Mode.common] : modes for mode in modes { runLoop.add(self, forMode: mode) } } }
mit
72ff37356aac6248182be26dc87679ed
28.342466
159
0.623249
4.135135
false
false
false
false
denmanboy/IQKeyboardManager
KeyboardTextFieldDemo/IQKeyboardManager Swift/ScrollViewController.swift
19
2312
// // ScrollViewController.swift // IQKeyboard // // Created by Iftekhar on 23/09/14. // Copyright (c) 2014 Iftekhar. All rights reserved. // import Foundation import UIKit class ScrollViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, UITextFieldDelegate, UITextViewDelegate { @IBOutlet private var scrollViewDemo : UIScrollView!; @IBOutlet private var simpleTableView : UITableView!; @IBOutlet private var scrollViewOfTableViews : UIScrollView!; @IBOutlet private var tableViewInsideScrollView : UITableView!; @IBOutlet private var scrollViewInsideScrollView : UIScrollView!; @IBOutlet private var topTextField : UITextField!; @IBOutlet private var bottomTextField : UITextField!; @IBOutlet private var topTextView : UITextView!; @IBOutlet private var bottomTextView : UITextView!; override func viewDidLoad() { super.viewDidLoad() scrollViewDemo.contentSize = CGSizeMake(0, 321); scrollViewInsideScrollView.contentSize = CGSizeMake(0,321); } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 5; } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let identifier = "\(indexPath.section) \(indexPath.row)" var cell : UITableViewCell? = tableView.dequeueReusableCellWithIdentifier(identifier) as? UITableViewCell if cell == nil { cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: identifier) cell?.selectionStyle = UITableViewCellSelectionStyle.None cell?.backgroundColor = UIColor.clearColor() let textField = UITextField(frame: CGRectInset(cell!.contentView.bounds, 5, 5)) textField.autoresizingMask = UIViewAutoresizing.FlexibleBottomMargin | UIViewAutoresizing.FlexibleTopMargin | UIViewAutoresizing.FlexibleWidth textField.placeholder = identifier textField.borderStyle = UITextBorderStyle.RoundedRect cell?.contentView.addSubview(textField) } return cell! } override func shouldAutorotate() -> Bool { return true } }
mit
48d1fd6bdce3e836e38c0188c3c1b692
35.125
154
0.696799
6.005195
false
false
false
false
lichendi/ExtendEverything
Extensions/UIColor+hex.swift
1
1130
// // UIImage+color.swift // ExtendEverything // github https://github.com/lichendi/ExtendEverything // Created by LiChendi on 2017/2/12. // Copyright © 2017年 Li Chendi. All rights reserved. // // extension UIColor { // convenience init(red: Int, green: Int, blue: Int) { // assert(red >= 0 && red <= 255, "Invalid red component") // assert(green >= 0 && green <= 255, "Invalid green component") // assert(blue >= 0 && blue <= 255, "Invalid blue component") // self.init(red: CGFloat(red) / 255.0, green: CGFloat(green) / 255.0, blue: CGFloat(blue) / 255.0, alpha: 1.0) // } // convenience init(hex:Int) { // self.init(red:(netHex >> 16) & 0xff, green:(netHex >> 8) & 0xff, blue:netHex & 0xff) // } // } extension UIColor { public convenience init(hex: UInt32, alpha: CGFloat = 1.0) { let red = CGFloat((hex & 0xFF0000) >> 16) / 255.0 let green = CGFloat((hex & 0x00FF00) >> 8 ) / 255.0 let blue = CGFloat((hex & 0x0000FF) ) / 255.0 self.init(red: red, green: green, blue: blue, alpha: alpha) } }
mit
576987a128f79ca9b7d36a346b5a185a
37.862069
119
0.573203
3.183616
false
false
false
false
wokalski/Graph.swift
Graph/Graph.swift
1
6503
/** Node is a building block of any `Graph`. */ public protocol Node: Hashable { var children: [Self] { get } } /** Graph defines basic directed graph. Instances of conforming can leverage basic Graph algorithms defined in the extension. */ public protocol Graph { associatedtype T : Node var nodes: [T] { get } } public extension Graph { /** Checks whether a graph contains a cycle. A cycle means that there is a parent-child relation where child is also a predecessor of the parent. - Complexity: O(N + E) where N is the number of all nodes, and E is the number of connections between them - returns: `true` if doesn't contain a cycle */ func isAcyclic() -> Bool { var isAcyclic = true depthSearch(edgeFound: { edge in isAcyclic = (edge.type() != .Back) return isAcyclic }, nodeStatusChanged: nil) return isAcyclic } /** Topological sort ([Wikipedia link](https://en.wikipedia.org/wiki/Topological_sorting)) is an ordering of graph's nodes such that for every directed edge u->v, u comes before v in the ordering. - Complexity: O(N + E) where N is the number of all nodes, and E is the number of connections between them - returns: Ordered array of nodes or nil if it cannot be done (i.e. the graph contains cycles) */ func topologicalSort() -> [T]? { var orderedVertices = [T]() var isAcyclic = true let nodeProcessed = { (nodeInfo: NodeInfo<T>) -> Bool in if nodeInfo.status == .Processed { orderedVertices.append(nodeInfo.node) } return true } depthSearch(edgeFound: { edge in isAcyclic = (edge.type() != .Back) return isAcyclic } , nodeStatusChanged: nodeProcessed) return isAcyclic ? orderedVertices : nil } /** Breadth First Search ([Wikipedia link](https://en.wikipedia.org/wiki/Breadth-first_search)) - Complexity: O(N + E) where N is the number of all nodes, and E is the number of connections between them - Parameter edgeFound: Called whenever a new connection between nodes is discovered - Parameter nodeStatusChanged: Called when a node changes its status. It is called twice for every node - Note: Search will stop if `false` is returned from any closure. - Warning: It will only call `nodeStatusChanged:` on tree edges because we don't maintain entry and exit times of nodes. More information about entry and exit times [here](https://courses.csail.mit.edu/6.006/fall11/rec/rec14.pdf). It is very easy to implement them, but might have big influence on memory use. */ func breadthSearch(edgeFound edgeFound: (Edge<T> -> Bool)?, nodeStatusChanged: (NodeInfo<T> -> Bool)?) { var queue = Queue<T>() var searchInfo = SearchInfo<T>() for graphRoot in nodes { if searchInfo.status(graphRoot) == .New { queue.enqueue(graphRoot) if updateNodeStatus(&searchInfo, node: graphRoot, status: .Discovered, nodeStatusChanged: nodeStatusChanged) == false { return } while queue.isEmpty() == false { let parent = queue.dequeue() for child in parent.children { if searchInfo.status(child) == .New { queue.enqueue(child) if updateNodeStatus(&searchInfo, node: child, status: .Discovered, nodeStatusChanged: nodeStatusChanged) == false { return } if let c = edgeFound?(Edge(from: searchInfo.nodeInfo(parent), to: searchInfo.nodeInfo(child))) where c == false { return } // Since we don't maintain entry and exit times, we can only rely on tree edges type. } } if updateNodeStatus(&searchInfo, node: parent, status: .Processed, nodeStatusChanged: nodeStatusChanged) == false { return } } } } } /** Depth First Search ([Wikipedia link](https://en.wikipedia.org/wiki/Depth-first_search)) - Complexity: O(N + E) where N is the number of all nodes, and E is the number of connections between them - Parameter edgeFound: Called whenever a new connection between nodes is discovered - Parameter nodeStatusChanged: Called when a node changes its status. It is called twice for every node - Note: Search will stop if `false` is returned from any closure. - Warning: This function makes recursive calls. Keep it in mind when operating on big data sets. */ func depthSearch(edgeFound edgeFound: (Edge<T> -> Bool)?, nodeStatusChanged: (NodeInfo<T> -> Bool)?) { var searchInfo = SearchInfo<T>() for node in nodes { if searchInfo.status(node) == .New { if dfsVisit(node, searchInfo: &searchInfo, edgeFound: edgeFound, nodeStatusChanged: nodeStatusChanged) == false { return } } } } private func updateNodeStatus(inout searchInfo: SearchInfo<T>, node: T, status: NodeStatus, nodeStatusChanged: (NodeInfo<T> -> Bool)?) -> Bool { searchInfo.set(node, status: status) guard let shouldContinue = nodeStatusChanged?(searchInfo.nodeInfo(node)) else { return true } return shouldContinue } private func dfsVisit(node: T, inout searchInfo: SearchInfo<T>, edgeFound: (Edge<T> -> Bool)?, nodeStatusChanged: (NodeInfo<T> -> Bool)?) -> Bool { if updateNodeStatus(&searchInfo, node: node, status: .Discovered, nodeStatusChanged: nodeStatusChanged) == false { return false } for child in node.children { if let c = edgeFound?(Edge(from: searchInfo.nodeInfo(node), to: searchInfo.nodeInfo(child))) where c == false { return false } if searchInfo.status(child) == .New { if dfsVisit(child, searchInfo: &searchInfo, edgeFound: edgeFound, nodeStatusChanged: nodeStatusChanged) == false { return false } } } if updateNodeStatus(&searchInfo, node: node, status: .Processed, nodeStatusChanged: nodeStatusChanged) == false { return false } return true } }
mit
1abfdbaade3986aace1213a340c7cc06
45.120567
314
0.611256
4.569923
false
false
false
false
NilStack/NilThemeKit
NilThemeKit/AppDelegate.swift
2
1410
// // AppDelegate.swift // NilThemeKit // // Created by Peng on 9/26/14. // Copyright (c) 2014 peng. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. window = UIWindow(frame: UIScreen.mainScreen().bounds) window?.backgroundColor = UIColor.whiteColor() NilThemeKit.setupTheme(primaryColor: NilThemeKit.color(r: 3.0, g: 169.0, b: 244.0), secondaryColor: UIColor.whiteColor(), fontname: "HelveticaNeue-Light", lightStatusBar:true) let mainVC: ViewController = ViewController() let navigationController: UINavigationController = UINavigationController(rootViewController: mainVC) mainVC.tabBarItem = UITabBarItem(tabBarSystemItem: UITabBarSystemItem.Favorites, tag: 0) navigationController.navigationBar.translucent = false let tabBarController: UITabBarController = UITabBarController() tabBarController.viewControllers = [navigationController] tabBarController.tabBar.translucent = false window?.rootViewController = tabBarController window?.makeKeyAndVisible() return true } }
mit
2b9730ec2d7f0f4f28cc632cc07d63c8
35.153846
183
0.719858
5.423077
false
false
false
false
tgsala/HackingWithSwift
project32/project32/AppDelegate.swift
1
3431
// // AppDelegate.swift // project32 // // Created by g5 on 3/21/16. // Copyright © 2016 tgsala. All rights reserved. // import UIKit import CoreSpotlight @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate, UISplitViewControllerDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. let splitViewController = self.window!.rootViewController as! UISplitViewController let navigationController = splitViewController.viewControllers[splitViewController.viewControllers.count-1] as! UINavigationController navigationController.topViewController!.navigationItem.leftBarButtonItem = splitViewController.displayModeButtonItem() splitViewController.delegate = self return true } func application(application: UIApplication, continueUserActivity userActivity: NSUserActivity, restorationHandler: ([AnyObject]?) -> Void) -> Bool { if userActivity.activityType == CSSearchableItemActionType { if let uniqueIdentifier = userActivity.userInfo?[CSSearchableItemActivityIdentifier] as? String { let splitViewController = self.window!.rootViewController as! UISplitViewController let navigationController = splitViewController.viewControllers[splitViewController.viewControllers.count-1] as! UINavigationController if let masterVC = navigationController.topViewController as? MasterViewController { masterVC.showTutorial(Int(uniqueIdentifier)!) } } } return true } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
unlicense
2a6cf49d876e1decfcf2376a0b16cccb
52.59375
285
0.744606
6.114082
false
false
false
false
invoy/CoreDataQueryInterface
CoreDataQueryInterfaceTests/NumericTypeTests.swift
1
4212
/* The MIT License (MIT) Copyright (c) 2015 Gregory Higley (Prosumma) 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. */ @testable import CoreDataQueryInterface import XCTest class NumericTypeTests: BaseTestCase { func testIntValueComparison() { let resultCount = try! managedObjectContext.from(TestEntity.self).filter({ $0.integer64 >= Int.max }).count() XCTAssert(resultCount == 1) } func testNSNumberValueComparison() { let intMax = Int.max as NSNumber let resultCount = try! managedObjectContext.from(TestEntity.self).filter({ $0.integer64 >= intMax }).count() XCTAssert(resultCount == 1) } func testInt16ValueComparison() { let int: Int16 = 32767 let resultCount = try! managedObjectContext.from(TestEntity.self).filter({ $0.integer16 == int }).count() XCTAssert(resultCount == 1) } func testUInt16ValueComparison() { let int: UInt16 = 32767 let resultCount = try! managedObjectContext.from(TestEntity.self).filter({ $0.integer16 == int }).count() XCTAssert(resultCount == 1) } func testUInt32ValueComparison() { let int: UInt32 = 32767 let resultCount = try! managedObjectContext.from(TestEntity.self).filter{ $0.integer16 == int }.count() XCTAssert(resultCount == 1) } func testUInt64ValueComparison() { let int: UInt64 = 32767 let resultCount = try! managedObjectContext.from(TestEntity.self).filter{ $0.integer16 == int }.count() XCTAssert(resultCount == 1) } func testInt16OverflowValueComparison() { let overflowCount = try! managedObjectContext.from(TestEntity.self).filter{ $0.integer16 == 500000000 }.count() XCTAssert(overflowCount == 0) } func testInt32ValueComparison() { let integer: Int32 = Int32.max let resultCount = try! managedObjectContext.from(TestEntity.self).filter({ $0.integer32 == integer }).count() XCTAssert(resultCount == 1) } func testInt64ValueComparison() { let integer: Int64 = Int64.max let resultCount = try! managedObjectContext.from(TestEntity.self).filter({ $0.integer64 == integer }).count() XCTAssert(resultCount == 1) } func testUIntInt32ValueComparison() { let integer: UInt = UInt(Int32.max) let resultCount = try! managedObjectContext.from(TestEntity.self).filter{ $0.integer32 == integer }.count() XCTAssert(resultCount == 1) } func testFloatValueComparison() { let float: Float = 510.2304 let resultCount = try! managedObjectContext.from(TestEntity.self).filter{ $0.float == float }.count() XCTAssert(resultCount == 1) } func testIntDoubleValueComparison() { let intValue: Int = 212309 let resultCount = try! managedObjectContext.from(TestEntity.self).filter{ $0.double == intValue }.count() XCTAssert(resultCount == 1) } func testDecimalValueComparison() { let double: Double = 5.0 let resultCount = try! managedObjectContext.from(TestEntity.self).filter{ $0.decimal == double }.count() XCTAssert(resultCount == 1) } }
mit
60a94733ec5c567e0a037d01322024ef
38.735849
119
0.687085
4.509636
false
true
false
false
VladislavJevremovic/WebcamViewer
WebcamViewer/Common/System/Processes/WindowSetupStartupProcess.swift
1
778
// // Copyright © 2019 Vladislav Jevremović. All rights reserved. // import UIKit internal final class WindowSetupStartupProcess: StartupProcess { let scene: UIScene let localStore: LocalStore let completion: (UIWindow) -> Void init(scene: UIScene, localStore: LocalStore, completion: @escaping (UIWindow) -> Void) { self.scene = scene self.localStore = localStore self.completion = completion } func run(completion: @escaping (Bool) -> Void) { guard let windowScene = (scene as? UIWindowScene) else { return } let window = UIWindow(windowScene: windowScene) window.rootViewController = ViewerViewController(localStore: localStore, delegate: nil) window.makeKeyAndVisible() self.completion(window) completion(true) } }
mit
8073eedc4cfe7837a69cb8f281b802d2
26.714286
91
0.722938
4.263736
false
false
false
false
lYcHeeM/ZJImageBrowser
ZJImageBrowser/ZJImageBrowser/ZJImageBrowser.swift
1
21528
// // ZJImageBrowser.swift // // Created by luozhijun on 2017/7/5. // Copyright © 2017年 RickLuo. All rights reserved. // import UIKit import Photos internal func bundleImage(named: String) -> UIImage? { var path = "ZJImageBrowser.bundle" + "/\(named)" if let image = UIImage(named: path) { return image } else { path = "Frameworks/ZJImageBrowser.framework/" + path return UIImage(named: path) } } /// An simple full screen photo browser based on UICollectionView. open class ZJImageBrowser: UICollectionView { open static var buttonHorizontalPadding: CGFloat = 20 open static var buttonVerticalPadding : CGFloat = 35 open static var buttonHeight : CGFloat = 27 open static var pageSpacing : CGFloat = 10 open static var maximumZoomScale: CGFloat = 3 open static var albumAuthorizingFailedHint = "Saving failed! Can't access your ablum, check in \"Settings\"->\"Privacy\"->\"Photos\"." open static var imageSavingSucceedHint = "Saving succeed" open static var imageSavingFailedHint = "Saving failed!" open static var retryButtonTitle = "Downloading failed, Tap to retry" open static var saveActionTitle = "Save to Album" open static var copyToPastboardActionTitle = "Copy to pastboard" open static var imageHavenotBeenDownloadedFromIcloudHint = "Photo cannot been downloaded from iCloud." open static var showsDebugHud = false fileprivate var isShowing = false fileprivate var saveButton = UIButton(type: .system) fileprivate var deleteButton = UIButton(type: .system) fileprivate var pageIndexLabel = UILabel() fileprivate var innerCurrentIndex = 0 { didSet { if imageWrappers.count > 0 { pageIndexLabel.text = "\(innerCurrentIndex + 1)/\(imageWrappers.count)" } else { pageIndexLabel.text = nil } } } fileprivate weak var hud: ZJImageBrowserHUD? open var imageWrappers = [ZJImageWrapper]() { didSet { reloadData() } } open var currentIndex: Int { return innerCurrentIndex } open var containerRect: CGRect = UIScreen.main.bounds { didSet { let pageSpacing: CGFloat = ZJImageBrowser.pageSpacing frame = CGRect(x: containerRect.minX, y: containerRect.minY, width: containerRect.width + pageSpacing, height: containerRect.height) if let layout = collectionViewLayout as? UICollectionViewFlowLayout { layout.itemSize = CGSize(width: containerRect.width + pageSpacing, height: containerRect.height) collectionViewLayout = layout } } } override open var isScrollEnabled: Bool { didSet { needsPageIndex = isScrollEnabled let tempValue = isScrollEnabled super.isScrollEnabled = tempValue } } open var needsPageIndex: Bool = true { didSet { pageIndexLabel.isHidden = !needsPageIndex } } open var needsSaveButton: Bool = true { didSet { saveButton.isHidden = !needsSaveButton } } open var needsDeleteButton: Bool = false { didSet { deleteButton.isHidden = !needsDeleteButton } } /// Default is true. trun off it if you want use loacl HUD. /// 默认打开, 如果想用项目本地的hud提示异常, 请置为false open var usesInternalHUD = true open var shrinkingAnimated = true open var imageViewSingleTapped : ((ZJImageBrowser, Int, UIImage?) -> Swift.Void)? open var deleteActionAt : ((ZJImageBrowser, Int, UIImage?) -> Swift.Void)? open var albumAuthorizingFailed: ((ZJImageBrowser, PHAuthorizationStatus) -> Swift.Void)? open var photoSavingFailed : ((ZJImageBrowser, UIImage) -> Swift.Void)? /// 注意: 此闭包将不在主线程执行 /// Note: this closure excutes in the global queue. open var imageQueryingFinished : ((ZJImageBrowser, Bool, UIImage?) -> Swift.Void)? required public init(imageWrappers: [ZJImageWrapper], initialIndex: Int = 0, containerRect: CGRect = UIScreen.main.bounds) { let layout = UICollectionViewFlowLayout() self.containerRect = containerRect // 每个item, 除了实际内容, 尾部再加一段空白间隙, 以实现和ScrollView一样的翻页效果. // 意识到设置minimumLineSpacing = 10, 并增加collectionView相同的宽度, // 似乎也能达到这个效果, 但由于最后一页尾部不存在lineSpacing, collectionView的contentSize将无法完全展示最后一页, 即最后一页末尾10距离的内容将不能显示. // By default, UICollectionViewFlowLayout's minimumLineSpacing is 10.0, when collectionView's item is horizontally filled (itemSize.width = collectionView.bounds.width) and collectionView is paging enabled, greater than zero 'minimumLineSpacing' will cause an unintended performance: start from second page, every page has a gap which will be accumulated by page number. // It seems that we can expand collectionView's width by 'minimumLineSpacing' to fix this problem. But pratice negates this solution: When there are tow pages or more, collectionView will not give the last one a 'lineSpacing', so it's 'contentSize' is not enough to show this page's content completely, which means if the 'minimumLineSpacing' were 10.0, the last page's end would overstep the collectionView's contentSize by 10.0. // Finally, I use the following simple solution to insert a margin between every item (like UIScrollView's preformance): Expand every collectionViewItem's width by a fixed value 'pageSpacing' (such as 10.0), and expand the collectionView's width by the same value, too. And don't forget that, when layout collevtionViewCell's subviews, there's an additional spacing which is not for diplaying the real content. let pageSpacing: CGFloat = ZJImageBrowser.pageSpacing layout.itemSize = CGSize(width: containerRect.width + pageSpacing, height: containerRect.height) layout.scrollDirection = .horizontal layout.minimumInteritemSpacing = 0 layout.minimumLineSpacing = 0 super.init(frame: CGRect(x: containerRect.minX, y: containerRect.minY, width: containerRect.width + pageSpacing, height: containerRect.height), collectionViewLayout: layout) self.imageWrappers = imageWrappers if initialIndex >= 0 && initialIndex < imageWrappers.count { self.innerCurrentIndex = initialIndex } isPagingEnabled = true dataSource = self delegate = self showsHorizontalScrollIndicator = false register(ZJImageCell.self, forCellWithReuseIdentifier: ZJImageCell.reuseIdentifier) setupSaveButton() setupDeleteButton() setupPageIndexLabel() } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } } //MARK: - Setup UI extension ZJImageBrowser { override open func layoutSubviews() { super.layoutSubviews() saveButton.frame.origin = CGPoint(x: frame.width - ZJImageBrowser.buttonHorizontalPadding - 10 - saveButton.bounds.width, y: frame.height - ZJImageBrowser.buttonHeight - ZJImageBrowser.buttonVerticalPadding) var deleteButtonX = saveButton.frame.minX - 10 - deleteButton.bounds.width if needsSaveButton == false { deleteButtonX = saveButton.frame.origin.x } deleteButton.center.y = saveButton.center.y deleteButton.frame.origin.x = deleteButtonX } fileprivate func setupSaveButton() { saveButton.setImage(bundleImage(named: "icon_save")?.withRenderingMode(.alwaysOriginal), for: .normal) saveButton.sizeToFit() saveButton.addTarget(self, action: #selector(saveButtonClicked), for: .touchUpInside) } fileprivate func setupDeleteButton() { deleteButton.setImage(bundleImage(named: "icon_delete")?.withRenderingMode(.alwaysOriginal), for: .normal) deleteButton.sizeToFit() deleteButton.addTarget(self, action: #selector(deleteButtonClicked), for: .touchUpInside) } fileprivate func setupPageIndexLabel() { pageIndexLabel.font = UIFont.boldSystemFont(ofSize: 20) pageIndexLabel.textColor = .white pageIndexLabel.textAlignment = .center pageIndexLabel.frame.size = CGSize(width: 60, height: 27) pageIndexLabel.center = CGPoint(x: UIScreen.main.bounds.width/2, y: 30) pageIndexLabel.text = "\(innerCurrentIndex + 1)/\(imageWrappers.count)" } } //MARK: - Show & Hide extension ZJImageBrowser { open func show(inView view: UIView? = nil, animated: Bool = true, enlargingAnimated: Bool = true, at index: Int? = nil) { guard let _superview = view == nil ? UIApplication.shared.keyWindow : view else { return } guard isShowing == false else { return } _superview.addSubview(self) _superview.addSubview(saveButton) _superview.addSubview(deleteButton) _superview.addSubview(pageIndexLabel) saveButton.isHidden = !needsSaveButton deleteButton.isHidden = !needsDeleteButton if let index = index, index >= 0, index < imageWrappers.count { innerCurrentIndex = index } scrollToItem(at: IndexPath(item: innerCurrentIndex, section: 0), at: .centeredHorizontally, animated: false) let currentImageWrapper = imageWrappers[innerCurrentIndex] guard enlargingAnimated, let enlargingView = currentImageWrapper.imageContainer, let enlargingImage = currentImageWrapper.placeholderImage else { animate(animated: animated) return } let enlargingViewOriginalFrame = enlargingView.frame let enlargingAnimationStartFrame = enlargingView.convert(enlargingView.bounds, to: _superview) let tempImageView = UIImageView() tempImageView.frame = enlargingAnimationStartFrame tempImageView.image = currentImageWrapper.placeholderImage tempImageView.contentMode = .scaleAspectFill tempImageView.clipsToBounds = true enlargingView.isHidden = true _superview.addSubview(tempImageView) // 使enlargingViewEndFrame的宽度和屏慕宽度保持一致, 宽高比和图片的宽高比一致 // Make enlargingViewEndFrame's width equals to screen width, and its aspect ratio the same as its inner image; var enlargingAnimationEndFrame = CGRect.zero enlargingAnimationEndFrame.size.width = _superview.frame.width enlargingAnimationEndFrame.size.height = _superview.frame.width * (enlargingImage.size.height/enlargingImage.size.width) enlargingAnimationEndFrame.origin = CGPoint(x: 0, y: (_superview.frame.height - enlargingAnimationEndFrame.height)/2) animate(withMirroredImageView: tempImageView, enlargingView: enlargingView, originalFrame: enlargingViewOriginalFrame, animationEndFrame: enlargingAnimationEndFrame, animated: true) } fileprivate func animate(withMirroredImageView mirroredImageView: UIImageView? = nil, enlargingView: UIView? = nil, originalFrame: CGRect = .zero, animationEndFrame: CGRect = .zero, animated: Bool) { if animated { if enlargingView != nil { isHidden = true } alpha = 0 saveButton.alpha = 0 deleteButton.alpha = 0 pageIndexLabel.alpha = 0 UIView.animate(withDuration: 0.25, animations: { self.alpha = 1 self.saveButton.alpha = 1 self.deleteButton.alpha = 1 self.pageIndexLabel.alpha = 1 if let mirroredImageView = mirroredImageView { mirroredImageView.frame = animationEndFrame } else if let enlargingView = enlargingView { enlargingView.frame = animationEndFrame } }, completion: { (_) in self.isHidden = false enlargingView?.isHidden = false mirroredImageView?.removeFromSuperview() self.isShowing = true }) } else { // 思考为何要取消隐藏入口view。因为如果不取消,图片浏览器弹出后切换到其他图片,则入口view会一直隐藏,除非重新切回入口view再单击关闭图片浏览器,这样入口view才能被取消隐藏。 enlargingView?.isHidden = false isShowing = true } } open func dismiss(animated: Bool = true, shrinkingAnimated: Bool = true , force: Bool = false, completion: (() -> Swift.Void)? = nil) { if !isShowing && !force { return } if animated { var shrinkingView : UIView? var mirroredImageView : UIImageView! var shrinkingAnimationEndFrame = CGRect.zero if shrinkingAnimated, let _shrinkingView = imageWrappers[innerCurrentIndex].imageContainer, let _superview = superview, let photoCell = visibleCells.first as? ZJImageCell { let rect = _shrinkingView.convert(_shrinkingView.bounds, to: _superview) if _superview.bounds.intersects(rect) { shrinkingAnimationEndFrame = rect shrinkingView = _shrinkingView shrinkingView?.isHidden = true mirroredImageView = UIImageView() _superview.addSubview(mirroredImageView) mirroredImageView.frame = photoCell.imageContainer.frame mirroredImageView.image = photoCell.image != nil ? photoCell.image : imageWrappers[innerCurrentIndex].placeholderImage mirroredImageView.contentMode = .scaleAspectFill mirroredImageView.clipsToBounds = true removeFromSuperview() saveButton.isHidden = true } } UIView.animate(withDuration: 0.25, animations: { self.alpha = 0 self.saveButton.alpha = 0 self.deleteButton.alpha = 0 self.pageIndexLabel.alpha = 0 mirroredImageView?.frame = shrinkingAnimationEndFrame }, completion: { (_) in self.pageIndexLabel.removeFromSuperview() self.saveButton.removeFromSuperview() self.deleteButton.removeFromSuperview() self.removeFromSuperview() self.alpha = 1 self.saveButton.alpha = 1 self.deleteButton.alpha = 1 self.pageIndexLabel.alpha = 1 self.isShowing = false shrinkingView?.isHidden = false mirroredImageView?.removeFromSuperview() completion?() }) } else { pageIndexLabel.removeFromSuperview() saveButton.removeFromSuperview() removeFromSuperview() isShowing = false completion?() } } } //MARK: - Handle Events extension ZJImageBrowser { @objc fileprivate func saveButtonClicked() { let saveAction = { if self.visibleCells.count == 1, let photoCell = self.visibleCells.first as? ZJImageCell, let image = photoCell.image { UIImageWriteToSavedPhotosAlbum(image, self, #selector(self.image(_:didFinishSavingWithError:contextInfo:)), nil) } } let status = PHPhotoLibrary.authorizationStatus() if status == .restricted || status == .denied { albumAuthorizingFailed?(self, status) guard usesInternalHUD else { return } ZJImageBrowserHUD.show(message: ZJImageBrowser.albumAuthorizingFailedHint, inView: self, needsIndicator: false, hideAfter: 2.5) } else if status == .notDetermined { PHPhotoLibrary.requestAuthorization({ (status) in DispatchQueue.main.async { if status != .authorized { if self.usesInternalHUD { ZJImageBrowserHUD.show(message: ZJImageBrowser.albumAuthorizingFailedHint, inView: self, needsIndicator: false, hideAfter: 2.5) } } else { saveAction() } } }) } else { saveAction() } } @objc fileprivate func image(_ image: UIImage, didFinishSavingWithError error: NSError?, contextInfo: Any?) { photoSavingFailed?(self, image) guard usesInternalHUD else { return } var alertMessage = "" if error == nil { alertMessage = ZJImageBrowser.imageSavingSucceedHint } else { alertMessage = ZJImageBrowser.imageSavingFailedHint } hud?.hide(animated: false) ZJImageBrowserHUD.show(message: alertMessage, inView: self, needsIndicator: false) } @objc fileprivate func deleteButtonClicked() { var image: UIImage? if visibleCells.count == 1, let photoCell = visibleCells.first as? ZJImageCell { image = photoCell.image } if imageWrappers.count <= 1 { dismiss() imageWrappers.remove(at: innerCurrentIndex) deleteActionAt?(self, innerCurrentIndex, image) innerCurrentIndex = 0 return } performBatchUpdates({ self.imageWrappers.remove(at: self.innerCurrentIndex) self.deleteItems(at: [IndexPath(item: self.innerCurrentIndex, section: 0)]) self.deleteActionAt?(self, self.innerCurrentIndex, image) if let currentIndexPath = self.indexPathsForVisibleItems.first { self.innerCurrentIndex = currentIndexPath.item // 发现currentIndexPath更新不及时, 快速删除多张图片时, 可能还停留在上一个item, 可能与deleteItems带动画效果有关, 此处加一个判断, 防止越界. if self.innerCurrentIndex >= self.imageWrappers.count { self.innerCurrentIndex = self.imageWrappers.count - 1 } } else { self.innerCurrentIndex -= 1 } }, completion: { _ in }) } } //MARK: - UICollectionViewDataSource & UICollectionViewDelegate extension ZJImageBrowser: UICollectionViewDelegate, UICollectionViewDataSource { public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return imageWrappers.count } public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: ZJImageCell.reuseIdentifier, for: indexPath) as! ZJImageCell cell.setImage(with: imageWrappers[indexPath.item]) weak var weakCell = cell cell.singleTapped = { [weak self] _ in guard self != nil, let strongCell = weakCell else { return } if let closure = self?.imageViewSingleTapped { closure(self!, indexPath.item, strongCell.imageContainer.image) } else { self!.dismiss(shrinkingAnimated: self!.shrinkingAnimated) } } cell.imageQueryingFinished = { [weak self] (succeed, image) in guard self != nil else { return } self?.imageQueryingFinished?(self!, succeed, image) } cell.imageDragedDistanceChanged = { [weak self] (_cell, dragedDistanceRatio) in guard let `self` = self else { return } let imageViewBeneathBrowser = self.imageWrappers[self.innerCurrentIndex].imageContainer imageViewBeneathBrowser?.isHidden = true self.layer.backgroundColor = self.backgroundColor?.withAlphaComponent(1 - dragedDistanceRatio).cgColor } cell.imageDragingEnd = { [weak self] (_cell, shouldDismiss) in guard let `self` = self else { return } if shouldDismiss { self.dismiss() } else { UIView.animate(withDuration: 0.25, animations: { self.layer.backgroundColor = UIColor.black.cgColor }, completion: { _ in let imageViewBeneathBrowser = self.imageWrappers[self.innerCurrentIndex].imageContainer imageViewBeneathBrowser?.isHidden = false }) } } return cell } public func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) { guard let flowLayout = collectionViewLayout as? UICollectionViewFlowLayout else { return } let currentPage = Int(scrollView.contentOffset.x / flowLayout.itemSize.width) innerCurrentIndex = currentPage } }
mit
90b61ec937e7a40125e50b5f05b1015b
47.675174
438
0.633729
5.061279
false
false
false
false
JmoVxia/CLPlayer
Base/CLTabBarController/CLTabBarController.swift
1
4738
// // CLTabBarController.swift // CLPlayer // // Created by Chen JmoVxia on 2021/10/25. // import UIKit // MARK: - JmoVxia---类-属性 class CLTabBarController: UITabBarController { override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) } @available(*, unavailable) required init?(coder _: NSCoder) { fatalError("init(coder:) has not been implemented") } deinit {} } // MARK: - JmoVxia---生命周期 extension CLTabBarController { override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) } override func viewDidLoad() { super.viewDidLoad() initUI() makeConstraints() initData() } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) } override func viewDidDisappear(_ animated: Bool) { super.viewDidDisappear(animated) } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() } } // MARK: - JmoVxia---布局 private extension CLTabBarController { func initUI() { view.backgroundColor = .white UITabBar.appearance().unselectedItemTintColor = .hex("#999999") UITabBar.appearance().tintColor = .hex("#24C065") addChild(child: CLHomeController(), title: "Home", image: UIImage(named: "homeNormal"), selectedImage: UIImage(named: "homeSelected")) addChild(child: CLMoreController(), title: "More", image: UIImage(named: "meNormal"), selectedImage: UIImage(named: "meSelected")) } func makeConstraints() {} } // MARK: - JmoVxia---数据 private extension CLTabBarController { func initData() {} } // MARK: - JmoVxia---override extension CLTabBarController { // 是否支持自动转屏 override var shouldAutorotate: Bool { guard let navigationController = selectedViewController as? UINavigationController else { return selectedViewController?.shouldAutorotate ?? false } return navigationController.topViewController?.shouldAutorotate ?? false } // 支持哪些屏幕方向 override var supportedInterfaceOrientations: UIInterfaceOrientationMask { guard let navigationController = selectedViewController as? UINavigationController else { return selectedViewController?.supportedInterfaceOrientations ?? .portrait } return navigationController.topViewController?.supportedInterfaceOrientations ?? .portrait } // 默认的屏幕方向(当前ViewController必须是通过模态出来的UIViewController(模态带导航的无效)方式展现出来的,才会调用这个方法) override var preferredInterfaceOrientationForPresentation: UIInterfaceOrientation { guard let navigationController = selectedViewController as? UINavigationController else { return selectedViewController?.preferredInterfaceOrientationForPresentation ?? .portrait } return navigationController.topViewController?.preferredInterfaceOrientationForPresentation ?? .portrait } /// 状态栏样式 override var preferredStatusBarStyle: UIStatusBarStyle { guard let navigationController = selectedViewController as? UINavigationController else { return selectedViewController?.preferredStatusBarStyle ?? .default } return navigationController.topViewController?.preferredStatusBarStyle ?? .default } /// 是否隐藏状态栏 override var prefersStatusBarHidden: Bool { guard let navigationController = selectedViewController as? UINavigationController else { return selectedViewController?.prefersStatusBarHidden ?? false } return navigationController.topViewController?.prefersStatusBarHidden ?? false } } // MARK: - JmoVxia---objc @objc private extension CLTabBarController {} // MARK: - JmoVxia---私有方法 private extension CLTabBarController { func addChild(child: UIViewController, title: String, image: UIImage?, selectedImage: UIImage?) { child.title = title child.tabBarItem.setTitleTextAttributes([.font: UIFont.systemFont(ofSize: 11)], for: .normal) child.tabBarItem.setTitleTextAttributes([.font: UIFont.boldSystemFont(ofSize: 11)], for: .selected) child.tabBarItem.image = image?.withRenderingMode(.alwaysOriginal) child.tabBarItem.selectedImage = selectedImage?.withRenderingMode(.alwaysOriginal) let navController = CLNavigationController(rootViewController: child) addChild(navController) } } // MARK: - JmoVxia---公共方法 extension CLTabBarController {}
mit
f133acb9340c42f3ebf99cadcb7b277c
34
188
0.724835
5.321637
false
false
false
false
zach-freeman/swift-localview
ThirdPartyLib/Alamofire/Source/SessionManager.swift
2
38297
// // SessionManager.swift // // Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/) // // 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 /// Responsible for creating and managing `Request` objects, as well as their underlying `NSURLSession`. open class SessionManager { // MARK: - Helper Types /// Defines whether the `MultipartFormData` encoding was successful and contains result of the encoding as /// associated values. /// /// - Success: Represents a successful `MultipartFormData` encoding and contains the new `UploadRequest` along with /// streaming information. /// - Failure: Used to represent a failure in the `MultipartFormData` encoding and also contains the encoding /// error. public enum MultipartFormDataEncodingResult { case success(request: UploadRequest, streamingFromDisk: Bool, streamFileURL: URL?) case failure(Error) } // MARK: - Properties /// A default instance of `SessionManager`, used by top-level Alamofire request methods, and suitable for use /// directly for any ad hoc requests. public static let `default`: SessionManager = { let configuration = URLSessionConfiguration.default configuration.httpAdditionalHeaders = SessionManager.defaultHTTPHeaders return SessionManager(configuration: configuration) }() /// Creates default values for the "Accept-Encoding", "Accept-Language" and "User-Agent" headers. public static let defaultHTTPHeaders: HTTPHeaders = { // Accept-Encoding HTTP Header; see https://tools.ietf.org/html/rfc7230#section-4.2.3 let acceptEncoding: String = "gzip;q=1.0, compress;q=0.5" // Accept-Language HTTP Header; see https://tools.ietf.org/html/rfc7231#section-5.3.5 let acceptLanguage = Locale.preferredLanguages.prefix(6).enumerated().map { index, languageCode in let quality = 1.0 - (Double(index) * 0.1) return "\(languageCode);q=\(quality)" }.joined(separator: ", ") // User-Agent Header; see https://tools.ietf.org/html/rfc7231#section-5.5.3 // Example: `iOS Example/1.0 (org.alamofire.iOS-Example; build:1; iOS 10.0.0) Alamofire/4.0.0` let userAgent: String = { if let info = Bundle.main.infoDictionary { let executable = info[kCFBundleExecutableKey as String] as? String ?? "Unknown" let bundle = info[kCFBundleIdentifierKey as String] as? String ?? "Unknown" let appVersion = info["CFBundleShortVersionString"] as? String ?? "Unknown" let appBuild = info[kCFBundleVersionKey as String] as? String ?? "Unknown" let osNameVersion: String = { let version = ProcessInfo.processInfo.operatingSystemVersion let versionString = "\(version.majorVersion).\(version.minorVersion).\(version.patchVersion)" let osName: String = { #if os(iOS) return "iOS" #elseif os(watchOS) return "watchOS" #elseif os(tvOS) return "tvOS" #elseif os(macOS) return "OS X" #elseif os(Linux) return "Linux" #else return "Unknown" #endif }() return "\(osName) \(versionString)" }() let alamofireVersion: String = { guard let afInfo = Bundle(for: SessionManager.self).infoDictionary, let build = afInfo["CFBundleShortVersionString"] else { return "Unknown" } return "Alamofire/\(build)" }() return "\(executable)/\(appVersion) (\(bundle); build:\(appBuild); \(osNameVersion)) \(alamofireVersion)" } return "Alamofire" }() return [ "Accept-Encoding": acceptEncoding, "Accept-Language": acceptLanguage, "User-Agent": userAgent ] }() /// Default memory threshold used when encoding `MultipartFormData` in bytes. public static let multipartFormDataEncodingMemoryThreshold: UInt64 = 10_000_000 /// The underlying session. public let session: URLSession /// The session delegate handling all the task and session delegate callbacks. public let delegate: SessionDelegate /// Whether to start requests immediately after being constructed. `true` by default. open var startRequestsImmediately: Bool = true /// The request adapter called each time a new request is created. open var adapter: RequestAdapter? /// The request retrier called each time a request encounters an error to determine whether to retry the request. open var retrier: RequestRetrier? { get { return delegate.retrier } set { delegate.retrier = newValue } } /// The background completion handler closure provided by the UIApplicationDelegate /// `application:handleEventsForBackgroundURLSession:completionHandler:` method. By setting the background /// completion handler, the SessionDelegate `sessionDidFinishEventsForBackgroundURLSession` closure implementation /// will automatically call the handler. /// /// If you need to handle your own events before the handler is called, then you need to override the /// SessionDelegate `sessionDidFinishEventsForBackgroundURLSession` and manually call the handler when finished. /// /// `nil` by default. open var backgroundCompletionHandler: (() -> Void)? let queue = DispatchQueue(label: "org.alamofire.session-manager." + UUID().uuidString) // MARK: - Lifecycle /// Creates an instance with the specified `configuration`, `delegate` and `serverTrustPolicyManager`. /// /// - parameter configuration: The configuration used to construct the managed session. /// `URLSessionConfiguration.default` by default. /// - parameter delegate: The delegate used when initializing the session. `SessionDelegate()` by /// default. /// - parameter serverTrustPolicyManager: The server trust policy manager to use for evaluating all server trust /// challenges. `nil` by default. /// /// - returns: The new `SessionManager` instance. public init( configuration: URLSessionConfiguration = URLSessionConfiguration.default, delegate: SessionDelegate = SessionDelegate(), serverTrustPolicyManager: ServerTrustPolicyManager? = nil) { self.delegate = delegate self.session = URLSession(configuration: configuration, delegate: delegate, delegateQueue: nil) commonInit(serverTrustPolicyManager: serverTrustPolicyManager) } /// Creates an instance with the specified `session`, `delegate` and `serverTrustPolicyManager`. /// /// - parameter session: The URL session. /// - parameter delegate: The delegate of the URL session. Must equal the URL session's delegate. /// - parameter serverTrustPolicyManager: The server trust policy manager to use for evaluating all server trust /// challenges. `nil` by default. /// /// - returns: The new `SessionManager` instance if the URL session's delegate matches; `nil` otherwise. public init?( session: URLSession, delegate: SessionDelegate, serverTrustPolicyManager: ServerTrustPolicyManager? = nil) { guard delegate === session.delegate else { return nil } self.delegate = delegate self.session = session commonInit(serverTrustPolicyManager: serverTrustPolicyManager) } private func commonInit(serverTrustPolicyManager: ServerTrustPolicyManager?) { session.serverTrustPolicyManager = serverTrustPolicyManager delegate.sessionManager = self delegate.sessionDidFinishEventsForBackgroundURLSession = { [weak self] session in guard let strongSelf = self else { return } DispatchQueue.main.async { strongSelf.backgroundCompletionHandler?() } } } deinit { session.invalidateAndCancel() } // MARK: - Data Request /// Creates a `DataRequest` to retrieve the contents of the specified `url`, `method`, `parameters`, `encoding` /// and `headers`. /// /// - parameter url: The URL. /// - parameter method: The HTTP method. `.get` by default. /// - parameter parameters: The parameters. `nil` by default. /// - parameter encoding: The parameter encoding. `URLEncoding.default` by default. /// - parameter headers: The HTTP headers. `nil` by default. /// /// - returns: The created `DataRequest`. @discardableResult open func request( _ url: URLConvertible, method: HTTPMethod = .get, parameters: Parameters? = nil, encoding: ParameterEncoding = URLEncoding.default, headers: HTTPHeaders? = nil) -> DataRequest { var originalRequest: URLRequest? do { originalRequest = try URLRequest(url: url, method: method, headers: headers) let encodedURLRequest = try encoding.encode(originalRequest!, with: parameters) return request(encodedURLRequest) } catch { return request(originalRequest, failedWith: error) } } /// Creates a `DataRequest` to retrieve the contents of a URL based on the specified `urlRequest`. /// /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. /// /// - parameter urlRequest: The URL request. /// /// - returns: The created `DataRequest`. @discardableResult open func request(_ urlRequest: URLRequestConvertible) -> DataRequest { var originalRequest: URLRequest? do { originalRequest = try urlRequest.asURLRequest() let originalTask = DataRequest.Requestable(urlRequest: originalRequest!) let task = try originalTask.task(session: session, adapter: adapter, queue: queue) let request = DataRequest(session: session, requestTask: .data(originalTask, task)) delegate[task] = request if startRequestsImmediately { request.resume() } return request } catch { return request(originalRequest, failedWith: error) } } // MARK: Private - Request Implementation private func request(_ urlRequest: URLRequest?, failedWith error: Error) -> DataRequest { var requestTask: Request.RequestTask = .data(nil, nil) if let urlRequest = urlRequest { let originalTask = DataRequest.Requestable(urlRequest: urlRequest) requestTask = .data(originalTask, nil) } let underlyingError = error.underlyingAdaptError ?? error let request = DataRequest(session: session, requestTask: requestTask, error: underlyingError) if let retrier = retrier, error is AdaptError { allowRetrier(retrier, toRetry: request, with: underlyingError) } else { if startRequestsImmediately { request.resume() } } return request } // MARK: - Download Request // MARK: URL Request /// Creates a `DownloadRequest` to retrieve the contents the specified `url`, `method`, `parameters`, `encoding`, /// `headers` and save them to the `destination`. /// /// If `destination` is not specified, the contents will remain in the temporary location determined by the /// underlying URL session. /// /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. /// /// - parameter url: The URL. /// - parameter method: The HTTP method. `.get` by default. /// - parameter parameters: The parameters. `nil` by default. /// - parameter encoding: The parameter encoding. `URLEncoding.default` by default. /// - parameter headers: The HTTP headers. `nil` by default. /// - parameter destination: The closure used to determine the destination of the downloaded file. `nil` by default. /// /// - returns: The created `DownloadRequest`. @discardableResult open func download( _ url: URLConvertible, method: HTTPMethod = .get, parameters: Parameters? = nil, encoding: ParameterEncoding = URLEncoding.default, headers: HTTPHeaders? = nil, to destination: DownloadRequest.DownloadFileDestination? = nil) -> DownloadRequest { do { let urlRequest = try URLRequest(url: url, method: method, headers: headers) let encodedURLRequest = try encoding.encode(urlRequest, with: parameters) return download(encodedURLRequest, to: destination) } catch { return download(nil, to: destination, failedWith: error) } } /// Creates a `DownloadRequest` to retrieve the contents of a URL based on the specified `urlRequest` and save /// them to the `destination`. /// /// If `destination` is not specified, the contents will remain in the temporary location determined by the /// underlying URL session. /// /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. /// /// - parameter urlRequest: The URL request /// - parameter destination: The closure used to determine the destination of the downloaded file. `nil` by default. /// /// - returns: The created `DownloadRequest`. @discardableResult open func download( _ urlRequest: URLRequestConvertible, to destination: DownloadRequest.DownloadFileDestination? = nil) -> DownloadRequest { do { let urlRequest = try urlRequest.asURLRequest() return download(.request(urlRequest), to: destination) } catch { return download(nil, to: destination, failedWith: error) } } // MARK: Resume Data /// Creates a `DownloadRequest` from the `resumeData` produced from a previous request cancellation to retrieve /// the contents of the original request and save them to the `destination`. /// /// If `destination` is not specified, the contents will remain in the temporary location determined by the /// underlying URL session. /// /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. /// /// On the latest release of all the Apple platforms (iOS 10, macOS 10.12, tvOS 10, watchOS 3), `resumeData` is broken /// on background URL session configurations. There's an underlying bug in the `resumeData` generation logic where the /// data is written incorrectly and will always fail to resume the download. For more information about the bug and /// possible workarounds, please refer to the following Stack Overflow post: /// /// - http://stackoverflow.com/a/39347461/1342462 /// /// - parameter resumeData: The resume data. This is an opaque data blob produced by `URLSessionDownloadTask` /// when a task is cancelled. See `URLSession -downloadTask(withResumeData:)` for /// additional information. /// - parameter destination: The closure used to determine the destination of the downloaded file. `nil` by default. /// /// - returns: The created `DownloadRequest`. @discardableResult open func download( resumingWith resumeData: Data, to destination: DownloadRequest.DownloadFileDestination? = nil) -> DownloadRequest { return download(.resumeData(resumeData), to: destination) } // MARK: Private - Download Implementation private func download( _ downloadable: DownloadRequest.Downloadable, to destination: DownloadRequest.DownloadFileDestination?) -> DownloadRequest { do { let task = try downloadable.task(session: session, adapter: adapter, queue: queue) let download = DownloadRequest(session: session, requestTask: .download(downloadable, task)) download.downloadDelegate.destination = destination delegate[task] = download if startRequestsImmediately { download.resume() } return download } catch { return download(downloadable, to: destination, failedWith: error) } } private func download( _ downloadable: DownloadRequest.Downloadable?, to destination: DownloadRequest.DownloadFileDestination?, failedWith error: Error) -> DownloadRequest { var downloadTask: Request.RequestTask = .download(nil, nil) if let downloadable = downloadable { downloadTask = .download(downloadable, nil) } let underlyingError = error.underlyingAdaptError ?? error let download = DownloadRequest(session: session, requestTask: downloadTask, error: underlyingError) download.downloadDelegate.destination = destination if let retrier = retrier, error is AdaptError { allowRetrier(retrier, toRetry: download, with: underlyingError) } else { if startRequestsImmediately { download.resume() } } return download } // MARK: - Upload Request // MARK: File /// Creates an `UploadRequest` from the specified `url`, `method` and `headers` for uploading the `file`. /// /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. /// /// - parameter file: The file to upload. /// - parameter url: The URL. /// - parameter method: The HTTP method. `.post` by default. /// - parameter headers: The HTTP headers. `nil` by default. /// /// - returns: The created `UploadRequest`. @discardableResult open func upload( _ fileURL: URL, to url: URLConvertible, method: HTTPMethod = .post, headers: HTTPHeaders? = nil) -> UploadRequest { do { let urlRequest = try URLRequest(url: url, method: method, headers: headers) return upload(fileURL, with: urlRequest) } catch { return upload(nil, failedWith: error) } } /// Creates a `UploadRequest` from the specified `urlRequest` for uploading the `file`. /// /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. /// /// - parameter file: The file to upload. /// - parameter urlRequest: The URL request. /// /// - returns: The created `UploadRequest`. @discardableResult open func upload(_ fileURL: URL, with urlRequest: URLRequestConvertible) -> UploadRequest { do { let urlRequest = try urlRequest.asURLRequest() return upload(.file(fileURL, urlRequest)) } catch { return upload(nil, failedWith: error) } } // MARK: Data /// Creates an `UploadRequest` from the specified `url`, `method` and `headers` for uploading the `data`. /// /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. /// /// - parameter data: The data to upload. /// - parameter url: The URL. /// - parameter method: The HTTP method. `.post` by default. /// - parameter headers: The HTTP headers. `nil` by default. /// /// - returns: The created `UploadRequest`. @discardableResult open func upload( _ data: Data, to url: URLConvertible, method: HTTPMethod = .post, headers: HTTPHeaders? = nil) -> UploadRequest { do { let urlRequest = try URLRequest(url: url, method: method, headers: headers) return upload(data, with: urlRequest) } catch { return upload(nil, failedWith: error) } } /// Creates an `UploadRequest` from the specified `urlRequest` for uploading the `data`. /// /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. /// /// - parameter data: The data to upload. /// - parameter urlRequest: The URL request. /// /// - returns: The created `UploadRequest`. @discardableResult open func upload(_ data: Data, with urlRequest: URLRequestConvertible) -> UploadRequest { do { let urlRequest = try urlRequest.asURLRequest() return upload(.data(data, urlRequest)) } catch { return upload(nil, failedWith: error) } } // MARK: InputStream /// Creates an `UploadRequest` from the specified `url`, `method` and `headers` for uploading the `stream`. /// /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. /// /// - parameter stream: The stream to upload. /// - parameter url: The URL. /// - parameter method: The HTTP method. `.post` by default. /// - parameter headers: The HTTP headers. `nil` by default. /// /// - returns: The created `UploadRequest`. @discardableResult open func upload( _ stream: InputStream, to url: URLConvertible, method: HTTPMethod = .post, headers: HTTPHeaders? = nil) -> UploadRequest { do { let urlRequest = try URLRequest(url: url, method: method, headers: headers) return upload(stream, with: urlRequest) } catch { return upload(nil, failedWith: error) } } /// Creates an `UploadRequest` from the specified `urlRequest` for uploading the `stream`. /// /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. /// /// - parameter stream: The stream to upload. /// - parameter urlRequest: The URL request. /// /// - returns: The created `UploadRequest`. @discardableResult open func upload(_ stream: InputStream, with urlRequest: URLRequestConvertible) -> UploadRequest { do { let urlRequest = try urlRequest.asURLRequest() return upload(.stream(stream, urlRequest)) } catch { return upload(nil, failedWith: error) } } // MARK: MultipartFormData /// Encodes `multipartFormData` using `encodingMemoryThreshold` and calls `encodingCompletion` with new /// `UploadRequest` using the `url`, `method` and `headers`. /// /// It is important to understand the memory implications of uploading `MultipartFormData`. If the cummulative /// payload is small, encoding the data in-memory and directly uploading to a server is the by far the most /// efficient approach. However, if the payload is too large, encoding the data in-memory could cause your app to /// be terminated. Larger payloads must first be written to disk using input and output streams to keep the memory /// footprint low, then the data can be uploaded as a stream from the resulting file. Streaming from disk MUST be /// used for larger payloads such as video content. /// /// The `encodingMemoryThreshold` parameter allows Alamofire to automatically determine whether to encode in-memory /// or stream from disk. If the content length of the `MultipartFormData` is below the `encodingMemoryThreshold`, /// encoding takes place in-memory. If the content length exceeds the threshold, the data is streamed to disk /// during the encoding process. Then the result is uploaded as data or as a stream depending on which encoding /// technique was used. /// /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. /// /// - parameter multipartFormData: The closure used to append body parts to the `MultipartFormData`. /// - parameter encodingMemoryThreshold: The encoding memory threshold in bytes. /// `multipartFormDataEncodingMemoryThreshold` by default. /// - parameter url: The URL. /// - parameter method: The HTTP method. `.post` by default. /// - parameter headers: The HTTP headers. `nil` by default. /// - parameter encodingCompletion: The closure called when the `MultipartFormData` encoding is complete. open func upload( multipartFormData: @escaping (MultipartFormData) -> Void, usingThreshold encodingMemoryThreshold: UInt64 = SessionManager.multipartFormDataEncodingMemoryThreshold, to url: URLConvertible, method: HTTPMethod = .post, headers: HTTPHeaders? = nil, queue: DispatchQueue? = nil, encodingCompletion: ((MultipartFormDataEncodingResult) -> Void)?) { do { let urlRequest = try URLRequest(url: url, method: method, headers: headers) return upload( multipartFormData: multipartFormData, usingThreshold: encodingMemoryThreshold, with: urlRequest, queue: queue, encodingCompletion: encodingCompletion ) } catch { (queue ?? DispatchQueue.main).async { encodingCompletion?(.failure(error)) } } } /// Encodes `multipartFormData` using `encodingMemoryThreshold` and calls `encodingCompletion` with new /// `UploadRequest` using the `urlRequest`. /// /// It is important to understand the memory implications of uploading `MultipartFormData`. If the cummulative /// payload is small, encoding the data in-memory and directly uploading to a server is the by far the most /// efficient approach. However, if the payload is too large, encoding the data in-memory could cause your app to /// be terminated. Larger payloads must first be written to disk using input and output streams to keep the memory /// footprint low, then the data can be uploaded as a stream from the resulting file. Streaming from disk MUST be /// used for larger payloads such as video content. /// /// The `encodingMemoryThreshold` parameter allows Alamofire to automatically determine whether to encode in-memory /// or stream from disk. If the content length of the `MultipartFormData` is below the `encodingMemoryThreshold`, /// encoding takes place in-memory. If the content length exceeds the threshold, the data is streamed to disk /// during the encoding process. Then the result is uploaded as data or as a stream depending on which encoding /// technique was used. /// /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. /// /// - parameter multipartFormData: The closure used to append body parts to the `MultipartFormData`. /// - parameter encodingMemoryThreshold: The encoding memory threshold in bytes. /// `multipartFormDataEncodingMemoryThreshold` by default. /// - parameter urlRequest: The URL request. /// - parameter encodingCompletion: The closure called when the `MultipartFormData` encoding is complete. open func upload( multipartFormData: @escaping (MultipartFormData) -> Void, usingThreshold encodingMemoryThreshold: UInt64 = SessionManager.multipartFormDataEncodingMemoryThreshold, with urlRequest: URLRequestConvertible, queue: DispatchQueue? = nil, encodingCompletion: ((MultipartFormDataEncodingResult) -> Void)?) { DispatchQueue.global(qos: .utility).async { let formData = MultipartFormData() multipartFormData(formData) var tempFileURL: URL? do { var urlRequestWithContentType = try urlRequest.asURLRequest() urlRequestWithContentType.setValue(formData.contentType, forHTTPHeaderField: "Content-Type") let isBackgroundSession = self.session.configuration.identifier != nil if formData.contentLength < encodingMemoryThreshold && !isBackgroundSession { let data = try formData.encode() let encodingResult = MultipartFormDataEncodingResult.success( request: self.upload(data, with: urlRequestWithContentType), streamingFromDisk: false, streamFileURL: nil ) (queue ?? DispatchQueue.main).async { encodingCompletion?(encodingResult) } } else { let fileManager = FileManager.default let tempDirectoryURL = URL(fileURLWithPath: NSTemporaryDirectory()) let directoryURL = tempDirectoryURL.appendingPathComponent("org.alamofire.manager/multipart.form.data") let fileName = UUID().uuidString let fileURL = directoryURL.appendingPathComponent(fileName) tempFileURL = fileURL var directoryError: Error? // Create directory inside serial queue to ensure two threads don't do this in parallel self.queue.sync { do { try fileManager.createDirectory(at: directoryURL, withIntermediateDirectories: true, attributes: nil) } catch { directoryError = error } } if let directoryError = directoryError { throw directoryError } try formData.writeEncodedData(to: fileURL) let upload = self.upload(fileURL, with: urlRequestWithContentType) // Cleanup the temp file once the upload is complete upload.delegate.queue.addOperation { do { try FileManager.default.removeItem(at: fileURL) } catch { // No-op } } (queue ?? DispatchQueue.main).async { let encodingResult = MultipartFormDataEncodingResult.success( request: upload, streamingFromDisk: true, streamFileURL: fileURL ) encodingCompletion?(encodingResult) } } } catch { // Cleanup the temp file in the event that the multipart form data encoding failed if let tempFileURL = tempFileURL { do { try FileManager.default.removeItem(at: tempFileURL) } catch { // No-op } } (queue ?? DispatchQueue.main).async { encodingCompletion?(.failure(error)) } } } } // MARK: Private - Upload Implementation private func upload(_ uploadable: UploadRequest.Uploadable) -> UploadRequest { do { let task = try uploadable.task(session: session, adapter: adapter, queue: queue) let upload = UploadRequest(session: session, requestTask: .upload(uploadable, task)) if case let .stream(inputStream, _) = uploadable { upload.delegate.taskNeedNewBodyStream = { _, _ in inputStream } } delegate[task] = upload if startRequestsImmediately { upload.resume() } return upload } catch { return upload(uploadable, failedWith: error) } } private func upload(_ uploadable: UploadRequest.Uploadable?, failedWith error: Error) -> UploadRequest { var uploadTask: Request.RequestTask = .upload(nil, nil) if let uploadable = uploadable { uploadTask = .upload(uploadable, nil) } let underlyingError = error.underlyingAdaptError ?? error let upload = UploadRequest(session: session, requestTask: uploadTask, error: underlyingError) if let retrier = retrier, error is AdaptError { allowRetrier(retrier, toRetry: upload, with: underlyingError) } else { if startRequestsImmediately { upload.resume() } } return upload } #if !os(watchOS) // MARK: - Stream Request // MARK: Hostname and Port /// Creates a `StreamRequest` for bidirectional streaming using the `hostname` and `port`. /// /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. /// /// - parameter hostName: The hostname of the server to connect to. /// - parameter port: The port of the server to connect to. /// /// - returns: The created `StreamRequest`. @discardableResult @available(iOS 9.0, macOS 10.11, tvOS 9.0, *) open func stream(withHostName hostName: String, port: Int) -> StreamRequest { return stream(.stream(hostName: hostName, port: port)) } // MARK: NetService /// Creates a `StreamRequest` for bidirectional streaming using the `netService`. /// /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. /// /// - parameter netService: The net service used to identify the endpoint. /// /// - returns: The created `StreamRequest`. @discardableResult @available(iOS 9.0, macOS 10.11, tvOS 9.0, *) open func stream(with netService: NetService) -> StreamRequest { return stream(.netService(netService)) } // MARK: Private - Stream Implementation @available(iOS 9.0, macOS 10.11, tvOS 9.0, *) private func stream(_ streamable: StreamRequest.Streamable) -> StreamRequest { do { let task = try streamable.task(session: session, adapter: adapter, queue: queue) let request = StreamRequest(session: session, requestTask: .stream(streamable, task)) delegate[task] = request if startRequestsImmediately { request.resume() } return request } catch { return stream(failedWith: error) } } @available(iOS 9.0, macOS 10.11, tvOS 9.0, *) private func stream(failedWith error: Error) -> StreamRequest { let stream = StreamRequest(session: session, requestTask: .stream(nil, nil), error: error) if startRequestsImmediately { stream.resume() } return stream } #endif // MARK: - Internal - Retry Request func retry(_ request: Request) -> Bool { guard let originalTask = request.originalTask else { return false } do { let task = try originalTask.task(session: session, adapter: adapter, queue: queue) if let originalTask = request.task { delegate[originalTask] = nil // removes the old request to avoid endless growth } request.delegate.task = task // resets all task delegate data request.retryCount += 1 request.startTime = CFAbsoluteTimeGetCurrent() request.endTime = nil task.resume() return true } catch { request.delegate.error = error.underlyingAdaptError ?? error return false } } private func allowRetrier(_ retrier: RequestRetrier, toRetry request: Request, with error: Error) { DispatchQueue.utility.async { [weak self] in guard let strongSelf = self else { return } retrier.should(strongSelf, retry: request, with: error) { shouldRetry, timeDelay in guard let strongSelf = self else { return } guard shouldRetry else { if strongSelf.startRequestsImmediately { request.resume() } return } DispatchQueue.utility.after(timeDelay) { guard let strongSelf = self else { return } let retrySucceeded = strongSelf.retry(request) if retrySucceeded, let task = request.task { strongSelf.delegate[task] = request } else { if strongSelf.startRequestsImmediately { request.resume() } } } } } } }
mit
57735cde6f596674ca44f2807929e0bb
41.599555
129
0.623913
5.414534
false
false
false
false
natecook1000/WWDC
WWDC/PDFWindowController.swift
2
2757
// // PDFWindowController.swift // WWDC // // Created by Guilherme Rambo on 20/04/15. // Copyright (c) 2015 Guilherme Rambo. All rights reserved. // import Cocoa import Quartz class PDFWindowController: NSWindowController { @IBOutlet weak var pdfView: PDFView! @IBOutlet weak var progressBgView: ContentBackgroundView! @IBOutlet weak var progressIndicator: NSProgressIndicator! var session: Session! var slidesDocument: PDFDocument? { didSet { guard slidesDocument != nil else { return } window?.titlebarAppearsTransparent = false window?.movableByWindowBackground = false pdfView.setDocument(slidesDocument) progressIndicator.stopAnimation(nil) pdfView.hidden = false progressBgView.hidden = true } } convenience init(session: Session) { self.init(windowNibName: "PDFWindowController") self.session = session } var downloader: SlidesDownloader! override func windowDidLoad() { super.windowDidLoad() window?.titlebarAppearsTransparent = true window?.movableByWindowBackground = true progressIndicator.startAnimation(nil) guard session != nil else { return } window?.title = "WWDC \(session.year) | \(session.title) | Slides" downloader = SlidesDownloader(session: session) if session.slidesPDFData.length > 0 { self.slidesDocument = PDFDocument(data: session.slidesPDFData) } else { let progressHandler: SlidesDownloader.ProgressHandler = { downloaded, total in if self.progressIndicator.indeterminate { self.progressIndicator.minValue = 0 self.progressIndicator.maxValue = total self.progressIndicator.indeterminate = false } self.progressIndicator.doubleValue = downloaded } downloader.downloadSlides({ success, data in if success == true { self.slidesDocument = PDFDocument(data: data) } else { print("Download failed") } }, progressHandler: progressHandler) } } func saveDocument(sender: AnyObject?) { let panel = NSSavePanel() panel.allowedFileTypes = ["pdf"] panel.nameFieldStringValue = session!.title panel.beginSheetModalForWindow(window!){ result in if result != 1 { return } self.slidesDocument?.writeToURL(panel.URL) } } }
bsd-2-clause
3074ecc0f649b7d8edd9b6cece42714c
30.329545
90
0.585056
5.755741
false
false
false
false
edjiang/forward-swift-workshop
SwiftNotesIOS/Pods/Stormpath/Stormpath/Social Login/FacebookLoginProvider.swift
1
1926
// // FacebookLoginProvider.swift // Stormpath // // Created by Edward Jiang on 3/7/16. // Copyright © 2016 Stormpath. All rights reserved. // import Foundation class FacebookLoginProvider: NSObject, LoginProvider { var urlSchemePrefix = "fb" var state = arc4random_uniform(10000000) func authenticationRequestURL(application: StormpathSocialProviderConfiguration) -> NSURL { let scopes = application.scopes ?? "email" // Auth_type is re-request since we need to ask for email scope again if // people decline the email permission. If it gets annoying because // people keep asking for more scopes, we can change this. let queryString = "client_id=\(application.appId)&redirect_uri=\(application.urlScheme)://authorize&response_type=token&scope=\(scopes)&state=\(state)&auth_type=rerequest".stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet())! return NSURL(string: "https://www.facebook.com/dialog/oauth?\(queryString)")! } func getResponseFromCallbackURL(url: NSURL, callback: LoginProviderCallback) { if(url.queryDictionary["error"] != nil) { // We are not even going to callback, because the user never started // the login process in the first place. Error is always because // people cancelled the FB login according to https://developers.facebook.com/docs/facebook-login/manually-build-a-login-flow return } // Get the access token, and check that the state is the same guard let accessToken = url.fragmentDictionary["access_token"] where url.fragmentDictionary["state"] == "\(state)" else { callback(nil, StormpathError.InternalSDKError) return } callback(LoginProviderResponse(data: accessToken, type: .AccessToken), nil) } }
apache-2.0
82724f3ee285d73c92d6b42fc07cf4b0
44.833333
277
0.682597
4.8125
false
false
false
false
liuxianghong/SmartLight
Code/SmartLight/SmartLight/AppDefine/DeviceSize.swift
1
1781
// // DeviceSize.swift // Drone // // Created by GuoLeon on 15/12/21. // Copyright © 2015年 fimi. All rights reserved. // import UIKit class DeviceSize: NSObject { class var customButtonHeight: CGFloat { get { return 42.0 } } class func deviceWidth() -> CGFloat { return UIScreen.main.bounds.width } class func deviceHeight() -> CGFloat { return UIScreen.main.bounds.height } class func isIPhone4s(_ isLandscape: Bool) -> Bool { if isLandscape { return deviceHeight() == 320 && deviceWidth() == 480 } else { return deviceHeight() == 480 && deviceWidth() == 320 } } class func isIPhone5(_ isLandscape: Bool) -> Bool { if isLandscape { return deviceHeight() == 320 && deviceWidth() == 568 } else { return deviceHeight() == 568 && deviceWidth() == 320 } } class func isIPhone6(_ isLandscape: Bool) -> Bool { if isLandscape { return deviceHeight() == 375 && deviceWidth() == 667 } else { return deviceHeight() == 667 && deviceWidth() == 375 } } class func isIPhone6Plus(_ isLandscape:Bool) -> Bool { if isLandscape { return deviceHeight() == 414 && deviceWidth() == 736 } else { return deviceHeight() == 736 && deviceWidth() == 414 } } var isSettingPop = false //var homeViewType: RootHomeMode = .Account // 缺省单实例对象 static let sharedInstance = DeviceSize() fileprivate override init() { super.init() } }
apache-2.0
a112f195efe02d10b0aee5e1c63bef0e
21.909091
64
0.509637
4.927374
false
false
false
false
MengQuietly/MQDouYuTV
MQDouYuTV/MQDouYuTV/Classes/Home/View/MQRecommendGameView.swift
1
2300
// // MQRecommendGameView.swift // MQDouYuTV // // Created by mengmeng on 16/12/29. // Copyright © 2016年 mengQuietly. All rights reserved. // 推荐界面:游戏view import UIKit let kMQRecommendGameCell = "kMQRecommendGameCell" let kMQGameCollectionViewsWithEdgeInsetMargin : CGFloat = 15 class MQRecommendGameView: UIView { // MARK: - 控件属性 @IBOutlet weak var gameCollectionViews: UICollectionView! // MARK:-定义模型数组属性 var gameList : [MQBaseGameModel]?{ didSet { gameCollectionViews.reloadData() } } override func awakeFromNib() { super.awakeFromNib() autoresizingMask = UIViewAutoresizing(rawValue: 0) gameCollectionViews.register(UINib(nibName: "MQRecommendGameCell", bundle: nil), forCellWithReuseIdentifier: kMQRecommendGameCell) gameCollectionViews.contentInset = UIEdgeInsets(top: 0, left: kMQGameCollectionViewsWithEdgeInsetMargin, bottom: 0, right: kMQGameCollectionViewsWithEdgeInsetMargin) gameCollectionViews.showsHorizontalScrollIndicator = false } override func layoutSubviews() { super.layoutSubviews() let layout = gameCollectionViews.collectionViewLayout as! UICollectionViewFlowLayout layout.minimumLineSpacing = 0 layout.minimumInteritemSpacing = 0 layout.scrollDirection = .horizontal layout.itemSize = CGSize(width: 90, height: 90) } } // MARK: - 快速创建View extension MQRecommendGameView { class func recommendGemeView()->MQRecommendGameView{ return Bundle.main.loadNibNamed("MQRecommendGameView", owner: nil, options: nil)?.first as! MQRecommendGameView } } // MARK:- extension MQRecommendGameView: UICollectionViewDataSource { func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return gameList?.count ?? 0 } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: kMQRecommendGameCell, for: indexPath) as! MQRecommendGameCell cell.baseGameModel = self.gameList?[indexPath.item] return cell } }
mit
db7255c878dc902196497085f198e6d7
34.171875
173
0.717903
4.936404
false
false
false
false
Czajnikowski/TrainTrippin
Pods/RxCocoa/RxCocoa/Common/RxCocoaObjCRuntimeError+Extensions.swift
3
8840
// // RxCocoaObjCRuntimeError+Extensions.swift // RxCocoa // // Created by Krunoslav Zaher on 10/9/16. // Copyright © 2016 Krunoslav Zaher. All rights reserved. // import Foundation #if !RX_NO_MODULE #if SWIFT_PACKAGE && !DISABLE_SWIZZLING && !os(Linux) import RxCocoaRuntime #endif #endif #if !DISABLE_SWIZZLING && !os(Linux) /** RxCocoa ObjC runtime interception mechanism. */ public enum RxCocoaInterceptionMechanism { /** Unknown message interception mechanism. */ case unknown /** Key value observing interception mechanism. */ case kvo } /** RxCocoa ObjC runtime modification errors. */ public enum RxCocoaObjCRuntimeError : Swift.Error , CustomDebugStringConvertible { /** Unknown error has occurred. */ case unknown(target: AnyObject) /** If the object is reporting a different class then it's real class, that means that there is probably already some interception mechanism in place or something weird is happening. The most common case when this would happen is when using a combination of KVO (`observe`) and `sentMessage`. This error is easily resolved by just using `sentMessage` observing before `observe`. The reason why the other way around could create issues is because KVO will unregister it's interceptor class and restore original class. Unfortunately that will happen no matter was there another interceptor subclass registered in hierarchy or not. Failure scenario: * KVO sets class to be `__KVO__OriginalClass` (subclass of `OriginalClass`) * `sentMessage` sets object class to be `_RX_namespace___KVO__OriginalClass` (subclass of `__KVO__OriginalClass`) * then unobserving with KVO will restore class to be `OriginalClass` -> failure point (possibly a bug in KVO) The reason why changing order of observing works is because any interception method on unregistration should return object's original real class (if that doesn't happen then it's really easy to argue that's a bug in that interception mechanism). This library won't remove registered interceptor even if there aren't any observers left because it's highly unlikely it would have any benefit in real world use cases, and it's even more dangerous. */ case objectMessagesAlreadyBeingIntercepted(target: AnyObject, interceptionMechanism: RxCocoaInterceptionMechanism) /** Trying to observe messages for selector that isn't implemented. */ case selectorNotImplemented(target: AnyObject) /** Core Foundation classes are usually toll free bridged. Those classes crash the program in case `object_setClass` is performed on them. There is a possibility to just swizzle methods on original object, but since those won't be usual use cases for this library, then an error will just be reported for now. */ case cantInterceptCoreFoundationTollFreeBridgedObjects(target: AnyObject) /** Two libraries have simultaneously tried to modify ObjC runtime and that was detected. This can only happen in scenarios where multiple interception libraries are used. To synchronize other libraries intercepting messages for an object, use `synchronized` on target object and it's meta-class. */ case threadingCollisionWithOtherInterceptionMechanism(target: AnyObject) /** For some reason saving original method implementation under RX namespace failed. */ case savingOriginalForwardingMethodFailed(target: AnyObject) /** Intercepting a sent message by replacing a method implementation with `_objc_msgForward` failed for some reason. */ case replacingMethodWithForwardingImplementation(target: AnyObject) /** Attempt to intercept one of the performance sensitive methods: * class * respondsToSelector: * methodSignatureForSelector: * forwardingTargetForSelector: */ case observingPerformanceSensitiveMessages(target: AnyObject) /** Message implementation has unsupported return type (for example large struct). The reason why this is a error is because in some cases intercepting sent messages requires replacing implementation with `_objc_msgForward_stret` instead of `_objc_msgForward`. The unsupported cases should be fairly uncommon. */ case observingMessagesWithUnsupportedReturnType(target: AnyObject) } public extension RxCocoaObjCRuntimeError { /** A textual representation of `self`, suitable for debugging. */ public var debugDescription: String { switch self { case let .unknown(target): return "Unknown error occurred.\nTarget: `\(target)`" case let .objectMessagesAlreadyBeingIntercepted(target, interceptionMechanism): let interceptionMechanismDescription = interceptionMechanism == .kvo ? "KVO" : "other interception mechanism" return "Collision between RxCocoa interception mechanism and \(interceptionMechanismDescription)." + " To resolve this conflict please use this interception mechanism first.\nTarget: \(target)" case let .selectorNotImplemented(target): return "Trying to observe messages for selector that isn't implemented.\nTarget: \(target)" case let .cantInterceptCoreFoundationTollFreeBridgedObjects(target): return "Interception of messages sent to Core Foundation isn't supported.\nTarget: \(target)" case let .threadingCollisionWithOtherInterceptionMechanism(target): return "Detected a conflict while modifying ObjC runtime.\nTarget: \(target)" case let .savingOriginalForwardingMethodFailed(target): return "Saving original method implementation failed.\nTarget: \(target)" case let .replacingMethodWithForwardingImplementation(target): return "Intercepting a sent message by replacing a method implementation with `_objc_msgForward` failed for some reason.\nTarget: \(target)" case let .observingPerformanceSensitiveMessages(target): return "Attempt to intercept one of the performance sensitive methods. \nTarget: \(target)" case let .observingMessagesWithUnsupportedReturnType(target): return "Attempt to intercept a method with unsupported return type. \nTarget: \(target)" } } } // MARK: Conversions `NSError` > `RxCocoaObjCRuntimeError` extension Error { func rxCocoaErrorForTarget(_ target: AnyObject) -> RxCocoaObjCRuntimeError { let error = self as NSError if error.domain == RXObjCRuntimeErrorDomain { let errorCode = RXObjCRuntimeError(rawValue: error.code) ?? .unknown switch errorCode { case .unknown: return .unknown(target: target) case .objectMessagesAlreadyBeingIntercepted: let isKVO = (error.userInfo[RXObjCRuntimeErrorIsKVOKey] as? NSNumber)?.boolValue ?? false return .objectMessagesAlreadyBeingIntercepted(target: target, interceptionMechanism: isKVO ? .kvo : .unknown) case .selectorNotImplemented: return .selectorNotImplemented(target: target) case .cantInterceptCoreFoundationTollFreeBridgedObjects: return .cantInterceptCoreFoundationTollFreeBridgedObjects(target: target) case .threadingCollisionWithOtherInterceptionMechanism: return .threadingCollisionWithOtherInterceptionMechanism(target: target) case .savingOriginalForwardingMethodFailed: return .savingOriginalForwardingMethodFailed(target: target) case .replacingMethodWithForwardingImplementation: return .replacingMethodWithForwardingImplementation(target: target) case .observingPerformanceSensitiveMessages: return .observingPerformanceSensitiveMessages(target: target) case .observingMessagesWithUnsupportedReturnType: return .observingMessagesWithUnsupportedReturnType(target: target) } } return RxCocoaObjCRuntimeError.unknown(target: target) } } #endif
mit
b43e860760b77c134711504bd5387ede
46.015957
156
0.668741
5.666026
false
false
false
false
enpitut/SAWARITAI
iOS/PoiPet/TextFieldEffects/KaedeTextField.swift
4
4530
// // KaedeTextField.swift // Swish // // Created by Raúl Riera on 20/01/2015. // Copyright (c) 2015 com.raulriera.swishapp. All rights reserved. // import UIKit /** A KaedeTextField is a subclass of the TextFieldEffects object, is a control that displays an UITextField with a customizable visual effect around the foreground of the control. */ @IBDesignable public class KaedeTextField: TextFieldEffects { /** The color of the placeholder text. This property applies a color to the complete placeholder string. The default value for this property is a black color. */ @IBInspectable dynamic public var placeholderColor: UIColor? { didSet { updatePlaceholder() } } /** The view’s foreground color. The default value for this property is a clear color. */ @IBInspectable dynamic public var foregroundColor: UIColor? { didSet { updateForegroundColor() } } override public var placeholder: String? { didSet { updatePlaceholder() } } override public var bounds: CGRect { didSet { drawViewsForRect(bounds) } } private let foregroundView = UIView() private let placeholderInsets = CGPoint(x: 10, y: 5) private let textFieldInsets = CGPoint(x: 10, y: 0) // MARK: - TextFieldsEffects override public func drawViewsForRect(rect: CGRect) { let frame = CGRect(origin: CGPointZero, size: CGSize(width: rect.size.width, height: rect.size.height)) foregroundView.frame = frame foregroundView.userInteractionEnabled = false placeholderLabel.frame = CGRectInset(frame, placeholderInsets.x, placeholderInsets.y) placeholderLabel.font = placeholderFontFromFont(font!) updateForegroundColor() updatePlaceholder() if text!.isNotEmpty || isFirstResponder() { animateViewsForTextEntry() } addSubview(foregroundView) addSubview(placeholderLabel) } override public func animateViewsForTextEntry() { UIView.animateWithDuration(0.35, delay: 0.0, usingSpringWithDamping: 0.8, initialSpringVelocity: 2.0, options: .BeginFromCurrentState, animations: ({ self.placeholderLabel.frame.origin = CGPoint(x: self.frame.size.width * 0.65, y: self.placeholderInsets.y) }), completion: nil) UIView.animateWithDuration(0.45, delay: 0.0, usingSpringWithDamping: 0.8, initialSpringVelocity: 1.5, options: .BeginFromCurrentState, animations: ({ self.foregroundView.frame.origin = CGPoint(x: self.frame.size.width * 0.6, y: 0) }), completion: nil) } override public func animateViewsForTextDisplay() { if text!.isEmpty { UIView.animateWithDuration(0.3, delay: 0.0, usingSpringWithDamping: 0.8, initialSpringVelocity: 2.0, options: .BeginFromCurrentState, animations: ({ self.placeholderLabel.frame.origin = self.placeholderInsets }), completion: nil) UIView.animateWithDuration(0.3, delay: 0.0, usingSpringWithDamping: 1.0, initialSpringVelocity: 2.0, options: .BeginFromCurrentState, animations: ({ self.foregroundView.frame.origin = CGPointZero }), completion: nil) } } // MARK: - Private private func updateForegroundColor() { foregroundView.backgroundColor = foregroundColor } private func updatePlaceholder() { placeholderLabel.text = placeholder placeholderLabel.textColor = placeholderColor } private func placeholderFontFromFont(font: UIFont) -> UIFont! { let smallerFont = UIFont(name: font.fontName, size: font.pointSize * 0.8) return smallerFont } // MARK: - Overrides override public func editingRectForBounds(bounds: CGRect) -> CGRect { let frame = CGRect(origin: bounds.origin, size: CGSize(width: bounds.size.width * 0.6, height: bounds.size.height)) return CGRectInset(frame, textFieldInsets.x, textFieldInsets.y) } override public func textRectForBounds(bounds: CGRect) -> CGRect { let frame = CGRect(origin: bounds.origin, size: CGSize(width: bounds.size.width * 0.6, height: bounds.size.height)) return CGRectInset(frame, textFieldInsets.x, textFieldInsets.y) } }
gpl-2.0
71fadaf7d1ed652abb165452c1f47faa
34.653543
177
0.646565
5.03
false
false
false
false
testpress/ios-app
ios-app/UI/BaseDBTableViewController.swift
1
2520
// // BaseDBViewController.swift // ios-app // // Copyright © 2017 Testpress. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import UIKit import ObjectMapper import RealmSwift class BaseDBTableViewController<T: Mappable>: TPBasePagedTableViewController<T> where T:Object { var firstCallBack: Bool = true // On firstCallBack load modified items if items already exists override func viewWillAppear(_ animated: Bool) { items = getItemsFromDb() super.viewWillAppear(animated) } override func viewDidAppear(_ animated: Bool) { if (items.isEmpty || firstCallBack) { firstCallBack = false tableView.tableFooterView?.isHidden = true pager.reset() loadItems() } } func getItemsFromDb() -> [T] { return DBManager<T>().getItemsFromDB() } override func loadItems() { if loadingItems { return } loadingItems = true pager.next(completion: { items, error in if let error = error { debugPrint(error.message ?? "No error") debugPrint(error.kind) self.handleError(error) return } let items = Array(items!.values) DBManager<T>().addData(objects: items) self.onLoadFinished(items: self.getItemsFromDb()) }) } }
mit
28425eb93999a7598d47977706dc89fe
33.986111
98
0.651052
4.699627
false
false
false
false
coderMONSTER/iosstar
iOSStar/AppAPI/DealAPI/DealSocketAPI.swift
1
3264
// // DealSocketAPI.swift // iOSStar // // Created by J-bb on 17/6/8. // Copyright © 2017年 YunDian. All rights reserved. // import Foundation class DealSocketAPI: BaseSocketAPI, DealAPI{ //发起委托 func buyOrSell(requestModel:BuyOrSellRequestModel, complete: CompleteBlock?, error: ErrorBlock?) { let packet = SocketDataPacket(opcode: .buyOrSell, model: requestModel) startModelRequest(packet, modelClass: EntrustSuccessModel.self, complete: complete, error: error) } //确认订单 func sureOrderRequest(requestModel:SureOrderRequestModel, complete: CompleteBlock?, error: ErrorBlock?) { let packet = SocketDataPacket(opcode: .sureOrder, model: requestModel) startModelRequest(packet, modelClass: SureOrderResultModel.self, complete: complete, error: error) } //取消订单 func cancelOrderRequest(requestModel:CancelOrderRequestModel, complete: CompleteBlock?, error: ErrorBlock?) { let packet = SocketDataPacket(opcode: .cancelOrder, model: requestModel) startResultIntRequest(packet, complete: complete, error: error) } //收到订单结果 func setReceiveOrderResult(complete:@escaping CompleteBlock) { SocketRequestManage.shared.receiveOrderResult = { (response) in let jsonResponse = response as! SocketJsonResponse let model = jsonResponse.responseModel(OrderResultModel.self) as? OrderResultModel if model != nil { complete(model) } } } //收到匹配成功 func setReceiveMatching(complete:@escaping CompleteBlock) { SocketRequestManage.shared.receiveMatching = { (response) in let jsonResponse = response as! SocketJsonResponse let model = jsonResponse.responseModel(ReceiveMacthingModel.self) as? ReceiveMacthingModel if model != nil { complete(model) } } } //验证交易密码 func checkPayPass( paypwd: String, complete: CompleteBlock?, error: ErrorBlock?){ let param: [String: Any] = [SocketConst.Key.id: StarUserModel.getCurrentUser()?.userinfo?.id ?? 0, SocketConst.Key.paypwd :paypwd, SocketConst.Key.token :StarUserModel.getCurrentUser()?.token ?? ""] let packet: SocketDataPacket = SocketDataPacket.init(opcode: .paypwd, dict: param as [String : AnyObject]) startRequest(packet, complete: complete, error: error) } //请求委托列表 func requestEntrustList(requestModel:DealRecordRequestModel,OPCode:SocketConst.OPCode,complete: CompleteBlock?, error: ErrorBlock?) { let packet = SocketDataPacket(opcode:OPCode, model: requestModel) startModelsRequest(packet, listName: "positionsList", modelClass: EntrustListModel.self, complete: complete, error: error) } //订单列表 func requestOrderList(requestModel:OrderRecordRequestModel,OPCode:SocketConst.OPCode,complete: CompleteBlock?, error: ErrorBlock?) { let packet = SocketDataPacket(opcode: OPCode, model: requestModel) startModelsRequest(packet, listName: "ordersList", modelClass: OrderListModel.self, complete: complete, error: error) } }
gpl-3.0
ba8d90f133dff649e500add244e43c10
43.180556
137
0.689406
4.518466
false
false
false
false
derekcdaley/anipalooza
AniPalooza/GameViewController.swift
1
2299
// // GameViewController.swift // Guess It // // Created by Derek Daley on 3/15/17. // Copyright © 2017 DSkwared. All rights reserved. // import UIKit import SpriteKit import GameplayKit import AVFoundation private var musicPlayer: AVAudioPlayer! = nil; class GameViewController: UIViewController { private var bgMusic = BackgroundMusicController(); private var settings = SettingsScene(); override func viewDidLoad() { super.viewDidLoad(); self.initializeView(); if let view = self.view as! SKView? { // Load the SKScene from 'GameScene.sks' if let scene = MainMenuScene(fileNamed: "MainMenuScene") { // Set the scale mode to scale to fit the window scene.scaleMode = .aspectFill // Present the scene view.presentScene(scene) } view.ignoresSiblingOrder = true view.showsFPS = false; view.showsNodeCount = false; } } override var shouldAutorotate: Bool { return true } override var supportedInterfaceOrientations: UIInterfaceOrientationMask { if UIDevice.current.userInterfaceIdiom == .phone { return .allButUpsideDown } else { return .all } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Release any cached data, images, etc that aren't in use. } override var prefersStatusBarHidden: Bool { return true } func initializeView() { let launchedBefore = UserDefaults.standard.bool(forKey: "launchedBefore"); let scene = MainMenuScene(fileNamed: "MainMenuScene"); if !launchedBefore { settings.defaults.set("On", forKey: "MusicPref"); UserDefaults.standard.set(true, forKey: "launchedBefore"); } musicPlayer = bgMusic.playBackgroundMusic(scene: scene!); } func globalMusicStop() { if musicPlayer.isPlaying { musicPlayer.stop(); } } func globalMusicStart() { if !musicPlayer.isPlaying { musicPlayer.play(); } } }
gpl-3.0
df51bf7380968eb7a26d48d26f409177
24.820225
82
0.583551
5.199095
false
false
false
false
premefeed/premefeed-ios
PremeFeed-iOS/SwiftyJSON.swift
1
35807
// SwiftyJSON.swift // // Copyright (c) 2014 Ruoyu Fu, Pinglin Tang // // 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 // MARK: - Error ///Error domain public let ErrorDomain: String! = "SwiftyJSONErrorDomain" ///Error code public let ErrorUnsupportedType: Int! = 999 public let ErrorIndexOutOfBounds: Int! = 900 public let ErrorWrongType: Int! = 901 public let ErrorNotExist: Int! = 500 // MARK: - JSON Type /** JSON's type definitions. See http://tools.ietf.org/html/rfc7231#section-4.3 */ public enum Type :Int{ case Number case String case Bool case Array case Dictionary case Null case Unknown } // MARK: - JSON Base public struct JSON { /** Creates a JSON using the data. - parameter data: The NSData used to convert to json.Top level object in data is an NSArray or NSDictionary - parameter opt: The JSON serialization reading options. `.AllowFragments` by default. - parameter error: error The NSErrorPointer used to return the error. `nil` by default. - returns: The created JSON */ public init(data:NSData, options opt: NSJSONReadingOptions = .AllowFragments, error: NSErrorPointer = nil) { do { let object: AnyObject = try NSJSONSerialization.JSONObjectWithData(data, options: opt) self.init(object) } catch let error1 as NSError { error.memory = error1 self.init(NSNull()) } } /** Creates a JSON using the object. - parameter object: The object must have the following properties: All objects are NSString/String, NSNumber/Int/Float/Double/Bool, NSArray/Array, NSDictionary/Dictionary, or NSNull; All dictionary keys are NSStrings/String; NSNumbers are not NaN or infinity. - returns: The created JSON */ public init(_ object: AnyObject) { self.object = object } /** Creates a JSON from a [JSON] - parameter jsonArray: A Swift array of JSON objects - returns: The created JSON */ public init(_ jsonArray:[JSON]) { self.init(jsonArray.map { $0.object }) } /// Private object private var _object: AnyObject = NSNull() /// Private type private var _type: Type = .Null /// prviate error private var _error: NSError? /// Object in JSON public var object: AnyObject { get { return _object } set { _object = newValue switch newValue { case let number as NSNumber: if number.isBool { _type = .Bool } else { _type = .Number } case let string as NSString: _type = .String case let null as NSNull: _type = .Null case let array as [AnyObject]: _type = .Array case let dictionary as [String : AnyObject]: _type = .Dictionary default: _type = .Unknown _object = NSNull() _error = NSError(domain: ErrorDomain, code: ErrorUnsupportedType, userInfo: [NSLocalizedDescriptionKey: "It is a unsupported type"]) } } } /// json type public var type: Type { get { return _type } } /// Error in JSON public var error: NSError? { get { return self._error } } /// The static null json public static var nullJSON: JSON { get { return JSON(NSNull()) } } } // MARK: - SequenceType extension JSON : Swift.SequenceType { /// If `type` is `.Array` or `.Dictionary`, return `array.empty` or `dictonary.empty` otherwise return `false`. public var isEmpty: Bool { get { switch self.type { case .Array: return (self.object as! [AnyObject]).isEmpty case .Dictionary: return (self.object as! [String : AnyObject]).isEmpty default: return false } } } /// If `type` is `.Array` or `.Dictionary`, return `array.count` or `dictonary.count` otherwise return `0`. public var count: Int { get { switch self.type { case .Array: return self.arrayValue.count case .Dictionary: return self.dictionaryValue.count default: return 0 } } } /** If `type` is `.Array` or `.Dictionary`, return a generator over the elements like `Array` or `Dictionary`, otherwise return a generator over empty. - returns: Return a *generator* over the elements of this *sequence*. */ public func generate() -> AnyGenerator<(String, JSON)> { switch self.type { case .Array: let array_ = object as! [AnyObject] var generate_ = array_.generate() var index_: Int = 0 return anyGenerator { if let element_: AnyObject = generate_.next() { return ("\(index_++)", JSON(element_)) } else { return nil } } case .Dictionary: let dictionary_ = object as! [String : AnyObject] var generate_ = dictionary_.generate() return anyGenerator { if let (key_, value_): (String, AnyObject) = generate_.next() { return (key_, JSON(value_)) } else { return nil } } default: return anyGenerator { return nil } } } } // MARK: - Subscript /** * To mark both String and Int can be used in subscript. */ public protocol SubscriptType {} extension Int: SubscriptType {} extension String: SubscriptType {} extension JSON { /// If `type` is `.Array`, return json which's object is `array[index]`, otherwise return null json with error. private subscript(index index: Int) -> JSON { get { if self.type != .Array { var errorResult_ = JSON.nullJSON errorResult_._error = self._error ?? NSError(domain: ErrorDomain, code: ErrorWrongType, userInfo: [NSLocalizedDescriptionKey: "Array[\(index)] failure, It is not an array"]) return errorResult_ } let array_ = self.object as! [AnyObject] if index >= 0 && index < array_.count { return JSON(array_[index]) } var errorResult_ = JSON.nullJSON errorResult_._error = NSError(domain: ErrorDomain, code:ErrorIndexOutOfBounds , userInfo: [NSLocalizedDescriptionKey: "Array[\(index)] is out of bounds"]) return errorResult_ } set { if self.type == .Array { var array_ = self.object as! [AnyObject] if array_.count > index { array_[index] = newValue.object self.object = array_ } } } } /// If `type` is `.Dictionary`, return json which's object is `dictionary[key]` , otherwise return null json with error. private subscript(key key: String) -> JSON { get { var returnJSON = JSON.nullJSON if self.type == .Dictionary { let dictionary_ = self.object as! [String : AnyObject] if let object_: AnyObject = dictionary_[key] { returnJSON = JSON(object_) } else { returnJSON._error = NSError(domain: ErrorDomain, code: ErrorNotExist, userInfo: [NSLocalizedDescriptionKey: "Dictionary[\"\(key)\"] does not exist"]) } } else { returnJSON._error = self._error ?? NSError(domain: ErrorDomain, code: ErrorWrongType, userInfo: [NSLocalizedDescriptionKey: "Dictionary[\"\(key)\"] failure, It is not an dictionary"]) } return returnJSON } set { if self.type == .Dictionary { var dictionary_ = self.object as! [String : AnyObject] dictionary_[key] = newValue.object self.object = dictionary_ } } } /// If `sub` is `Int`, return `subscript(index:)`; If `sub` is `String`, return `subscript(key:)`. private subscript(sub sub: SubscriptType) -> JSON { get { if sub is String { return self[key:sub as! String] } else { return self[index:sub as! Int] } } set { if sub is String { self[key:sub as! String] = newValue } else { self[index:sub as! Int] = newValue } } } /** Find a json in the complex data structuresby using the Int/String's array. - parameter path: The target json's path. Example: let json = JSON[data] let path = [9,"list","person","name"] let name = json[path] The same as: let name = json[9]["list"]["person"]["name"] - returns: Return a json found by the path or a null json with error */ public subscript(path: [SubscriptType]) -> JSON { get { if path.count == 0 { return JSON.nullJSON } var next = self for sub in path { next = next[sub:sub] } return next } set { switch path.count { case 0: return case 1: self[sub:path[0]] = newValue default: var last = newValue var newPath = path newPath.removeLast() for sub in Array(path.reverse()) { var previousLast = self[newPath] previousLast[sub:sub] = last last = previousLast if newPath.count <= 1 { break } newPath.removeLast() } self[sub:newPath[0]] = last } } } /** Find a json in the complex data structuresby using the Int/String's array. - parameter path: The target json's path. Example: let name = json[9,"list","person","name"] The same as: let name = json[9]["list"]["person"]["name"] - returns: Return a json found by the path or a null json with error */ public subscript(path: SubscriptType...) -> JSON { get { return self[path] } set { self[path] = newValue } } } // MARK: - LiteralConvertible extension JSON: Swift.StringLiteralConvertible { public init(stringLiteral value: StringLiteralType) { self.init(value) } public init(extendedGraphemeClusterLiteral value: StringLiteralType) { self.init(value) } public init(unicodeScalarLiteral value: StringLiteralType) { self.init(value) } } extension JSON: Swift.IntegerLiteralConvertible { public init(integerLiteral value: IntegerLiteralType) { self.init(value) } } extension JSON: Swift.BooleanLiteralConvertible { public init(booleanLiteral value: BooleanLiteralType) { self.init(value) } } extension JSON: Swift.FloatLiteralConvertible { public init(floatLiteral value: FloatLiteralType) { self.init(value) } } extension JSON: Swift.DictionaryLiteralConvertible { public init(dictionaryLiteral elements: (String, AnyObject)...) { var dictionary_ = [String : AnyObject]() for (key_, value) in elements { dictionary_[key_] = value } self.init(dictionary_) } } extension JSON: Swift.ArrayLiteralConvertible { public init(arrayLiteral elements: AnyObject...) { self.init(elements) } } extension JSON: Swift.NilLiteralConvertible { public init(nilLiteral: ()) { self.init(NSNull()) } } // MARK: - Raw extension JSON: Swift.RawRepresentable { public init?(rawValue: AnyObject) { if JSON(rawValue).type == .Unknown { return nil } else { self.init(rawValue) } } public var rawValue: AnyObject { return self.object } public func rawData(options opt: NSJSONWritingOptions = NSJSONWritingOptions(rawValue: 0)) throws -> NSData { return try NSJSONSerialization.dataWithJSONObject(self.object, options: opt) } public func rawString(encoding: UInt = NSUTF8StringEncoding, options opt: NSJSONWritingOptions = .PrettyPrinted) -> String? { switch self.type { case .Array, .Dictionary: do { let data = try self.rawData(options: opt) return NSString(data: data, encoding: encoding) as? String } catch _ { return nil } case .String: return (self.object as! String) case .Number: return (self.object as! NSNumber).stringValue case .Bool: return (self.object as! Bool).description case .Null: return "null" default: return nil } } } // MARK: - Printable, DebugPrintable extension JSON: Swift.Printable, Swift.DebugPrintable { public var description: String { if let string = self.rawString(options:.PrettyPrinted) { return string } else { return "unknown" } } public var debugDescription: String { return description } } // MARK: - Array extension JSON { //Optional [JSON] public var array: [JSON]? { get { if self.type == .Array { return (self.object as! [AnyObject]).map{ JSON($0) } } else { return nil } } } //Non-optional [JSON] public var arrayValue: [JSON] { get { return self.array ?? [] } } //Optional [AnyObject] public var arrayObject: [AnyObject]? { get { switch self.type { case .Array: return self.object as? [AnyObject] default: return nil } } set { if newValue != nil { self.object = NSMutableArray(array: newValue!, copyItems: true) } else { self.object = NSNull() } } } } // MARK: - Dictionary extension JSON { private func _map<Key:Hashable ,Value, NewValue>(source: [Key: Value], transform: Value -> NewValue) -> [Key: NewValue] { var result = [Key: NewValue](minimumCapacity:source.count) for (key,value) in source { result[key] = transform(value) } return result } //Optional [String : JSON] public var dictionary: [String : JSON]? { get { if self.type == .Dictionary { return _map(self.object as! [String : AnyObject]){ JSON($0) } } else { return nil } } } //Non-optional [String : JSON] public var dictionaryValue: [String : JSON] { get { return self.dictionary ?? [:] } } //Optional [String : AnyObject] public var dictionaryObject: [String : AnyObject]? { get { switch self.type { case .Dictionary: return self.object as? [String : AnyObject] default: return nil } } set { if newValue != nil { self.object = NSMutableDictionary(dictionary: newValue!, copyItems: true) } else { self.object = NSNull() } } } } // MARK: - Bool extension JSON: Swift.BooleanType { //Optional bool public var bool: Bool? { get { switch self.type { case .Bool: return self.object.boolValue default: return nil } } set { if newValue != nil { self.object = NSNumber(bool: newValue!) } else { self.object = NSNull() } } } //Non-optional bool public var boolValue: Bool { get { switch self.type { case .Bool, .Number, .String: return self.object.boolValue default: return false } } set { self.object = NSNumber(bool: newValue) } } } // MARK: - String extension JSON { //Optional string public var string: String? { get { switch self.type { case .String: return self.object as? String default: return nil } } set { if newValue != nil { self.object = NSString(string:newValue!) } else { self.object = NSNull() } } } //Non-optional string public var stringValue: String { get { switch self.type { case .String: return self.object as! String case .Number: return self.object.stringValue case .Bool: return (self.object as! Bool).description default: return "" } } set { self.object = NSString(string:newValue) } } } // MARK: - Number extension JSON { //Optional number public var number: NSNumber? { get { switch self.type { case .Number, .Bool: return self.object as? NSNumber default: return nil } } set { self.object = newValue?.copy() ?? NSNull() } } //Non-optional number public var numberValue: NSNumber { get { switch self.type { case .String: let scanner = NSScanner(string: self.object as! String) if scanner.scanDouble(nil){ if (scanner.atEnd) { return NSNumber(double:(self.object as! NSString).doubleValue) } } return NSNumber(double: 0.0) case .Number, .Bool: return self.object as! NSNumber default: return NSNumber(double: 0.0) } } set { self.object = newValue.copy() } } } //MARK: - Null extension JSON { public var null: NSNull? { get { switch self.type { case .Null: return NSNull() default: return nil } } set { self.object = NSNull() } } } //MARK: - URL extension JSON { //Optional URL public var URL: NSURL? { get { switch self.type { case .String: if let encodedString_ = self.object.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding) { return NSURL(string: encodedString_) } else { return nil } default: return nil } } set { self.object = newValue?.absoluteString ?? NSNull() } } } // MARK: - Int, Double, Float, Int8, Int16, Int32, Int64 extension JSON { public var double: Double? { get { return self.number?.doubleValue } set { if newValue != nil { self.object = NSNumber(double: newValue!) } else { self.object = NSNull() } } } public var doubleValue: Double { get { return self.numberValue.doubleValue } set { self.object = NSNumber(double: newValue) } } public var float: Float? { get { return self.number?.floatValue } set { if newValue != nil { self.object = NSNumber(float: newValue!) } else { self.object = NSNull() } } } public var floatValue: Float { get { return self.numberValue.floatValue } set { self.object = NSNumber(float: newValue) } } public var int: Int? { get { return self.number?.longValue } set { if newValue != nil { self.object = NSNumber(integer: newValue!) } else { self.object = NSNull() } } } public var intValue: Int { get { return self.numberValue.integerValue } set { self.object = NSNumber(integer: newValue) } } public var uInt: UInt? { get { return self.number?.unsignedLongValue } set { if newValue != nil { self.object = NSNumber(unsignedLong: newValue!) } else { self.object = NSNull() } } } public var uIntValue: UInt { get { return self.numberValue.unsignedLongValue } set { self.object = NSNumber(unsignedLong: newValue) } } public var int8: Int8? { get { return self.number?.charValue } set { if newValue != nil { self.object = NSNumber(char: newValue!) } else { self.object = NSNull() } } } public var int8Value: Int8 { get { return self.numberValue.charValue } set { self.object = NSNumber(char: newValue) } } public var uInt8: UInt8? { get { return self.number?.unsignedCharValue } set { if newValue != nil { self.object = NSNumber(unsignedChar: newValue!) } else { self.object = NSNull() } } } public var uInt8Value: UInt8 { get { return self.numberValue.unsignedCharValue } set { self.object = NSNumber(unsignedChar: newValue) } } public var int16: Int16? { get { return self.number?.shortValue } set { if newValue != nil { self.object = NSNumber(short: newValue!) } else { self.object = NSNull() } } } public var int16Value: Int16 { get { return self.numberValue.shortValue } set { self.object = NSNumber(short: newValue) } } public var uInt16: UInt16? { get { return self.number?.unsignedShortValue } set { if newValue != nil { self.object = NSNumber(unsignedShort: newValue!) } else { self.object = NSNull() } } } public var uInt16Value: UInt16 { get { return self.numberValue.unsignedShortValue } set { self.object = NSNumber(unsignedShort: newValue) } } public var int32: Int32? { get { return self.number?.intValue } set { if newValue != nil { self.object = NSNumber(int: newValue!) } else { self.object = NSNull() } } } public var int32Value: Int32 { get { return self.numberValue.intValue } set { self.object = NSNumber(int: newValue) } } public var uInt32: UInt32? { get { return self.number?.unsignedIntValue } set { if newValue != nil { self.object = NSNumber(unsignedInt: newValue!) } else { self.object = NSNull() } } } public var uInt32Value: UInt32 { get { return self.numberValue.unsignedIntValue } set { self.object = NSNumber(unsignedInt: newValue) } } public var int64: Int64? { get { return self.number?.longLongValue } set { if newValue != nil { self.object = NSNumber(longLong: newValue!) } else { self.object = NSNull() } } } public var int64Value: Int64 { get { return self.numberValue.longLongValue } set { self.object = NSNumber(longLong: newValue) } } public var uInt64: UInt64? { get { return self.number?.unsignedLongLongValue } set { if newValue != nil { self.object = NSNumber(unsignedLongLong: newValue!) } else { self.object = NSNull() } } } public var uInt64Value: UInt64 { get { return self.numberValue.unsignedLongLongValue } set { self.object = NSNumber(unsignedLongLong: newValue) } } } //MARK: - Comparable extension JSON: Swift.Comparable {} public func ==(lhs: JSON, rhs: JSON) -> Bool { switch (lhs.type, rhs.type) { case (.Number, .Number): return (lhs.object as! NSNumber) == (rhs.object as! NSNumber) case (.String, .String): return (lhs.object as! String) == (rhs.object as! String) case (.Bool, .Bool): return (lhs.object as! Bool) == (rhs.object as! Bool) case (.Array, .Array): return (lhs.object as! NSArray) == (rhs.object as! NSArray) case (.Dictionary, .Dictionary): return (lhs.object as! NSDictionary) == (rhs.object as! NSDictionary) case (.Null, .Null): return true default: return false } } public func <=(lhs: JSON, rhs: JSON) -> Bool { switch (lhs.type, rhs.type) { case (.Number, .Number): return (lhs.object as! NSNumber) <= (rhs.object as! NSNumber) case (.String, .String): return (lhs.object as! String) <= (rhs.object as! String) case (.Bool, .Bool): return (lhs.object as! Bool) == (rhs.object as! Bool) case (.Array, .Array): return (lhs.object as! NSArray) == (rhs.object as! NSArray) case (.Dictionary, .Dictionary): return (lhs.object as! NSDictionary) == (rhs.object as! NSDictionary) case (.Null, .Null): return true default: return false } } public func >=(lhs: JSON, rhs: JSON) -> Bool { switch (lhs.type, rhs.type) { case (.Number, .Number): return (lhs.object as! NSNumber) >= (rhs.object as! NSNumber) case (.String, .String): return (lhs.object as! String) >= (rhs.object as! String) case (.Bool, .Bool): return (lhs.object as! Bool) == (rhs.object as! Bool) case (.Array, .Array): return (lhs.object as! NSArray) == (rhs.object as! NSArray) case (.Dictionary, .Dictionary): return (lhs.object as! NSDictionary) == (rhs.object as! NSDictionary) case (.Null, .Null): return true default: return false } } public func >(lhs: JSON, rhs: JSON) -> Bool { switch (lhs.type, rhs.type) { case (.Number, .Number): return (lhs.object as! NSNumber) > (rhs.object as! NSNumber) case (.String, .String): return (lhs.object as! String) > (rhs.object as! String) default: return false } } public func <(lhs: JSON, rhs: JSON) -> Bool { switch (lhs.type, rhs.type) { case (.Number, .Number): return (lhs.object as! NSNumber) < (rhs.object as! NSNumber) case (.String, .String): return (lhs.object as! String) < (rhs.object as! String) default: return false } } private let trueNumber = NSNumber(bool: true) private let falseNumber = NSNumber(bool: false) private let trueObjCType = String.fromCString(trueNumber.objCType) private let falseObjCType = String.fromCString(falseNumber.objCType) // MARK: - NSNumber: Comparable extension NSNumber: Swift.Comparable { var isBool:Bool { get { let objCType = String.fromCString(self.objCType) if (self.compare(trueNumber) == NSComparisonResult.OrderedSame && objCType == trueObjCType) || (self.compare(falseNumber) == NSComparisonResult.OrderedSame && objCType == falseObjCType){ return true } else { return false } } } } public func ==(lhs: NSNumber, rhs: NSNumber) -> Bool { switch (lhs.isBool, rhs.isBool) { case (false, true): return false case (true, false): return false default: return lhs.compare(rhs) == NSComparisonResult.OrderedSame } } public func !=(lhs: NSNumber, rhs: NSNumber) -> Bool { return !(lhs == rhs) } public func <(lhs: NSNumber, rhs: NSNumber) -> Bool { switch (lhs.isBool, rhs.isBool) { case (false, true): return false case (true, false): return false default: return lhs.compare(rhs) == NSComparisonResult.OrderedAscending } } public func >(lhs: NSNumber, rhs: NSNumber) -> Bool { switch (lhs.isBool, rhs.isBool) { case (false, true): return false case (true, false): return false default: return lhs.compare(rhs) == NSComparisonResult.OrderedDescending } } public func <=(lhs: NSNumber, rhs: NSNumber) -> Bool { switch (lhs.isBool, rhs.isBool) { case (false, true): return false case (true, false): return false default: return lhs.compare(rhs) != NSComparisonResult.OrderedDescending } } public func >=(lhs: NSNumber, rhs: NSNumber) -> Bool { switch (lhs.isBool, rhs.isBool) { case (false, true): return false case (true, false): return false default: return lhs.compare(rhs) != NSComparisonResult.OrderedAscending } } //MARK:- Unavailable @available(*, unavailable, renamed="JSON") public typealias JSONValue = JSON extension JSON { @available(*, unavailable, message="use 'init(_ object:AnyObject)' instead") public init(object: AnyObject) { self = JSON(object) } @available(*, unavailable, renamed="dictionaryObject") public var dictionaryObjects: [String : AnyObject]? { get { return self.dictionaryObject } } @available(*, unavailable, renamed="arrayObject") public var arrayObjects: [AnyObject]? { get { return self.arrayObject } } @available(*, unavailable, renamed="int8") public var char: Int8? { get { return self.number?.charValue } } @available(*, unavailable, renamed="int8Value") public var charValue: Int8 { get { return self.numberValue.charValue } } @available(*, unavailable, renamed="uInt8") public var unsignedChar: UInt8? { get{ return self.number?.unsignedCharValue } } @available(*, unavailable, renamed="uInt8Value") public var unsignedCharValue: UInt8 { get{ return self.numberValue.unsignedCharValue } } @available(*, unavailable, renamed="int16") public var short: Int16? { get{ return self.number?.shortValue } } @available(*, unavailable, renamed="int16Value") public var shortValue: Int16 { get{ return self.numberValue.shortValue } } @available(*, unavailable, renamed="uInt16") public var unsignedShort: UInt16? { get{ return self.number?.unsignedShortValue } } @available(*, unavailable, renamed="uInt16Value") public var unsignedShortValue: UInt16 { get{ return self.numberValue.unsignedShortValue } } @available(*, unavailable, renamed="int") public var long: Int? { get{ return self.number?.longValue } } @available(*, unavailable, renamed="intValue") public var longValue: Int { get{ return self.numberValue.longValue } } @available(*, unavailable, renamed="uInt") public var unsignedLong: UInt? { get{ return self.number?.unsignedLongValue } } @available(*, unavailable, renamed="uIntValue") public var unsignedLongValue: UInt { get{ return self.numberValue.unsignedLongValue } } @available(*, unavailable, renamed="int64") public var longLong: Int64? { get{ return self.number?.longLongValue } } @available(*, unavailable, renamed="int64Value") public var longLongValue: Int64 { get{ return self.numberValue.longLongValue } } @available(*, unavailable, renamed="uInt64") public var unsignedLongLong: UInt64? { get{ return self.number?.unsignedLongLongValue } } @available(*, unavailable, renamed="uInt64Value") public var unsignedLongLongValue: UInt64 { get{ return self.numberValue.unsignedLongLongValue } } @available(*, unavailable, renamed="int") public var integer: Int? { get { return self.number?.integerValue } } @available(*, unavailable, renamed="intValue") public var integerValue: Int { get { return self.numberValue.integerValue } } @available(*, unavailable, renamed="uInt") public var unsignedInteger: UInt? { get { return self.number?.unsignedIntegerValue } } @available(*, unavailable, renamed="uIntValue") public var unsignedIntegerValue: UInt { get { return self.numberValue.unsignedIntegerValue } } }
mit
29f13a283108671d2c62f5f881c6f4cf
25.523704
264
0.527634
4.711447
false
false
false
false
brentdax/swift
test/Reflection/typeref_decoding_objc.swift
6
2410
// RUN: %empty-directory(%t) // RUN: %target-build-swift %S/Inputs/ObjectiveCTypes.swift -parse-as-library -emit-module -emit-library -module-name TypesToReflect -o %t/libTypesToReflect.%target-dylib-extension // RUN: %target-swift-reflection-dump -binary-filename %t/libTypesToReflect.%target-dylib-extension | %FileCheck %s --check-prefix=CHECK-%target-ptrsize --check-prefix=CHECK // REQUIRES: objc_interop // Disable asan builds until we build swift-reflection-dump and the reflection library with the same compile: rdar://problem/30406870 // REQUIRES: no_asan // CHECK: FIELDS: // CHECK: ======= // CHECK: TypesToReflect.OC // CHECK: ----------------- // CHECK: nsObject: __C.NSObject // CHECK: (class __C.NSObject) // CHECK: nsString: __C.NSString // CHECK: (class __C.NSString) // CHECK: cfString: __C.CFStringRef // CHECK: (alias __C.CFStringRef) // CHECK: aBlock: @convention(block) () -> () // CHECK: (function convention=block // CHECK: (tuple)) // CHECK: ocnss: TypesToReflect.GenericOC<__C.NSString> // CHECK: (bound_generic_class TypesToReflect.GenericOC // CHECK: (class __C.NSString)) // CHECK: occfs: TypesToReflect.GenericOC<__C.CFStringRef> // CHECK: (bound_generic_class TypesToReflect.GenericOC // CHECK: (alias __C.CFStringRef)) // CHECK: TypesToReflect.GenericOC // CHECK: ------------------------ // CHECK: TypesToReflect.HasObjCClasses // CHECK: ----------------------------- // CHECK: url: __C.NSURL // CHECK: (class __C.NSURL) // CHECK: integer: Swift.Int // CHECK: (struct Swift.Int) // CHECK: rect: __C.CGRect // CHECK: (struct __C.CGRect) // CHECK: TypesToReflect.OP // CHECK: ----------------- // CHECK: __C.NSBundle // CHECK: ---------- // CHECK: __C.NSURL // CHECK: --------- // CHECK: __C.NSCoding // CHECK: ------------ // CHECK: ASSOCIATED TYPES: // CHECK: ================= // CHECK: BUILTIN TYPES: // CHECK: ============== // CHECK-32: - __C.CGRect: // CHECK-32: Size: 16 // CHECK-32: Alignment: 4 // CHECK-32: Stride: 16 // CHECK-32: NumExtraInhabitants: 0 // CHECK-64: - __C.CGRect: // CHECK-64: Size: 32 // CHECK-64: Alignment: 8 // CHECK-64: Stride: 32 // CHECK-64: NumExtraInhabitants: 0 // CHECK: CAPTURE DESCRIPTORS: // CHECK-NEXT: ==================== // CHECK: - Capture types: // CHECK-NEXT: (class __C.NSBundle) // CHECK-NEXT: (protocol_composition // CHECK-NEXT: (protocol __C.NSCoding)) // CHECK-NEXT: - Metadata sources:
apache-2.0
ac8c769e0cbcd7734e654092a3829a82
28.036145
180
0.628216
3.41844
false
false
false
false
bre7/FBAnnotationClusteringSwift
Source/FBClusteringManager.swift
1
6378
// // FBClusteringManager.swift // FBAnnotationClusteringSwift // // Created by Robert Chen on 4/2/15. // Copyright (c) 2015 Robert Chen. All rights reserved. // import Foundation import MapKit protocol FBClusteringManagerDelegate { func cellSizeFactorForCoordinator(coordinator:FBClusteringManager) -> CGFloat } public class FBClusteringManager { var delegate:FBClusteringManagerDelegate? = .None var tree:FBQuadTree? = .None var lock:NSRecursiveLock = NSRecursiveLock() let cellSize: Int? let userLocationAnnotationType: AnyClass public init(userAnnotationType: AnyClass = MKUserLocation.self, clusteringCellSize: Int? = .None){ cellSize = clusteringCellSize userLocationAnnotationType = userAnnotationType } public func setAnnotations(annotations:[MKAnnotation]){ tree = nil addAnnotations(annotations) } public func addAnnotations(annotations:[MKAnnotation]){ if tree == nil { tree = FBQuadTree() } lock.lock() for annotation in annotations { tree!.insertAnnotation(annotation) } lock.unlock() } public func clusteredAnnotationsWithinMapRect(rect:MKMapRect, withZoomScale zoomScale:Double) -> [MKAnnotation]{ let clusterCellSize = cellSize ?? FBClusteringManager.FBCellSizeForZoomScale(MKZoomScale(zoomScale)) // if delegate?.respondsToSelector("cellSizeFactorForCoordinator:") { // cellSize *= delegate.cellSizeFactorForCoordinator(self) // } let scaleFactor:Double = zoomScale / Double(clusterCellSize) let minX:Int = Int(floor(MKMapRectGetMinX(rect) * scaleFactor)) let maxX:Int = Int(floor(MKMapRectGetMaxX(rect) * scaleFactor)) let minY:Int = Int(floor(MKMapRectGetMinY(rect) * scaleFactor)) let maxY:Int = Int(floor(MKMapRectGetMaxY(rect) * scaleFactor)) var clusteredAnnotations = [MKAnnotation]() lock.lock() for i in minX...maxX { for j in minY...maxY { let mapPoint = MKMapPoint(x: Double(i)/scaleFactor, y: Double(j)/scaleFactor) let mapSize = MKMapSize(width: 1.0/scaleFactor, height: 1.0/scaleFactor) let mapRect = MKMapRect(origin: mapPoint, size: mapSize) let mapBox:FBBoundingBox = FBQuadTreeNode.FBBoundingBoxForMapRect(mapRect) var totalLatitude:Double = 0 var totalLongitude:Double = 0 var annotations = [MKAnnotation]() tree?.enumerateAnnotationsInBox(mapBox){ obj in totalLatitude += obj.coordinate.latitude totalLongitude += obj.coordinate.longitude annotations.append(obj) } let count = annotations.count if count == 1 { clusteredAnnotations += annotations } if count > 1 { let coordinate = CLLocationCoordinate2D( latitude: CLLocationDegrees(totalLatitude)/CLLocationDegrees(count), longitude: CLLocationDegrees(totalLongitude)/CLLocationDegrees(count) ) var cluster = FBAnnotationCluster() cluster.coordinate = coordinate cluster.annotations = annotations #if DEBUG println("cluster.annotations.count:: \(cluster.annotations.count)") #endif clusteredAnnotations.append(cluster) } } } lock.unlock() return clusteredAnnotations } public func allAnnotations() -> [MKAnnotation] { var annotations = [MKAnnotation]() lock.lock() tree?.enumerateAnnotationsUsingBlock(){ obj in annotations.append(obj) } lock.unlock() return annotations } public func displayAnnotations(annotations: [MKAnnotation], onMapView mapView:MKMapView){ dispatch_async(dispatch_get_main_queue()) { let annotationsExceptUserLocation = mapView.annotations .filter({ !($0.isKindOfClass(self.userLocationAnnotationType)) }) let before = NSSet(array: annotationsExceptUserLocation) let after = NSSet(array: annotations) let toKeep = NSMutableSet(set: before) toKeep.intersectSet(after as Set<NSObject>) let toAdd = NSMutableSet(set: after) toAdd.minusSet(toKeep as Set<NSObject>) let toRemove = NSMutableSet(set: before) toRemove.minusSet(after as Set<NSObject>) mapView.addAnnotations(toAdd.allObjects as! [MKAnnotation]) mapView.removeAnnotations(toRemove.allObjects as! [MKAnnotation]) } } class func FBZoomScaleToZoomLevel(scale:MKZoomScale) -> Int{ let totalTilesAtMaxZoom:Double = MKMapSizeWorld.width / 256.0 let zoomLevelAtMaxZoom:Int = Int(log2(totalTilesAtMaxZoom)) let floorLog2ScaleFloat = floor(log2f(Float(scale))) + 0.5 let sum:Int = zoomLevelAtMaxZoom + Int(floorLog2ScaleFloat) let zoomLevel:Int = max(0, sum) return zoomLevel; } class func FBCellSizeForZoomScale(zoomScale:MKZoomScale) -> Int { let zoomLevel:Int = FBClusteringManager.FBZoomScaleToZoomLevel(zoomScale) #if DEBUG println("FBCellSizeForZoomScale: \(zoomLevel)") #endif switch zoomLevel { case 12: return 96 case 13: return 64 case 14: return 64 case 15: return 64 case 16: return 32 case 17: return 32 case 18: return 32 case 19: return 16 default: return 128 } } }
mit
592238164573c5a610e8f7b858dafa24
33.290323
116
0.566635
5.405085
false
false
false
false
colemancda/SwiftyRegex
Source/Regex.swift
1
3420
import Darwin /// POSIX Regular Expression wrapper structure. public struct Regex { typealias CMatch = regmatch_t typealias CRegex = regex_t public var expression: String public var flags: Flags public init(_ expression: String, flags: Flags = [.Extended]) { self.expression = expression self.flags = flags } /// Returns compiled expression func compile() -> CRegex { var cRegex = CRegex() let result = regcomp(&cRegex, expression, flags.rawValue) if result != 0 { var buffer = [Int8](count: 128, repeatedValue: 0) regerror(result, &cRegex, &buffer, sizeof(buffer.dynamicType)) print("@Regex.compile() - Compilation error { \(String(bytes: buffer)) }") } return cRegex } /// Checks if given string matches expression. /// - returns: /// * isMatching - true if string matches expression /// * range - first matching substring range func match(string: String) -> (matches: Bool, range: Range<Int>?) { var cMatches = [CMatch()] var cRegex = compile() defer { regfree(&cRegex) } let result = regexec(&cRegex, string, 1, &cMatches, 0) if result == 0 { // String matching let s = Int(cMatches.first!.rm_so) let e = Int(cMatches.first!.rm_eo) return (true, s..<e) } else if result == REG_NOMATCH { // String not matching return (false, nil) } else { var buffer = [Int8](count: 128, repeatedValue: 0) regerror(result, &cRegex, &buffer, sizeof(buffer.dynamicType)) print("@Regex.match() - Execution error { \(String(bytes: buffer)) }") return (false, nil) } } /// - returns: Matching substring ranges. public func ranges(var string: String) -> [Range<Int>] { var ranges = [Range<Int>]() var offset = 0 while var range = match(string).range { // Delete match from string string.replaceRange(range, with: "") range.startIndex += offset range.endIndex += offset ranges.append(range) offset += range.endIndex - range.startIndex } return ranges } /// - returns: Matching substrings. public func matches(string: String) -> [String] { var matches = [String]() for r in ranges(string) { matches.append(string.substringWithRange(r)) } return matches } /// - returns: `string` with the first matching substring replaced by `sub`. public func replace(var string: String, with sub: String) -> String { let match = self.match(string) if match.matches == true && match.range != nil { string.replaceRange(match.range!, with: sub) } return string } /// - returns: `string` with all matching substrings replaced by `sub`. public func replaceAll(var string: String, with sub: String) -> String { for r in ranges(string) { string.replaceRange(r, with: sub) } return string } /// Checks if given string matches expression. public func test(string: String) -> Bool { return match(string).matches } }
mit
55ead1b2c4479ffa88fe0602412177d2
29.810811
86
0.55731
4.453125
false
false
false
false
orta/Quick
QuickTests/Fixtures/Person.swift
78
648
import Foundation class Person: NSObject { var isHappy = true var isHungry = false var isSatisfied = false var hopes = ["winning the lottery", "going on a blimp ride"] var smalltalk = "Come here often?" var valediction = "See you soon." var greeting: String { get { if isHappy { return "Hello!" } else { return "Oh, hi." } } } func eatChineseFood() { let after = dispatch_time(DISPATCH_TIME_NOW, 500000000) dispatch_after(after, dispatch_get_main_queue()) { self.isHungry = true } } }
apache-2.0
5e4b37368082c160a20e2147dd653139
23
64
0.532407
4.05
false
false
false
false
EZ-NET/ESSwim
Sources/Number/Digits.swift
1
1911
// // Digits.swift // ESSwim // // Created by Tomohiro Kumagai on 1/16/16. // // public struct ReverseDigitsGenerator<Number : UnsignedIntegerType> : GeneratorType { private var source: UIntMax? private var radix: UIntMax public init(source: Number, radix: UInt) { self.source = source.toUIntMax() self.radix = radix.toUIntMax() } public mutating func next() -> UInt? { switch self.source { case nil: return nil case let source? where source < radix: self.source = nil return UInt(source) case let source?: self.source = source / radix return UInt(source % radix) } } } public struct ReverseDigitsSequence<Number : UnsignedIntegerType> : SequenceType { private var generator: ReverseDigitsGenerator<Number> public init(source: Number, radix: UInt) { self.generator = ReverseDigitsGenerator(source: source, radix: radix) } public func generate() -> ReverseDigitsGenerator<Number> { return self.generator } } extension UnsignedIntegerType { public func digitsWithRadix(radix: UInt) -> [UInt] { return reverseDigitsWithRadix(radix).reverse() } public func reverseDigitsWithRadix(radix: UInt) -> [UInt] { return Array(ReverseDigitsSequence(source: self, radix: radix)) } public var decimalDigits: [UInt] { return digitsWithRadix(10) } public var reverseDecimalDigits: [UInt] { return reverseDigitsWithRadix(10) } public var binaryDigits: [UInt] { return digitsWithRadix(2) } public var reverseBinaryDigits: [UInt] { return reverseDigitsWithRadix(2) } public var octalDigits: [UInt] { return digitsWithRadix(8) } public var reverseOctalDigits: [UInt] { return reverseDigitsWithRadix(8) } public var hexadecimalDigits: [UInt] { return digitsWithRadix(16) } public var reverseHexadecimalDigits: [UInt] { return reverseDigitsWithRadix(16) } }
mit
f44d1032abdb3943a7c7735b69c66247
17.375
84
0.698064
3.532348
false
false
false
false
dasdom/StackViewExperiments
StackViewExperiments/ProfileWithStackView/ProfileView.swift
1
5277
// // ProfileView.swift // StackViewExperiments // // Created by dasdom on 12.06.15. // Copyright © 2015 Dominik Hauser. All rights reserved. // import UIKit private let socialButtonHeight: CGFloat = 30 private let socialButtonSpacing: CGFloat = 10 private let avatarImageHeight: CGFloat = 100 class ProfileWithStackView: UIView { let headerImageView: UIImageView let adnButton: UIButton let twitterButton: UIButton let stackOverflowButton: UIButton let githubButton: UIButton let avatarImageView: UIImageView let nameLabel: UILabel let handleLabel: UILabel let bioLabel: UILabel override init(frame: CGRect) { headerImageView = UIImageView(frame: CGRect.zeroRect) headerImageView.backgroundColor = UIColor.yellowColor() headerImageView.contentMode = .ScaleAspectFill func socialButtonWithWhite(white: CGFloat) -> UIButton { let button = UIButton(type: .Custom) button.backgroundColor = UIColor(white: white, alpha: 1.0) button.layer.cornerRadius = ceil(socialButtonHeight/2) return button } adnButton = socialButtonWithWhite(0.2) twitterButton = socialButtonWithWhite(0.3) stackOverflowButton = socialButtonWithWhite(0.4) githubButton = socialButtonWithWhite(0.5) avatarImageView = UIImageView(frame: CGRect.zeroRect) avatarImageView.backgroundColor = UIColor(white: 0.6, alpha: 1.0) avatarImageView.layer.cornerRadius = ceil(avatarImageHeight/2) avatarImageView.layer.borderColor = UIColor.grayColor().CGColor avatarImageView.layer.borderWidth = 2 avatarImageView.clipsToBounds = true avatarImageView.contentMode = .ScaleAspectFit nameLabel = UILabel(frame: CGRect.zeroRect) nameLabel.text = "Dominik Hauser" nameLabel.font = UIFont(name: "Avenir-Medium", size: 25) nameLabel.textColor = UIColor.whiteColor() handleLabel = UILabel(frame: CGRect.zeroRect) handleLabel.text = "dasdom" handleLabel.font = UIFont(name: "Avenir-Book", size: 18) handleLabel.textColor = UIColor.lightGrayColor() bioLabel = UILabel(frame: CGRect.zeroRect) bioLabel.text = "iOS dev durung the day. iOS dev at night. Father and husband all time. Auto Layout master. Swift lover" bioLabel.numberOfLines = 0 bioLabel.font = UIFont(name: "Avenir-Oblique", size: 13) bioLabel.textAlignment = .Center bioLabel.textColor = UIColor.lightGrayColor() // bioLabel.backgr oundColor = UIColor.yellowColor() super.init(frame: frame) backgroundColor = UIColor(red: 0.12, green: 0.12, blue: 0.14, alpha: 1.0) let socialButtonStackView = UIStackView(arrangedSubviews: [adnButton, twitterButton, stackOverflowButton, githubButton]) socialButtonStackView.axis = .Vertical socialButtonStackView.spacing = socialButtonSpacing socialButtonStackView.distribution = .FillEqually socialButtonStackView.alignment = .Center let headerStackView = UIStackView(arrangedSubviews: [headerImageView, socialButtonStackView]) headerStackView.spacing = -(socialButtonHeight+socialButtonSpacing*2) headerStackView.alignment = .Center let personInfoStackView = UIStackView(arrangedSubviews: [avatarImageView, nameLabel, handleLabel, bioLabel]) personInfoStackView.axis = .Vertical personInfoStackView.alignment = .Center personInfoStackView.spacing = 10 let mainStackView = UIStackView(arrangedSubviews: [headerStackView, personInfoStackView]) mainStackView.translatesAutoresizingMaskIntoConstraints = false mainStackView.axis = .Vertical mainStackView.alignment = .Center mainStackView.spacing = -ceil(avatarImageHeight/2) addSubview(mainStackView) // MARK: - Layout headerImageView.heightAnchor.constraintEqualToConstant(220).active = true socialButtonStackView.widthAnchor.constraintEqualToConstant(socialButtonHeight+socialButtonSpacing*2).active = true let numberOfSocialButtons = CGFloat(socialButtonStackView.arrangedSubviews.count) let socialButtonStackViewHeight = numberOfSocialButtons * socialButtonHeight + (numberOfSocialButtons - 1) * socialButtonSpacing socialButtonStackView.heightAnchor.constraintEqualToConstant(socialButtonStackViewHeight).active = true avatarImageView.widthAnchor.constraintEqualToConstant(avatarImageHeight).active = true avatarImageView.heightAnchor.constraintEqualToConstant(avatarImageHeight).active = true let views = ["stackView": mainStackView, "headerStackView": headerStackView, "bio": bioLabel] NSLayoutConstraint.activateConstraints(NSLayoutConstraint.constraintsWithVisualFormat("|[headerStackView]|", options: [], metrics: nil, views: views)) NSLayoutConstraint.activateConstraints(NSLayoutConstraint.constraintsWithVisualFormat("|-10-[bio]", options: [], metrics: nil, views: views)) NSLayoutConstraint.activateConstraints(NSLayoutConstraint.constraintsWithVisualFormat("|[stackView]|", options: [], metrics: nil, views: views)) NSLayoutConstraint.activateConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|[stackView]", options: [], metrics: nil, views: views)) } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
mit
83ea851ecb2a5b1144f93d410494b615
41.548387
154
0.758529
5.203156
false
false
false
false
itsaboutcode/WordPress-iOS
WordPress/Classes/Utility/PushNotificationsManager.swift
1
17844
import Foundation import WordPressShared import UserNotifications import CocoaLumberjack import UserNotifications /// The purpose of this helper is to encapsulate all the tasks related to Push Notifications Registration + Handling, /// including iOS "Actionable" Notifications. /// final public class PushNotificationsManager: NSObject { /// Returns the shared PushNotificationsManager instance. /// @objc static let shared = PushNotificationsManager() /// Stores the Apple's Push Notifications Token /// @objc var deviceToken: String? { get { return UserDefaults.standard.string(forKey: Device.tokenKey) ?? String() } set { UserDefaults.standard.set(newValue, forKey: Device.tokenKey) } } /// Stores the WordPress.com Device identifier /// @objc var deviceId: String? { get { return UserDefaults.standard.string(forKey: Device.idKey) ?? String() } set { UserDefaults.standard.set(newValue, forKey: Device.idKey) } } /// Returns the SharedApplication instance. This is meant for Unit Testing purposes. /// @objc var sharedApplication: UIApplication { return UIApplication.shared } /// Returns the Application Execution State. This is meant for Unit Testing purposes. /// @objc var applicationState: UIApplication.State { return sharedApplication.applicationState } /// Registers the device for Remote Notifications: Badge + Sounds + Alerts /// @objc func registerForRemoteNotifications() { sharedApplication.registerForRemoteNotifications() } /// Checks asynchronously if Notifications are enabled in the Device's Settings, or not. /// @objc func loadAuthorizationStatus(completion: @escaping ((_ authorized: UNAuthorizationStatus) -> Void)) { UNUserNotificationCenter.current().getNotificationSettings { settings in DispatchQueue.main.async { completion(settings.authorizationStatus) } } } // MARK: - Token Setup /// Registers the Device Token agains WordPress.com backend, if there's a default account. /// /// - Note: Support will also be initialized. The token will be persisted across App Sessions. /// @objc func registerDeviceToken(_ tokenData: Data) { // Don't bother registering for WordPress anything if the user isn't logged in guard AccountHelper.isDotcomAvailable() else { return } // Token Cleanup let newToken = tokenData.hexString // Register device with Zendesk ZendeskUtils.setNeedToRegisterDevice(newToken) if deviceToken != newToken { DDLogInfo("Device Token has changed! OLD Value: \(String(describing: deviceToken)), NEW value: \(newToken)") } else { DDLogInfo("Device Token received in didRegisterForRemoteNotificationsWithDeviceToken: \(newToken)") } deviceToken = newToken // Register against WordPress.com let noteService = NotificationSettingsService(managedObjectContext: ContextManager.sharedInstance().mainContext) noteService.registerDeviceForPushNotifications(newToken, success: { deviceId in DDLogVerbose("Successfully registered Device ID \(deviceId) for Push Notifications") self.deviceId = deviceId }, failure: { error in DDLogError("Unable to register Device for Push Notifications: \(error)") }) } /// Perform cleanup when the registration for iOS notifications failed /// /// - Parameter error: Details the reason of failure /// @objc func registrationDidFail(_ error: NSError) { DDLogError("Failed to register for push notifications: \(error)") unregisterDeviceToken() } /// Unregister the device from WordPress.com notifications /// @objc func unregisterDeviceToken() { // It's possible for the unregister server call to fail, so always unregister the device locally // to fix https://github.com/wordpress-mobile/WordPress-iOS/issues/11779. if UIApplication.shared.isRegisteredForRemoteNotifications { UIApplication.shared.unregisterForRemoteNotifications() } guard let knownDeviceId = deviceId else { return } ZendeskUtils.unregisterDevice() let noteService = NotificationSettingsService(managedObjectContext: ContextManager.sharedInstance().mainContext) noteService.unregisterDeviceForPushNotifications(knownDeviceId, success: { DDLogInfo("Successfully unregistered Device ID \(knownDeviceId) for Push Notifications!") self.deviceToken = nil self.deviceId = nil }, failure: { error in DDLogError("Unable to unregister push for Device ID \(knownDeviceId): \(error)") }) } // MARK: - Handling Notifications /// Handles a Remote Notification /// /// - Parameters: /// - userInfo: The Notification's Payload /// - userInteraction: Indicates if the user interacted with the Push Notification /// - completionHandler: A callback, to be executed on completion /// @objc func handleNotification(_ userInfo: NSDictionary, userInteraction: Bool = false, completionHandler: ((UIBackgroundFetchResult) -> Void)?) { DDLogVerbose("Received push notification:\nPayload: \(userInfo)\n") DDLogVerbose("Current Application state: \(applicationState.rawValue)") // Badge: Update if let badgeCountNumber = userInfo.number(forKeyPath: Notification.badgePath)?.intValue { sharedApplication.applicationIconBadgeNumber = badgeCountNumber } // Badge: Reset guard let type = userInfo.string(forKey: Notification.typeKey), type != Notification.badgeResetValue else { return } // Analytics trackNotification(with: userInfo) // Handling! let handlers = [handleSupportNotification, handleAuthenticationNotification, handleInactiveNotification, handleBackgroundNotification, handleQuickStartLocalNotification] for handler in handlers { if handler(userInfo, userInteraction, completionHandler) { break } } } /// Tracks a Notification Event /// /// - Parameter userInfo: The Notification's Payload /// func trackNotification(with userInfo: NSDictionary) { var properties = [String: String]() if let noteId = userInfo.number(forKey: Notification.identifierKey) { properties[Tracking.identifierKey] = noteId.stringValue } if let type = userInfo.string(forKey: Notification.typeKey) { properties[Tracking.typeKey] = type } if let theToken = deviceToken { properties[Tracking.tokenKey] = theToken } let event: WPAnalyticsStat = (applicationState == .background) ? .pushNotificationReceived : .pushNotificationAlertPressed WPAnalytics.track(event, withProperties: properties) } } // MARK: - Handlers: Should be private, but... are open due to Unit Testing requirements! // extension PushNotificationsManager { /// Handles a Support Remote Notification /// /// - Note: This should actually be *private*. BUT: for unit testing purposes (within ObjC code, because of OCMock), /// we'll temporarily keep it as public. Sorry. /// /// - Parameters: /// - userInfo: The Notification's Payload /// - completionHandler: A callback, to be executed on completion /// /// - Returns: True when handled. False otherwise /// @objc func handleSupportNotification(_ userInfo: NSDictionary, userInteraction: Bool, completionHandler: ((UIBackgroundFetchResult) -> Void)?) -> Bool { guard let type = userInfo.string(forKey: ZendeskUtils.PushNotificationIdentifiers.key), type == ZendeskUtils.PushNotificationIdentifiers.type else { return false } DispatchQueue.main.async { ZendeskUtils.pushNotificationReceived() } WPAnalytics.track(.supportReceivedResponseFromSupport) if applicationState == .background { WPTabBarController.sharedInstance().showMeScene() } completionHandler?(.newData) return true } /// Handles a WordPress.com Push Authentication Notification /// /// - Note: This should actually be *private*. BUT: for unit testing purposes (within ObjC code, because of OCMock), /// we'll temporarily keep it as public. Sorry. /// /// - Parameters: /// - userInfo: The Notification's Payload /// - completionHandler: A callback, to be executed on completion /// /// - Returns: True when handled. False otherwise /// @objc func handleAuthenticationNotification(_ userInfo: NSDictionary, userInteraction: Bool, completionHandler: ((UIBackgroundFetchResult) -> Void)?) -> Bool { // WordPress.com Push Authentication Notification // Due to the Background Notifications entitlement, any given Push Notification's userInfo might be received // while the app is in BG, and when it's about to become active. In order to prevent UI glitches, let's skip // notifications when in BG mode. Still, we don't wanna relay that BG notification! // let authenticationManager = PushAuthenticationManager() guard authenticationManager.isAuthenticationNotification(userInfo) else { return false } /// This is a (hopefully temporary) workaround. A Push Authentication must be dealt with whenever: /// /// 1. When the user interacts with a Push Notification /// 2. When the App is in Foreground /// /// As per iOS 13 there are certain scenarios in which the `applicationState` may be `.background` when the user pressed over the Alert. /// By means of the `userInteraction` flag, we're just working around the new SDK behavior. /// /// Proper fix involves a full refactor, and definitely stop checking on `applicationState`, since it's not reliable anymore. /// if applicationState != .background || userInteraction { authenticationManager.handleAuthenticationNotification(userInfo) } else { DDLogInfo("Skipping handling authentication notification due to app being in background or user not interacting with it.") } completionHandler?(.newData) return true } /// A handler for a 2fa auth notification approval action. /// /// - Parameter userInfo: The Notification's Payload /// - Returns: True if successful. False otherwise. /// @objc func handleAuthenticationApprovedAction(_ userInfo: NSDictionary) -> Bool { let authenticationManager = PushAuthenticationManager() guard authenticationManager.isAuthenticationNotification(userInfo) else { return false } authenticationManager.handleAuthenticationApprovedAction(userInfo) return true } /// Handles a Notification while in Inactive Mode /// /// - Note: This should actually be *private*. BUT: for unit testing purposes (within ObjC code, because of OCMock), /// we'll temporarily keep it as public. Sorry. /// /// - Parameters: /// - userInfo: The Notification's Payload /// - completionHandler: A callback, to be executed on completion /// /// - Returns: True when handled. False otherwise /// @objc func handleInactiveNotification(_ userInfo: NSDictionary, userInteraction: Bool, completionHandler: ((UIBackgroundFetchResult) -> Void)?) -> Bool { guard applicationState == .inactive else { return false } guard let notificationId = userInfo.number(forKey: Notification.identifierKey)?.stringValue else { return false } WPTabBarController.sharedInstance().showNotificationsTabForNote(withID: notificationId) completionHandler?(.newData) return true } /// Handles a Notification while in Active OR Background Modes /// /// - Note: This should actually be *private*. BUT: for unit testing purposes (within ObjC code, because of OCMock), /// we'll temporarily keep it as public. Sorry. /// /// - Parameters: /// - userInfo: The Notification's Payload /// - completionHandler: A callback, to be executed on completion /// /// - Returns: True when handled. False otherwise /// @objc func handleBackgroundNotification(_ userInfo: NSDictionary, userInteraction: Bool, completionHandler: ((UIBackgroundFetchResult) -> Void)?) -> Bool { guard userInfo.number(forKey: Notification.identifierKey)?.stringValue != nil else { return false } guard applicationState == .background else { return false } guard let mediator = NotificationSyncMediator() else { completionHandler?(.failed) return true } DDLogInfo("Running Notifications Background Fetch...") mediator.sync { error, newData in DDLogInfo("Finished Notifications Background Fetch!") let result = newData ? UIBackgroundFetchResult.newData : .noData completionHandler?(result) } return true } } // MARK: - Nested Types // extension PushNotificationsManager { enum Device { static let tokenKey = "apnsDeviceToken" static let idKey = "notification_device_id" } enum Notification { static let badgePath = "aps.badge" static let identifierKey = "note_id" static let typeKey = "type" static let originKey = "origin" static let badgeResetValue = "badge-reset" static let local = "qs-local-notification" } enum Tracking { static let identifierKey = "push_notification_note_id" static let typeKey = "push_notification_type" static let tokenKey = "push_notification_token" } } // MARK: - Quick Start notifications extension PushNotificationsManager { /// Handles a Quick Start Local Notification /// /// - Note: This should actually be *private*. BUT: for unit testing purposes (within ObjC code, because of OCMock), /// we'll temporarily keep it as public. Sorry. /// /// - Parameters: /// - userInfo: The Notification's Payload /// - completionHandler: A callback, to be executed on completion /// /// - Returns: True when handled. False otherwise @objc func handleQuickStartLocalNotification(_ userInfo: NSDictionary, userInteraction: Bool, completionHandler: ((UIBackgroundFetchResult) -> Void)?) -> Bool { guard let type = userInfo.string(forKey: Notification.typeKey), type == Notification.local else { return false } if WPTabBarController.sharedInstance()?.presentedViewController != nil { WPTabBarController.sharedInstance()?.dismiss(animated: false) } WPTabBarController.sharedInstance()?.showMySitesTab() if let taskName = userInfo.string(forKey: QuickStartTracking.taskNameKey) { WPAnalytics.track(.quickStartNotificationTapped, withProperties: [QuickStartTracking.taskNameKey: taskName]) } completionHandler?(.newData) return true } func postNotification(for tour: QuickStartTour) { deletePendingLocalNotifications() let content = UNMutableNotificationContent() content.title = tour.title content.body = tour.description content.sound = UNNotificationSound.default content.userInfo = [Notification.typeKey: Notification.local, QuickStartTracking.taskNameKey: tour.analyticsKey] guard let futureDate = Calendar.current.date(byAdding: .day, value: Constants.localNotificationIntervalInDays, to: Date()) else { return } let trigger = UNCalendarNotificationTrigger(dateMatching: futureDate.components, repeats: false) let request = UNNotificationRequest(identifier: Constants.localNotificationIdentifier, content: content, trigger: trigger) UNUserNotificationCenter.current().add(request) WPAnalytics.track(.quickStartNotificationStarted, withProperties: [QuickStartTracking.taskNameKey: tour.analyticsKey]) } @objc func deletePendingLocalNotifications() { UNUserNotificationCenter.current().removePendingNotificationRequests(withIdentifiers: [Constants.localNotificationIdentifier]) } private enum Constants { static let localNotificationIntervalInDays = 2 static let localNotificationIdentifier = "QuickStartTourNotificationIdentifier" } private enum QuickStartTracking { static let taskNameKey = "task_name" } } private extension Date { var components: DateComponents { return Calendar.current.dateComponents([.year, .month, .day, .hour, .minute, .second], from: self) } }
gpl-2.0
1c741c251821160d58fb58d2df4b5f2d
35.867769
164
0.646716
5.595484
false
false
false
false
itsaboutcode/WordPress-iOS
WordPress/Classes/Services/PushAuthenticationService.swift
1
2257
import Foundation /// The purpose of this service is to encapsulate the Restful API that performs Mobile 2FA /// Code Verification. /// @objc open class PushAuthenticationService: LocalCoreDataService { @objc open var authenticationServiceRemote: PushAuthenticationServiceRemote? /// Designated Initializer /// /// - Parameter managedObjectContext: A Reference to the MOC that should be used to interact with /// the Core Data Persistent Store. /// public required override init(managedObjectContext: NSManagedObjectContext) { super.init(managedObjectContext: managedObjectContext) self.authenticationServiceRemote = PushAuthenticationServiceRemote(wordPressComRestApi: apiForRequest()) } /// Authorizes a WordPress.com Login Attempt (2FA Protected Accounts) /// /// - Parameters: /// - token: The Token sent over by the backend, via Push Notifications. /// - completion: The completion block to be executed when the remote call finishes. /// @objc open func authorizeLogin(_ token: String, completion: @escaping ((Bool) -> ())) { if self.authenticationServiceRemote == nil { return } self.authenticationServiceRemote!.authorizeLogin(token, success: { completion(true) }, failure: { completion(false) }) } /// Helper method to get the WordPress.com REST Api, if any /// /// - Returns: WordPressComRestApi instance. It can be an anonymous API instance if there are no credentials. /// fileprivate func apiForRequest() -> WordPressComRestApi { var api: WordPressComRestApi? = nil let accountService = AccountService(managedObjectContext: managedObjectContext) if let unwrappedRestApi = accountService.defaultWordPressComAccount()?.wordPressComRestApi { if unwrappedRestApi.hasCredentials() { api = unwrappedRestApi } } if api == nil { api = WordPressComRestApi.anonymousApi(userAgent: WPUserAgent.wordPress()) } return api! } }
gpl-2.0
bdae5b05377bb2cc701706d20bf1cf39
34.825397
114
0.633584
5.877604
false
false
false
false
abertelrud/swift-package-manager
Sources/XCBuildSupport/PIF.swift
2
51480
//===----------------------------------------------------------------------===// // // This source file is part of the Swift open source project // // Copyright (c) 2014-2020 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// import Basics import Foundation import TSCBasic import PackageModel /// The Project Interchange Format (PIF) is a structured representation of the /// project model created by clients (Xcode/SwiftPM) to send to XCBuild. /// /// The PIF is a representation of the project model describing the static /// objects which contribute to building products from the project, independent /// of "how" the user has chosen to build those products in any particular /// build. This information can be cached by XCBuild between builds (even /// between builds which use different schemes or configurations), and can be /// incrementally updated by clients when something changes. public enum PIF { /// This is used as part of the signature for the high-level PIF objects, to ensure that changes to the PIF schema /// are represented by the objects which do not use a content-based signature scheme (workspaces and projects, /// currently). static let schemaVersion = 11 /// The type used for identifying PIF objects. public typealias GUID = String /// The top-level PIF object. public struct TopLevelObject: Encodable { public let workspace: PIF.Workspace public init(workspace: PIF.Workspace) { self.workspace = workspace } public func encode(to encoder: Encoder) throws { var container = encoder.unkeyedContainer() // Encode the workspace. try container.encode(workspace) // Encode the projects and their targets. for project in workspace.projects { try container.encode(project) for target in project.targets { try container.encode(target) } } } } public class TypedObject: Codable { class var type: String { fatalError("\(self) missing implementation") } let type: String? fileprivate init() { type = Swift.type(of: self).type } private enum CodingKeys: CodingKey { case type } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) try container.encode(Swift.type(of: self).type, forKey: .type) } required public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) type = try container.decode(String.self, forKey: .type) } } public final class Workspace: TypedObject { override class var type: String { "workspace" } public let guid: GUID public var name: String public var path: AbsolutePath public var projects: [Project] var signature: String? public init(guid: GUID, name: String, path: AbsolutePath, projects: [Project]) { precondition(!guid.isEmpty) precondition(!name.isEmpty) precondition(Set(projects.map({ $0.guid })).count == projects.count) self.guid = guid self.name = name self.path = path self.projects = projects super.init() } private enum CodingKeys: CodingKey { case guid, name, path, projects, signature } public override func encode(to encoder: Encoder) throws { try super.encode(to: encoder) var container = encoder.container(keyedBy: StringKey.self) var contents = container.nestedContainer(keyedBy: CodingKeys.self, forKey: "contents") try contents.encode("\(guid)@\(schemaVersion)", forKey: .guid) try contents.encode(name, forKey: .name) try contents.encode(path, forKey: .path) if encoder.userInfo.keys.contains(.encodeForXCBuild) { guard let signature = self.signature else { throw InternalError("Expected to have workspace signature when encoding for XCBuild") } try container.encode(signature, forKey: "signature") try contents.encode(projects.map({ $0.signature }), forKey: .projects) } else { try contents.encode(projects, forKey: .projects) } } public required init(from decoder: Decoder) throws { let superContainer = try decoder.container(keyedBy: StringKey.self) let container = try superContainer.nestedContainer(keyedBy: CodingKeys.self, forKey: "contents") let guidString = try container.decode(GUID.self, forKey: .guid) self.guid = String(guidString.dropLast("\(schemaVersion)".count + 1)) self.name = try container.decode(String.self, forKey: .name) self.path = try container.decode(AbsolutePath.self, forKey: .path) self.projects = try container.decode([Project].self, forKey: .projects) try super.init(from: decoder) } } /// A PIF project, consisting of a tree of groups and file references, a list of targets, and some additional /// information. public final class Project: TypedObject { override class var type: String { "project" } public let guid: GUID public var name: String public var path: AbsolutePath public var projectDirectory: AbsolutePath public var developmentRegion: String public var buildConfigurations: [BuildConfiguration] public var targets: [BaseTarget] public var groupTree: Group var signature: String? public init( guid: GUID, name: String, path: AbsolutePath, projectDirectory: AbsolutePath, developmentRegion: String, buildConfigurations: [BuildConfiguration], targets: [BaseTarget], groupTree: Group ) { precondition(!guid.isEmpty) precondition(!name.isEmpty) precondition(!developmentRegion.isEmpty) precondition(Set(targets.map({ $0.guid })).count == targets.count) precondition(Set(buildConfigurations.map({ $0.guid })).count == buildConfigurations.count) self.guid = guid self.name = name self.path = path self.projectDirectory = projectDirectory self.developmentRegion = developmentRegion self.buildConfigurations = buildConfigurations self.targets = targets self.groupTree = groupTree super.init() } private enum CodingKeys: CodingKey { case guid, projectName, projectIsPackage, path, projectDirectory, developmentRegion, defaultConfigurationName, buildConfigurations, targets, groupTree, signature } public override func encode(to encoder: Encoder) throws { try super.encode(to: encoder) var container = encoder.container(keyedBy: StringKey.self) var contents = container.nestedContainer(keyedBy: CodingKeys.self, forKey: "contents") try contents.encode("\(guid)@\(schemaVersion)", forKey: .guid) try contents.encode(name, forKey: .projectName) try contents.encode("true", forKey: .projectIsPackage) try contents.encode(path, forKey: .path) try contents.encode(projectDirectory, forKey: .projectDirectory) try contents.encode(developmentRegion, forKey: .developmentRegion) try contents.encode("Release", forKey: .defaultConfigurationName) try contents.encode(buildConfigurations, forKey: .buildConfigurations) if encoder.userInfo.keys.contains(.encodeForXCBuild) { guard let signature = self.signature else { throw InternalError("Expected to have project signature when encoding for XCBuild") } try container.encode(signature, forKey: "signature") try contents.encode(targets.map{ $0.signature }, forKey: .targets) } else { try contents.encode(targets, forKey: .targets) } try contents.encode(groupTree, forKey: .groupTree) } public required init(from decoder: Decoder) throws { let superContainer = try decoder.container(keyedBy: StringKey.self) let container = try superContainer.nestedContainer(keyedBy: CodingKeys.self, forKey: "contents") let guidString = try container.decode(GUID.self, forKey: .guid) self.guid = String(guidString.dropLast("\(schemaVersion)".count + 1)) self.name = try container.decode(String.self, forKey: .projectName) self.path = try container.decode(AbsolutePath.self, forKey: .path) self.projectDirectory = try container.decode(AbsolutePath.self, forKey: .projectDirectory) self.developmentRegion = try container.decode(String.self, forKey: .developmentRegion) self.buildConfigurations = try container.decode([BuildConfiguration].self, forKey: .buildConfigurations) let untypedTargets = try container.decode([UntypedTarget].self, forKey: .targets) var targetContainer = try container.nestedUnkeyedContainer(forKey: .targets) self.targets = try untypedTargets.map { target in let type = target.contents.type switch type { case "aggregate": return try targetContainer.decode(AggregateTarget.self) case "standard", "packageProduct": return try targetContainer.decode(Target.self) default: throw InternalError("unknown target type \(type)") } } self.groupTree = try container.decode(Group.self, forKey: .groupTree) try super.init(from: decoder) } } /// Abstract base class for all items in the group hierarchy. public class Reference: TypedObject { /// Determines the base path for a reference's relative path. public enum SourceTree: String, Codable { /// Indicates that the path is relative to the source root (i.e. the "project directory"). case sourceRoot = "SOURCE_ROOT" /// Indicates that the path is relative to the path of the parent group. case group = "<group>" /// Indicates that the path is relative to the effective build directory (which varies depending on active /// scheme, active run destination, or even an overridden build setting. case builtProductsDir = "BUILT_PRODUCTS_DIR" /// Indicates that the path is an absolute path. case absolute = "<absolute>" } public let guid: GUID /// Relative path of the reference. It is usually a literal, but may in fact contain build settings. public var path: String /// Determines the base path for the reference's relative path. public var sourceTree: SourceTree /// Name of the reference, if different from the last path component (if not set, the last path component will /// be used as the name). public var name: String? fileprivate init( guid: GUID, path: String, sourceTree: SourceTree, name: String? ) { precondition(!guid.isEmpty) precondition(!(name?.isEmpty ?? false)) self.guid = guid self.path = path self.sourceTree = sourceTree self.name = name super.init() } private enum CodingKeys: CodingKey { case guid, sourceTree, path, name, type } public override func encode(to encoder: Encoder) throws { try super.encode(to: encoder) var container = encoder.container(keyedBy: CodingKeys.self) try container.encode(guid, forKey: .guid) try container.encode(sourceTree, forKey: .sourceTree) try container.encode(path, forKey: .path) try container.encode(name ?? path, forKey: .name) } public required init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) self.guid = try container.decode(String.self, forKey: .guid) self.sourceTree = try container.decode(SourceTree.self, forKey: .sourceTree) self.path = try container.decode(String.self, forKey: .path) self.name = try container.decodeIfPresent(String.self, forKey: .name) try super.init(from: decoder) } } /// A reference to a file system entity (a file, folder, etc). public final class FileReference: Reference { override class var type: String { "file" } public var fileType: String public init( guid: GUID, path: String, sourceTree: SourceTree = .group, name: String? = nil, fileType: String? = nil ) { self.fileType = fileType ?? FileReference.fileTypeIdentifier(forPath: path) super.init(guid: guid, path: path, sourceTree: sourceTree, name: name) } private enum CodingKeys: CodingKey { case fileType } public override func encode(to encoder: Encoder) throws { try super.encode(to: encoder) var container = encoder.container(keyedBy: CodingKeys.self) try container.encode(fileType, forKey: .fileType) } public required init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) self.fileType = try container.decode(String.self, forKey: .fileType) try super.init(from: decoder) } } /// A group that can contain References (FileReferences and other Groups). The resolved path of a group is used as /// the base path for any child references whose source tree type is GroupRelative. public final class Group: Reference { override class var type: String { "group" } public var children: [Reference] public init( guid: GUID, path: String, sourceTree: SourceTree = .group, name: String? = nil, children: [Reference] ) { precondition( Set(children.map({ $0.guid })).count == children.count, "multiple group children with the same guid: \(children.map({ $0.guid }))" ) self.children = children super.init(guid: guid, path: path, sourceTree: sourceTree, name: name) } private enum CodingKeys: CodingKey { case children, type } public override func encode(to encoder: Encoder) throws { try super.encode(to: encoder) var container = encoder.container(keyedBy: CodingKeys.self) try container.encode(children, forKey: .children) } public required init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) let untypedChildren = try container.decode([TypedObject].self, forKey: .children) var childrenContainer = try container.nestedUnkeyedContainer(forKey: .children) self.children = try untypedChildren.map { child in switch child.type { case Group.type: return try childrenContainer.decode(Group.self) case FileReference.type: return try childrenContainer.decode(FileReference.self) default: throw InternalError("unknown reference type \(child.type ?? "<nil>")") } } try super.init(from: decoder) } } /// Represents a dependency on another target (identified by its PIF GUID). public struct TargetDependency: Codable { /// Identifier of depended-upon target. public var targetGUID: String /// The platform filters for this target dependency. public var platformFilters: [PlatformFilter] public init(targetGUID: String, platformFilters: [PlatformFilter] = []) { self.targetGUID = targetGUID self.platformFilters = platformFilters } private enum CodingKeys: CodingKey { case guid, platformFilters } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) try container.encode("\(targetGUID)@\(schemaVersion)", forKey: .guid) if !platformFilters.isEmpty { try container.encode(platformFilters, forKey: .platformFilters) } } public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) let targetGUIDString = try container.decode(String.self, forKey: .guid) self.targetGUID = String(targetGUIDString.dropLast("\(schemaVersion)".count + 1)) platformFilters = try container.decodeIfPresent([PlatformFilter].self, forKey: .platformFilters) ?? [] } } public class BaseTarget: TypedObject { class override var type: String { "target" } public let guid: GUID public var name: String public var buildConfigurations: [BuildConfiguration] public var buildPhases: [BuildPhase] public var dependencies: [TargetDependency] public var impartedBuildProperties: ImpartedBuildProperties var signature: String? fileprivate init( guid: GUID, name: String, buildConfigurations: [BuildConfiguration], buildPhases: [BuildPhase], dependencies: [TargetDependency], impartedBuildSettings: PIF.BuildSettings, signature: String? ) { self.guid = guid self.name = name self.buildConfigurations = buildConfigurations self.buildPhases = buildPhases self.dependencies = dependencies impartedBuildProperties = ImpartedBuildProperties(settings: impartedBuildSettings) self.signature = signature super.init() } public required init(from decoder: Decoder) throws { throw InternalError("init(from:) has not been implemented") } } public final class AggregateTarget: BaseTarget { public init( guid: GUID, name: String, buildConfigurations: [BuildConfiguration], buildPhases: [BuildPhase], dependencies: [TargetDependency], impartedBuildSettings: PIF.BuildSettings ) { super.init( guid: guid, name: name, buildConfigurations: buildConfigurations, buildPhases: buildPhases, dependencies: dependencies, impartedBuildSettings: impartedBuildSettings, signature: nil ) } private enum CodingKeys: CodingKey { case type, guid, name, buildConfigurations, buildPhases, dependencies, impartedBuildProperties, signature } public override func encode(to encoder: Encoder) throws { try super.encode(to: encoder) var container = encoder.container(keyedBy: StringKey.self) var contents = container.nestedContainer(keyedBy: CodingKeys.self, forKey: "contents") try contents.encode("aggregate", forKey: .type) try contents.encode("\(guid)@\(schemaVersion)", forKey: .guid) try contents.encode(name, forKey: .name) try contents.encode(buildConfigurations, forKey: .buildConfigurations) try contents.encode(buildPhases, forKey: .buildPhases) try contents.encode(dependencies, forKey: .dependencies) try contents.encode(impartedBuildProperties, forKey: .impartedBuildProperties) if encoder.userInfo.keys.contains(.encodeForXCBuild) { guard let signature = self.signature else { throw InternalError("Expected to have \(Swift.type(of: self)) signature when encoding for XCBuild") } try container.encode(signature, forKey: "signature") } } public required init(from decoder: Decoder) throws { let superContainer = try decoder.container(keyedBy: StringKey.self) let container = try superContainer.nestedContainer(keyedBy: CodingKeys.self, forKey: "contents") let guidString = try container.decode(GUID.self, forKey: .guid) let guid = String(guidString.dropLast("\(schemaVersion)".count + 1)) let name = try container.decode(String.self, forKey: .name) let buildConfigurations = try container.decode([BuildConfiguration].self, forKey: .buildConfigurations) let untypedBuildPhases = try container.decode([TypedObject].self, forKey: .buildPhases) var buildPhasesContainer = try container.nestedUnkeyedContainer(forKey: .buildPhases) let buildPhases: [BuildPhase] = try untypedBuildPhases.map { guard let type = $0.type else { throw InternalError("Expected type in build phase \($0)") } return try BuildPhase.decode(container: &buildPhasesContainer, type: type) } let dependencies = try container.decode([TargetDependency].self, forKey: .dependencies) let impartedBuildProperties = try container.decode(BuildSettings.self, forKey: .impartedBuildProperties) super.init( guid: guid, name: name, buildConfigurations: buildConfigurations, buildPhases: buildPhases, dependencies: dependencies, impartedBuildSettings: impartedBuildProperties, signature: nil ) } } /// An Xcode target, representing a single entity to build. public final class Target: BaseTarget { public enum ProductType: String, Codable { case application = "com.apple.product-type.application" case staticArchive = "com.apple.product-type.library.static" case objectFile = "com.apple.product-type.objfile" case dynamicLibrary = "com.apple.product-type.library.dynamic" case framework = "com.apple.product-type.framework" case executable = "com.apple.product-type.tool" case unitTest = "com.apple.product-type.bundle.unit-test" case bundle = "com.apple.product-type.bundle" case packageProduct = "packageProduct" } public var productName: String public var productType: ProductType public init( guid: GUID, name: String, productType: ProductType, productName: String, buildConfigurations: [BuildConfiguration], buildPhases: [BuildPhase], dependencies: [TargetDependency], impartedBuildSettings: PIF.BuildSettings ) { self.productType = productType self.productName = productName super.init( guid: guid, name: name, buildConfigurations: buildConfigurations, buildPhases: buildPhases, dependencies: dependencies, impartedBuildSettings: impartedBuildSettings, signature: nil ) } private enum CodingKeys: CodingKey { case guid, name, dependencies, buildConfigurations, type, frameworksBuildPhase, productTypeIdentifier, productReference, buildRules, buildPhases, impartedBuildProperties, signature } override public func encode(to encoder: Encoder) throws { try super.encode(to: encoder) var container = encoder.container(keyedBy: StringKey.self) var contents = container.nestedContainer(keyedBy: CodingKeys.self, forKey: "contents") try contents.encode("\(guid)@\(schemaVersion)", forKey: .guid) try contents.encode(name, forKey: .name) try contents.encode(dependencies, forKey: .dependencies) try contents.encode(buildConfigurations, forKey: .buildConfigurations) if encoder.userInfo.keys.contains(.encodeForXCBuild) { guard let signature = self.signature else { throw InternalError("Expected to have \(Swift.type(of: self)) signature when encoding for XCBuild") } try container.encode(signature, forKey: "signature") } if productType == .packageProduct { try contents.encode("packageProduct", forKey: .type) // Add the framework build phase, if present. if let phase = buildPhases.first as? PIF.FrameworksBuildPhase { try contents.encode(phase, forKey: .frameworksBuildPhase) } } else { try contents.encode("standard", forKey: .type) try contents.encode(productType, forKey: .productTypeIdentifier) let productReference = [ "type": "file", "guid": "PRODUCTREF-\(guid)", "name": productName, ] try contents.encode(productReference, forKey: .productReference) try contents.encode([String](), forKey: .buildRules) try contents.encode(buildPhases, forKey: .buildPhases) try contents.encode(impartedBuildProperties, forKey: .impartedBuildProperties) } } public required init(from decoder: Decoder) throws { let superContainer = try decoder.container(keyedBy: StringKey.self) let container = try superContainer.nestedContainer(keyedBy: CodingKeys.self, forKey: "contents") let guidString = try container.decode(GUID.self, forKey: .guid) let guid = String(guidString.dropLast("\(schemaVersion)".count + 1)) let name = try container.decode(String.self, forKey: .name) let buildConfigurations = try container.decode([BuildConfiguration].self, forKey: .buildConfigurations) let dependencies = try container.decode([TargetDependency].self, forKey: .dependencies) let type = try container.decode(String.self, forKey: .type) let buildPhases: [BuildPhase] let impartedBuildProperties: BuildSettings if type == "packageProduct" { self.productType = .packageProduct self.productName = "" let fwkBuildPhase = try container.decodeIfPresent(FrameworksBuildPhase.self, forKey: .frameworksBuildPhase) buildPhases = fwkBuildPhase.map{ [$0] } ?? [] impartedBuildProperties = BuildSettings() } else if type == "standard" { self.productType = try container.decode(ProductType.self, forKey: .productTypeIdentifier) let productReference = try container.decode([String: String].self, forKey: .productReference) self.productName = productReference["name"]! let untypedBuildPhases = try container.decodeIfPresent([TypedObject].self, forKey: .buildPhases) ?? [] var buildPhasesContainer = try container.nestedUnkeyedContainer(forKey: .buildPhases) buildPhases = try untypedBuildPhases.map { guard let type = $0.type else { throw InternalError("Expected type in build phase \($0)") } return try BuildPhase.decode(container: &buildPhasesContainer, type: type) } impartedBuildProperties = try container.decode(BuildSettings.self, forKey: .impartedBuildProperties) } else { throw InternalError("Unhandled target type \(type)") } super.init( guid: guid, name: name, buildConfigurations: buildConfigurations, buildPhases: buildPhases, dependencies: dependencies, impartedBuildSettings: impartedBuildProperties, signature: nil ) } } /// Abstract base class for all build phases in a target. public class BuildPhase: TypedObject { static func decode(container: inout UnkeyedDecodingContainer, type: String) throws -> BuildPhase { switch type { case HeadersBuildPhase.type: return try container.decode(HeadersBuildPhase.self) case SourcesBuildPhase.type: return try container.decode(SourcesBuildPhase.self) case FrameworksBuildPhase.type: return try container.decode(FrameworksBuildPhase.self) case ResourcesBuildPhase.type: return try container.decode(ResourcesBuildPhase.self) default: throw InternalError("unknown build phase \(type)") } } public let guid: GUID public var buildFiles: [BuildFile] public init(guid: GUID, buildFiles: [BuildFile]) { precondition(!guid.isEmpty) self.guid = guid self.buildFiles = buildFiles super.init() } private enum CodingKeys: CodingKey { case guid, buildFiles } public override func encode(to encoder: Encoder) throws { try super.encode(to: encoder) var container = encoder.container(keyedBy: CodingKeys.self) try container.encode(guid, forKey: .guid) try container.encode(buildFiles, forKey: .buildFiles) } public required init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) self.guid = try container.decode(GUID.self, forKey: .guid) self.buildFiles = try container.decode([BuildFile].self, forKey: .buildFiles) try super.init(from: decoder) } } /// A "headers" build phase, i.e. one that copies headers into a directory of the product, after suitable /// processing. public final class HeadersBuildPhase: BuildPhase { override class var type: String { "com.apple.buildphase.headers" } } /// A "sources" build phase, i.e. one that compiles sources and provides them to be linked into the executable code /// of the product. public final class SourcesBuildPhase: BuildPhase { override class var type: String { "com.apple.buildphase.sources" } } /// A "frameworks" build phase, i.e. one that links compiled code and libraries into the executable of the product. public final class FrameworksBuildPhase: BuildPhase { override class var type: String { "com.apple.buildphase.frameworks" } } public final class ResourcesBuildPhase: BuildPhase { override class var type: String { "com.apple.buildphase.resources" } } /// A build file, representing the membership of either a file or target product reference in a build phase. public struct BuildFile: Codable { public enum Reference { case file(guid: PIF.GUID) case target(guid: PIF.GUID) } public enum HeaderVisibility: String, Codable { case `public` = "public" case `private` = "private" } public let guid: GUID public var reference: Reference public var headerVisibility: HeaderVisibility? = nil public var platformFilters: [PlatformFilter] public init(guid: GUID, file: FileReference, platformFilters: [PlatformFilter]) { self.guid = guid self.reference = .file(guid: file.guid) self.platformFilters = platformFilters } public init(guid: GUID, fileGUID: PIF.GUID, platformFilters: [PlatformFilter]) { self.guid = guid self.reference = .file(guid: fileGUID) self.platformFilters = platformFilters } public init(guid: GUID, target: PIF.BaseTarget, platformFilters: [PlatformFilter]) { self.guid = guid self.reference = .target(guid: target.guid) self.platformFilters = platformFilters } public init(guid: GUID, targetGUID: PIF.GUID, platformFilters: [PlatformFilter]) { self.guid = guid self.reference = .target(guid: targetGUID) self.platformFilters = platformFilters } public init(guid: GUID, reference: Reference, platformFilters: [PlatformFilter]) { self.guid = guid self.reference = reference self.platformFilters = platformFilters } private enum CodingKeys: CodingKey { case guid, platformFilters, fileReference, targetReference } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) try container.encode(guid, forKey: .guid) try container.encode(platformFilters, forKey: .platformFilters) switch self.reference { case .file(let fileGUID): try container.encode(fileGUID, forKey: .fileReference) case .target(let targetGUID): try container.encode("\(targetGUID)@\(schemaVersion)", forKey: .targetReference) } } public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) guid = try container.decode(GUID.self, forKey: .guid) platformFilters = try container.decode([PlatformFilter].self, forKey: .platformFilters) if container.allKeys.contains(.fileReference) { reference = try .file(guid: container.decode(GUID.self, forKey: .fileReference)) } else if container.allKeys.contains(.targetReference) { let targetGUIDString = try container.decode(GUID.self, forKey: .targetReference) let targetGUID = String(targetGUIDString.dropLast("\(schemaVersion)".count + 1)) reference = .target(guid: targetGUID) } else { throw InternalError("Expected \(CodingKeys.fileReference) or \(CodingKeys.targetReference) in the keys") } } } /// Represents a generic platform filter. public struct PlatformFilter: Codable, Equatable { /// The name of the platform (`LC_BUILD_VERSION`). /// /// Example: macos, ios, watchos, tvos. public var platform: String /// The name of the environment (`LC_BUILD_VERSION`) /// /// Example: simulator, maccatalyst. public var environment: String public init(platform: String, environment: String = "") { self.platform = platform self.environment = environment } } /// A build configuration, which is a named collection of build settings. public struct BuildConfiguration: Codable { public let guid: GUID public var name: String public var buildSettings: BuildSettings public init(guid: GUID, name: String, buildSettings: BuildSettings) { precondition(!guid.isEmpty) precondition(!name.isEmpty) self.guid = guid self.name = name self.buildSettings = buildSettings } } public struct ImpartedBuildProperties: Codable { public var buildSettings: BuildSettings public init(settings: BuildSettings) { self.buildSettings = settings } } /// A set of build settings, which is represented as a struct of optional build settings. This is not optimally /// efficient, but it is great for code completion and type-checking. public struct BuildSettings: Codable { public enum SingleValueSetting: String, Codable { case APPLICATION_EXTENSION_API_ONLY case BUILT_PRODUCTS_DIR case CLANG_CXX_LANGUAGE_STANDARD case CLANG_ENABLE_MODULES case CLANG_ENABLE_OBJC_ARC case CODE_SIGNING_REQUIRED case CODE_SIGN_IDENTITY case COMBINE_HIDPI_IMAGES case COPY_PHASE_STRIP case DEBUG_INFORMATION_FORMAT case DEFINES_MODULE case DRIVERKIT_DEPLOYMENT_TARGET case DYLIB_INSTALL_NAME_BASE case EMBEDDED_CONTENT_CONTAINS_SWIFT case ENABLE_NS_ASSERTIONS case ENABLE_TESTABILITY case ENABLE_TESTING_SEARCH_PATHS case ENTITLEMENTS_REQUIRED case EXECUTABLE_NAME case GENERATE_INFOPLIST_FILE case GCC_C_LANGUAGE_STANDARD case GCC_OPTIMIZATION_LEVEL case GENERATE_MASTER_OBJECT_FILE case INFOPLIST_FILE case IPHONEOS_DEPLOYMENT_TARGET case KEEP_PRIVATE_EXTERNS case CLANG_COVERAGE_MAPPING_LINKER_ARGS case MACH_O_TYPE case MACOSX_DEPLOYMENT_TARGET case MODULEMAP_FILE case MODULEMAP_FILE_CONTENTS case MODULEMAP_PATH case MODULE_CACHE_DIR case ONLY_ACTIVE_ARCH case PACKAGE_RESOURCE_BUNDLE_NAME case PACKAGE_RESOURCE_TARGET_KIND case PRODUCT_BUNDLE_IDENTIFIER case PRODUCT_MODULE_NAME case PRODUCT_NAME case PROJECT_NAME case SDKROOT case SDK_VARIANT case SKIP_INSTALL case INSTALL_PATH case SUPPORTS_MACCATALYST case SWIFT_SERIALIZE_DEBUGGING_OPTIONS case SWIFT_FORCE_STATIC_LINK_STDLIB case SWIFT_FORCE_DYNAMIC_LINK_STDLIB case SWIFT_INSTALL_OBJC_HEADER case SWIFT_OBJC_INTERFACE_HEADER_NAME case SWIFT_OBJC_INTERFACE_HEADER_DIR case SWIFT_OPTIMIZATION_LEVEL case SWIFT_VERSION case TARGET_NAME case TARGET_BUILD_DIR case TVOS_DEPLOYMENT_TARGET case USE_HEADERMAP case USES_SWIFTPM_UNSAFE_FLAGS case WATCHOS_DEPLOYMENT_TARGET case MARKETING_VERSION case CURRENT_PROJECT_VERSION case SWIFT_EMIT_MODULE_INTERFACE } public enum MultipleValueSetting: String, Codable { case EMBED_PACKAGE_RESOURCE_BUNDLE_NAMES case FRAMEWORK_SEARCH_PATHS case GCC_PREPROCESSOR_DEFINITIONS case HEADER_SEARCH_PATHS case LD_RUNPATH_SEARCH_PATHS case LIBRARY_SEARCH_PATHS case OTHER_CFLAGS case OTHER_CPLUSPLUSFLAGS case OTHER_LDFLAGS case OTHER_LDRFLAGS case OTHER_SWIFT_FLAGS case PRELINK_FLAGS case SPECIALIZATION_SDK_OPTIONS case SUPPORTED_PLATFORMS case SWIFT_ACTIVE_COMPILATION_CONDITIONS case SWIFT_MODULE_ALIASES } public enum Platform: String, CaseIterable, Codable { case macOS = "macos" case macCatalyst = "maccatalyst" case iOS = "ios" case tvOS = "tvos" case watchOS = "watchos" case driverKit = "driverkit" case linux public var packageModelPlatform: PackageModel.Platform { switch self { case .macOS: return .macOS case .macCatalyst: return .macCatalyst case .iOS: return .iOS case .tvOS: return .tvOS case .watchOS: return .watchOS case .driverKit: return .driverKit case .linux: return .linux } } public var conditions: [String] { let filters = [PlatformsCondition(platforms: [packageModelPlatform])].toPlatformFilters().map { (filter: PIF.PlatformFilter) -> String in if filter.environment.isEmpty { return filter.platform } else { return "\(filter.platform)-\(filter.environment)" } }.sorted() return ["__platform_filter=\(filters.joined(separator: ";"))"] } } public private(set) var platformSpecificSingleValueSettings = [Platform: [SingleValueSetting: String]]() public private(set) var platformSpecificMultipleValueSettings = [Platform: [MultipleValueSetting: [String]]]() public private(set) var singleValueSettings: [SingleValueSetting: String] = [:] public private(set) var multipleValueSettings: [MultipleValueSetting: [String]] = [:] public subscript(_ setting: SingleValueSetting) -> String? { get { singleValueSettings[setting] } set { singleValueSettings[setting] = newValue } } public subscript(_ setting: SingleValueSetting, for platform: Platform) -> String? { get { platformSpecificSingleValueSettings[platform]?[setting] } set { platformSpecificSingleValueSettings[platform, default: [:]][setting] = newValue } } public subscript(_ setting: SingleValueSetting, default defaultValue: @autoclosure () -> String) -> String { get { singleValueSettings[setting, default: defaultValue()] } set { singleValueSettings[setting] = newValue } } public subscript(_ setting: MultipleValueSetting) -> [String]? { get { multipleValueSettings[setting] } set { multipleValueSettings[setting] = newValue } } public subscript(_ setting: MultipleValueSetting, for platform: Platform) -> [String]? { get { platformSpecificMultipleValueSettings[platform]?[setting] } set { platformSpecificMultipleValueSettings[platform, default: [:]][setting] = newValue } } public subscript( _ setting: MultipleValueSetting, default defaultValue: @autoclosure () -> [String] ) -> [String] { get { multipleValueSettings[setting, default: defaultValue()] } set { multipleValueSettings[setting] = newValue } } public subscript( _ setting: MultipleValueSetting, for platform: Platform, default defaultValue: @autoclosure () -> [String] ) -> [String] { get { platformSpecificMultipleValueSettings[platform, default: [:]][setting, default: defaultValue()] } set { platformSpecificMultipleValueSettings[platform, default: [:]][setting] = newValue } } public init() { } private enum CodingKeys: CodingKey { case platformSpecificSingleValueSettings, platformSpecificMultipleValueSettings, singleValueSettings, multipleValueSettings } public func encode(to encoder: Encoder) throws { if encoder.userInfo.keys.contains(.encodeForXCBuild) { return try encodeForXCBuild(to: encoder) } var container = encoder.container(keyedBy: CodingKeys.self) try container.encode(platformSpecificSingleValueSettings, forKey: .platformSpecificSingleValueSettings) try container.encode(platformSpecificMultipleValueSettings, forKey: .platformSpecificMultipleValueSettings) try container.encode(singleValueSettings, forKey: .singleValueSettings) try container.encode(multipleValueSettings, forKey: .multipleValueSettings) } private func encodeForXCBuild(to encoder: Encoder) throws { var container = encoder.container(keyedBy: StringKey.self) for (key, value) in singleValueSettings { try container.encode(value, forKey: StringKey(key.rawValue)) } for (key, value) in multipleValueSettings { try container.encode(value, forKey: StringKey(key.rawValue)) } for (platform, values) in platformSpecificSingleValueSettings { for condition in platform.conditions { for (key, value) in values { try container.encode(value, forKey: "\(key.rawValue)[\(condition)]") } } } for (platform, values) in platformSpecificMultipleValueSettings { for condition in platform.conditions { for (key, value) in values { try container.encode(value, forKey: "\(key.rawValue)[\(condition)]") } } } } public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) platformSpecificSingleValueSettings = try container.decodeIfPresent([Platform: [SingleValueSetting: String]].self, forKey: .platformSpecificSingleValueSettings) ?? .init() platformSpecificMultipleValueSettings = try container.decodeIfPresent([Platform: [MultipleValueSetting: [String]]].self, forKey: .platformSpecificMultipleValueSettings) ?? .init() singleValueSettings = try container.decodeIfPresent([SingleValueSetting: String].self, forKey: .singleValueSettings) ?? [:] multipleValueSettings = try container.decodeIfPresent([MultipleValueSetting: [String]] .self, forKey: .multipleValueSettings) ?? [:] } } } /// Represents a filetype recognized by the Xcode build system. public struct XCBuildFileType: CaseIterable { public static let xcdatamodeld: XCBuildFileType = XCBuildFileType( fileType: "xcdatamodeld", fileTypeIdentifier: "wrapper.xcdatamodeld" ) public static let xcdatamodel: XCBuildFileType = XCBuildFileType( fileType: "xcdatamodel", fileTypeIdentifier: "wrapper.xcdatamodel" ) public static let xcmappingmodel: XCBuildFileType = XCBuildFileType( fileType: "xcmappingmodel", fileTypeIdentifier: "wrapper.xcmappingmodel" ) public static let allCases: [XCBuildFileType] = [ .xcdatamodeld, .xcdatamodel, .xcmappingmodel, ] public let fileTypes: Set<String> public let fileTypeIdentifier: String private init(fileTypes: Set<String>, fileTypeIdentifier: String) { self.fileTypes = fileTypes self.fileTypeIdentifier = fileTypeIdentifier } private init(fileType: String, fileTypeIdentifier: String) { self.init(fileTypes: [fileType], fileTypeIdentifier: fileTypeIdentifier) } } struct StringKey: CodingKey, ExpressibleByStringInterpolation { var stringValue: String var intValue: Int? init(stringLiteral stringValue: String) { self.stringValue = stringValue } init(stringValue value: String) { self.stringValue = value } init(_ value: String) { self.stringValue = value } init?(intValue: Int) { assertionFailure("does not support integer keys") return nil } } extension PIF.FileReference { fileprivate static func fileTypeIdentifier(forPath path: String) -> String { let pathExtension: String? if let path = try? AbsolutePath(validating: path) { pathExtension = path.extension } else if let path = try? RelativePath(validating: path) { pathExtension = path.extension } else { pathExtension = nil } switch pathExtension { case "a": return "archive.ar" case "s", "S": return "sourcecode.asm" case "c": return "sourcecode.c.c" case "cl": return "sourcecode.opencl" case "cpp", "cp", "cxx", "cc", "c++", "C", "tcc": return "sourcecode.cpp.cpp" case "d": return "sourcecode.dtrace" case "defs", "mig": return "sourcecode.mig" case "m": return "sourcecode.c.objc" case "mm", "M": return "sourcecode.cpp.objcpp" case "metal": return "sourcecode.metal" case "l", "lm", "lmm", "lpp", "lp", "lxx": return "sourcecode.lex" case "swift": return "sourcecode.swift" case "y", "ym", "ymm", "ypp", "yp", "yxx": return "sourcecode.yacc" case "xcassets": return "folder.assetcatalog" case "storyboard": return "file.storyboard" case "xib": return "file.xib" case "xcframework": return "wrapper.xcframework" default: return pathExtension.flatMap({ pathExtension in XCBuildFileType.allCases.first(where:{ $0.fileTypes.contains(pathExtension) }) })?.fileTypeIdentifier ?? "file" } } } extension CodingUserInfoKey { public static let encodingPIFSignature: CodingUserInfoKey = CodingUserInfoKey(rawValue: "encodingPIFSignature")! /// Perform the encoding for XCBuild consumption. public static let encodeForXCBuild: CodingUserInfoKey = CodingUserInfoKey(rawValue: "encodeForXCBuild")! } private struct UntypedTarget: Decodable { struct TargetContents: Decodable { let type: String } let contents: TargetContents } protocol PIFSignableObject: AnyObject { var signature: String? { get set } } extension PIF.Workspace: PIFSignableObject {} extension PIF.Project: PIFSignableObject {} extension PIF.BaseTarget: PIFSignableObject {} extension PIF { /// Add signature to workspace and its subobjects. public static func sign(_ workspace: PIF.Workspace) throws { let encoder = JSONEncoder.makeWithDefaults() func sign<T: PIFSignableObject & Encodable>(_ obj: T) throws { let signatureContent = try encoder.encode(obj) let bytes = ByteString(signatureContent) obj.signature = bytes.sha256Checksum } let projects = workspace.projects try projects.flatMap{ $0.targets }.forEach(sign) try projects.forEach(sign) try sign(workspace) } }
apache-2.0
968a774d997ff6e12315af5cb4dc2b7a
39.824742
192
0.61082
5.069923
false
false
false
false
dymx101/Gamers
Gamers/Models/Comment.swift
1
2332
// // Comment.swift // Gamers // // Created by 虚空之翼 on 15/8/3. // Copyright (c) 2015年 Freedom. All rights reserved. // import Foundation import RealmSwift import SwiftyJSON class Comment: Object { dynamic var id = "" //ID dynamic var title = "" //标题 dynamic var content = "" //内容 dynamic var data = CommentData() dynamic var videoId = "" //视频ID dynamic var userId = "" //评论人ID dynamic var userName = "" //评论人名称 class func collection(#json: JSON) -> [Comment] { var collection = [Comment]() if let items = json.array { for item in items { collection.append(Comment.modelFromJSON(item)) } } return collection } // 把JSON数据转换为对象 class func modelFromJSON(json: JSON) -> Comment { let model = Comment() if let id = json["id"].string { model.id = id } if let title = json["title"].string { model.title = title } if let content = json["content"].string { model.content = content } //if let data = json["data"].string { model.data = data } if let videoId = json["videoid"].string { model.videoId = videoId } if let userId = json["userid"].string { model.userId = userId } if let userName = json["username"].string { model.userName = userName } model.data = CommentData.collection(json: json["data"]) return model } } class CommentData: Object { dynamic var avatar = "" dynamic var dataPosted = "" dynamic var nextPageToken = "" //分页下个标识 class func collection(#json: JSON) -> CommentData { return CommentData.modelFromJSON(json) } // 把JSON数据转换为对象 class func modelFromJSON(json: JSON) -> CommentData { let model = CommentData() if let avatar = json["avatar"].string { model.avatar = avatar } if let dataPosted = json["date_posted"].string { model.dataPosted = dataPosted } if let nextPageToken = json["next_page_token"].string { model.nextPageToken = nextPageToken } return model } }
apache-2.0
1c9203bfff98e7f69a8df370e1e8bd6c
28.233766
101
0.558222
4.343629
false
false
false
false
itsaboutcode/WordPress-iOS
WordPress/Classes/ViewRelated/Me/App Settings/PrivacySettingsViewController.swift
1
9117
import Gridicons import UIKit import AutomatticTracks class PrivacySettingsViewController: UITableViewController { fileprivate var handler: ImmuTableViewHandler! override init(style: UITableView.Style) { super.init(style: style) navigationItem.title = NSLocalizedString("Privacy Settings", comment: "Privacy Settings Title") } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } required convenience init() { self.init(style: .grouped) } override func viewDidLoad() { super.viewDidLoad() ImmuTable.registerRows([ PaddedInfoRow.self, SwitchRow.self, PaddedLinkRow.self ], tableView: self.tableView) handler = ImmuTableViewHandler(takeOver: self) reloadViewModel() WPStyleGuide.configureColors(view: view, tableView: tableView) WPStyleGuide.configureAutomaticHeightRows(for: tableView) addAccountSettingsChangedObserver() } private func addAccountSettingsChangedObserver() { NotificationCenter.default.addObserver(self, selector: #selector(accountSettingsDidChange(_:)), name: NSNotification.Name.AccountSettingsChanged, object: nil) } @objc private func accountSettingsDidChange(_ notification: Notification) { reloadViewModel() } // MARK: - Model mapping fileprivate func reloadViewModel() { handler.viewModel = tableViewModel() } func tableViewModel() -> ImmuTable { let collectInformation = SwitchRow( title: NSLocalizedString("Collect information", comment: "Label for switch to turn on/off sending app usage data"), value: !WPAppAnalytics.userHasOptedOut(), icon: .gridicon(.stats), onChange: usageTrackingChanged ) let shareInfoText = PaddedInfoRow( title: NSLocalizedString("Share information with our analytics tool about your use of services while logged in to your WordPress.com account.", comment: "Informational text for Collect Information setting") ) let shareInfoLink = PaddedLinkRow( title: NSLocalizedString("Learn more", comment: "Link to cookie policy"), action: openCookiePolicy() ) let privacyText = PaddedInfoRow( title: NSLocalizedString("This information helps us improve our products, make marketing to you more relevant, personalize your WordPress.com experience, and more as detailed in our privacy policy.", comment: "Informational text for the privacy policy link") ) let privacyLink = PaddedLinkRow( title: NSLocalizedString("Read privacy policy", comment: "Link to privacy policy"), action: openPrivacyPolicy() ) let ccpaLink = PaddedLinkRow( title: NSLocalizedString("Privacy notice for California users", comment: "Link to the CCPA privacy notice for residents of California."), action: openCCPANotice() ) let otherTracking = PaddedInfoRow( title: NSLocalizedString("We use other tracking tools, including some from third parties. Read about these and how to control them.", comment: "Informational text about link to other tracking tools") ) let otherTrackingLink = PaddedLinkRow( title: NSLocalizedString("Learn more", comment: "Link to cookie policy"), action: openCookiePolicy() ) let reportCrashes = SwitchRow( title: NSLocalizedString("Crash reports", comment: "Label for switch to turn on/off sending crashes info"), value: !UserSettings.userHasOptedOutOfCrashLogging, icon: .gridicon(.bug), onChange: crashReportingChanged ) let reportCrashesInfoText = PaddedInfoRow( title: NSLocalizedString("To help us improve the app’s performance and fix the occasional bug, enable automatic crash reports.", comment: "Informational text for Report Crashes setting") ) return ImmuTable(sections: [ ImmuTableSection(rows: [ collectInformation, shareInfoText, shareInfoLink, privacyText, privacyLink, ccpaLink, otherTracking, otherTrackingLink ]), ImmuTableSection(rows: [ reportCrashes, reportCrashesInfoText ]) ]) } func usageTrackingChanged(_ enabled: Bool) { let appAnalytics = WordPressAppDelegate.shared?.analytics appAnalytics?.setUserHasOptedOut(!enabled) let accountService = AccountService(managedObjectContext: ContextManager.sharedInstance().mainContext) AccountSettingsHelper(accountService: accountService).updateTracksOptOutSetting(!enabled) } func openCookiePolicy() -> ImmuTableAction { return { [weak self] _ in self?.tableView.deselectSelectedRowWithAnimation(true) self?.displayWebView(WPAutomatticCookiesURL) } } func openPrivacyPolicy() -> ImmuTableAction { return { [weak self] _ in self?.tableView.deselectSelectedRowWithAnimation(true) self?.displayWebView(WPAutomatticPrivacyURL) } } func openCCPANotice() -> ImmuTableAction { return { [weak self] _ in self?.tableView.deselectSelectedRowWithAnimation(true) self?.displayWebView(WPAutomatticCCPAPrivacyNoticeURL) } } func displayWebView(_ urlString: String) { guard let url = URL(string: urlString) else { return } let webViewController = WebViewControllerFactory.controller(url: url) let navigation = UINavigationController(rootViewController: webViewController) present(navigation, animated: true) } func crashReportingChanged(_ enabled: Bool) { UserSettings.userHasOptedOutOfCrashLogging = !enabled WordPressAppDelegate.crashLogging?.setNeedsDataRefresh() } } private class InfoCell: WPTableViewCellDefault { override func layoutSubviews() { super.layoutSubviews() guard var imageFrame = imageView?.frame, let textLabel = textLabel, let textLabelFont = textLabel.font, let text = textLabel.text else { return } // Determine the smallest size of text constrained to the width of the label let size = CGSize(width: textLabel.bounds.width, height: .greatestFiniteMagnitude) // First a single line of text, so we can center against the first line of text let singleLineRect = "Text".boundingRect(with: size, options: [ .usesLineFragmentOrigin, .usesFontLeading], attributes: [NSAttributedString.Key.font: textLabelFont], context: nil) // And then the whole text, so we can calculate padding in the label above and below the text let textRect = text.boundingRect(with: size, options: [ .usesLineFragmentOrigin, .usesFontLeading], attributes: [NSAttributedString.Key.font: textLabelFont], context: nil) // Calculate the vertical padding in the label. // At very large accessibility sizing, the total rect size is coming out larger // than the label size. I'm unsure why, so we'll work around it by not allowing // values lower than zero. let padding = max(textLabel.bounds.height - textRect.height, 0) let topPadding = padding / 2.0 // Calculate the center point of the first line of text, and center the image against it let imageCenterX = imageFrame.size.height / 2.0 imageFrame.origin.y = floor(topPadding + singleLineRect.midY - imageCenterX) imageView?.frame = imageFrame } } private struct PaddedInfoRow: ImmuTableRow { static let cell = ImmuTableCell.class(InfoCell.self) let title: String let action: ImmuTableAction? = nil func configureCell(_ cell: UITableViewCell) { cell.textLabel?.text = title cell.textLabel?.numberOfLines = 10 cell.imageView?.image = UIImage(color: .clear, havingSize: Gridicon.defaultSize) cell.selectionStyle = .none WPStyleGuide.configureTableViewCell(cell) } } private struct PaddedLinkRow: ImmuTableRow { static let cell = ImmuTableCell.class(WPTableViewCellDefault.self) let title: String let action: ImmuTableAction? func configureCell(_ cell: UITableViewCell) { cell.textLabel?.text = title cell.imageView?.image = UIImage(color: .clear, havingSize: Gridicon.defaultSize) WPStyleGuide.configureTableViewActionCell(cell) cell.textLabel?.textColor = .primary } }
gpl-2.0
b7dd309a77909ee8745b73fbf036a891
37.787234
270
0.646846
5.399882
false
false
false
false
hooman/swift
test/IRGen/outlined_copy_addr.swift
13
2180
// RUN: %target-swift-frontend -disable-type-layout -emit-ir -module-name outcopyaddr -primary-file %s | %FileCheck %s public protocol BaseProt { } public protocol ChildProt: BaseProt { } public struct BaseStruct<T: BaseProt> { public typealias Element = T public var elem1: Element public var elem2: Element } public struct StructWithBaseStruct<T: BaseProt> { public typealias Element = T var elem1: Element var elem2: BaseStruct<Element> } // CHECK-LABEL: define hidden swiftcc void @"$s11outcopyaddr010StructWithbc4BaseB0V4elemAA0bcdB0VyxGvg"(%swift.opaque* noalias nocapture sret({{.*}}) %0, %swift.type* %"StructWithStructWithBaseStruct<T>", %T11outcopyaddr010StructWithbc4BaseB0V* noalias nocapture swiftself %1) // CHECK: call %T11outcopyaddr014StructWithBaseB0V.5* @"$s11outcopyaddr014StructWithBaseB0VyxGAA9ChildProtRzlWOc" public struct StructWithStructWithBaseStruct<T: ChildProt> { public typealias Element = T let elem: StructWithBaseStruct<Element> } protocol P { } class OtherPrivate<T> { } struct OtherInternal<T> { var myPrivate: OtherPrivate<T>? = nil } struct MyPrivate<T: P> { var otherHelper: OtherInternal<T>? = nil // CHECK-LABEL: define hidden swiftcc {{i32|i64}} @"$s11outcopyaddr9MyPrivateVyACyxGxcfC"(%swift.opaque* noalias nocapture %0, %swift.type* %T, i8** %T.P) {{.*}} { // CHECK: call %T11outcopyaddr9MyPrivateV* @"$s11outcopyaddr9MyPrivateVyxGAA1PRzlWOh"(%T11outcopyaddr9MyPrivateV* {{%.*}}) // CHECK: ret init(_: T) { } } extension P { func foo(data: Any) { _ = MyPrivate(data as! Self) } } enum GenericError<T: BaseProt> { case payload(T) } func testIt<P: BaseProt>(_ f: GenericError<P>?) { } func dontCrash<P: BaseProt>(_ f: GenericError<P>) { testIt(f) } protocol Baz : class { } extension Baz { static func crash(setup: ((Self) -> ())?){ } } class Foobar { public static func dontCrash() -> Baz? { let cls : Baz.Type = Foobar1.self // This used to crash because we tried to outline the optional consume with // an opened payload existential type. cls.crash(setup: { (arg: Baz) -> () in }) return nil } } class Foobar1 : Foobar, Baz { }
apache-2.0
8d1973d696cf536842f352ef06bdfc11
27.311688
276
0.701835
3.248882
false
false
false
false
wagnersouz4/replay
Replay/ReplayTests/Models/MovieTests.swift
1
2825
// // MovieTests.swift // Replay // // Created by Wagner Souza on 24/03/17. // Copyright © 2017 Wagner Souza. All rights reserved. // import Quick import Nimble @testable import Replay class MovieTests: QuickSpec { override func spec() { it("should create a Movie from a json object") { let genres = [["name": "Comedy"], ["name": "Adventure"]] let companies = [["name": "Walt Disney Pictures"], ["name": "Walt Disney Animation Studios"]] let countries = [["iso_3166_1": "US", "name": "United States of America"], ["iso_3166_1": "BR", "name": "Brazil"]] let languages = [["name": "English"], ["name": "Portuguese"]] let videos = [["key": "pjTDTmef5-c", "name": "Trailer", "site": "YouTube", "size": 480], ["key": "Sagg08DrO5U", "name": "Teaser", "site": "YouTube", "size": 360 ]] let images = [["file_path": "/imageA.jpg"], ["file_path": "/imageB.jpg"], ["file_path": "/imageC.jpg"]] let data: [String: Any] = ["genres": genres, "homepage": "http://www.google.com", "imdb_id": "tt0110912", "original_title": "Movie Title", "overview": "Lorem ipsum dolor sit amet, consectetur adipiscing elit.", "poster_path": "/poster.jpg", "production_companies": companies, "production_countries": countries, "release_date": "1995-02-18", "spoken_languages": languages, "videos": ["results": videos], "images": ["backdrops": images]] guard let movie = Movie(json: data) else { return fail() } expect(movie.genres.count) == genres.count expect(movie.companies.count) == companies.count expect(movie.contries[0].name) == "United States of America" expect(movie.spokenLanguages[0].name) == "English" expect(movie.videos.count) == videos.count expect(movie.backdropImages.count) == images.count expect(movie.homepage) == "http://www.google.com" expect(movie.imdbID) == "tt0110912" expect(movie.overview) == "Lorem ipsum dolor sit amet, consectetur adipiscing elit." expect(movie.posterPath) == "/poster.jpg" expect(movie.releaseDate) == "1995-02-18" } } }
mit
a853b8a4b312bae0bc0f9a1c2e8ecde2
43.125
110
0.467422
4.606852
false
false
false
false
SandcastleApps/partyup
Pods/SwiftDate/Sources/SwiftDate/NSDateComponents+SwiftDate.swift
1
9416
// // SwiftDate, an handy tool to manage date and timezones in swift // Created by: Daniele Margutti // Main contributors: Jeroen Houtzager // // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation //MARK: - Extension of Int To Manage Operations - public extension NSDateComponents { /** Create a new date from a specific date by adding self components - parameter refDate: reference date - parameter region: optional region to define the timezone and calendar. By default is local region - returns: a new NSDate instance */ public func fromDate(refDate: NSDate!, inRegion region: Region = Region.defaultRegion) -> NSDate { let date = region.calendar.dateByAddingComponents(self, toDate: refDate, options: NSCalendarOptions(rawValue: 0)) return date! } /** Create a new date from a specific date by subtracting self components - parameter refDate: reference date - parameter region: optional region to define the timezone and calendar. By default is local region - returns: a new NSDate instance */ public func agoFromDate(refDate: NSDate!, inRegion region: Region = Region.defaultRegion) -> NSDate { for unit in DateInRegion.componentFlagSet { let value = self.valueForComponent(unit) if value != NSDateComponentUndefined { self.setValue((value * -1), forComponent: unit) } } return region.calendar.dateByAddingComponents(self, toDate: refDate, options: NSCalendarOptions(rawValue: 0))! } /** Create a new date from current date and add self components. So you can make something like: let date = 4.days.fromNow() - parameter region: optional region to define the timezone and calendar. By default is local Region - returns: a new NSDate instance */ public func fromNow(inRegion region: Region = Region.defaultRegion) -> NSDate { return fromDate(NSDate(), inRegion: region) } /** Create a new date from current date and substract self components So you can make something like: let date = 5.hours.ago() - parameter region: optional region to define the timezone and calendar. By default is local Region - returns: a new NSDate instance */ public func ago(inRegion region: Region = Region.defaultRegion) -> NSDate { return agoFromDate(NSDate(), inRegion: region) } /// The same of calling fromNow() with default local region public var fromNow: NSDate { get { return fromDate(NSDate()) } } /// The same of calling ago() with default local region public var ago: NSDate { get { return agoFromDate(NSDate()) } } /// The dateInRegion for the current components public var dateInRegion: DateInRegion? { return DateInRegion(self) } } //MARK: - Combine NSDateComponents - public func | (lhs: NSDateComponents, rhs: NSDateComponents) -> NSDateComponents { let dc = NSDateComponents() for unit in DateInRegion.componentFlagSet { let lhs_value = lhs.valueForComponent(unit) let rhs_value = rhs.valueForComponent(unit) if lhs_value != NSDateComponentUndefined { dc.setValue(lhs_value, forComponent: unit) } if rhs_value != NSDateComponentUndefined { dc.setValue(rhs_value, forComponent: unit) } } return dc } /// Add date components to one another /// /// - parameters: /// - lhs: left hand side argument /// - rhs: right hand side argument /// /// - returns: date components lhs + rhs /// public func + (lhs: NSDateComponents, rhs: NSDateComponents) -> NSDateComponents { return sumDateComponents(lhs, rhs: rhs) } /// subtract date components from one another /// /// - parameters: /// - lhs: left hand side argument /// - rhs: right hand side argument /// /// - returns: date components lhs - rhs /// public func - (lhs: NSDateComponents, rhs: NSDateComponents) -> NSDateComponents { return sumDateComponents(lhs, rhs: rhs, sum: false) } /// Helper function for date component sum * subtract /// /// - parameters: /// - lhs: left hand side argument /// - rhs: right hand side argument /// - sum: indicates whether arguments should be added or subtracted /// /// - returns: date components lhs +/- rhs /// internal func sumDateComponents(lhs: NSDateComponents, rhs: NSDateComponents, sum: Bool = true) -> NSDateComponents { let newComponents = NSDateComponents() let components = DateInRegion.componentFlagSet for unit in components { let leftValue = lhs.valueForComponent(unit) let rightValue = rhs.valueForComponent(unit) guard leftValue != NSDateComponentUndefined || rightValue != NSDateComponentUndefined else { continue // both are undefined, don't touch } let checkedLeftValue = leftValue == NSDateComponentUndefined ? 0 : leftValue let checkedRightValue = rightValue == NSDateComponentUndefined ? 0 : rightValue let finalValue = checkedLeftValue + (sum ? checkedRightValue : -checkedRightValue) newComponents.setValue(finalValue, forComponent: unit) } return newComponents } // MARK: - Helpers to enable expressions e.g. date + 1.days - 20.seconds public extension NSTimeZone { /// Returns a new NSDateComponents object containing the time zone as specified by the receiver /// public var timeZone: NSDateComponents { let dateComponents = NSDateComponents() dateComponents.timeZone = self return dateComponents } } public extension NSCalendar { /// Returns a new NSDateComponents object containing the calendar as specified by the receiver /// public var calendar: NSDateComponents { let dateComponents = NSDateComponents() dateComponents.calendar = self return dateComponents } } public extension Int { /// Returns a new NSDateComponents object containing the number of nanoseconds as specified by /// the receiver /// public var nanoseconds: NSDateComponents { let dateComponents = NSDateComponents() dateComponents.nanosecond = self return dateComponents } /// Returns a new NSDateComponents object containing the number of seconds as specified by the /// receiver /// public var seconds: NSDateComponents { let dateComponents = NSDateComponents() dateComponents.second = self return dateComponents } /// Returns a new NSDateComponents object containing the number of minutes as specified by the /// receiver /// public var minutes: NSDateComponents { let dateComponents = NSDateComponents() dateComponents.minute = self return dateComponents } /// Returns a new NSDateComponents object containing the number of hours as specified by the /// receiver /// public var hours: NSDateComponents { let dateComponents = NSDateComponents() dateComponents.hour = self return dateComponents } /// Returns a new NSDateComponents object containing the number of days as specified by the /// receiver /// public var days: NSDateComponents { let dateComponents = NSDateComponents() dateComponents.day = self return dateComponents } /// Returns a new NSDateComponents object containing the number of weeks as specified by the /// receiver /// public var weeks: NSDateComponents { let dateComponents = NSDateComponents() dateComponents.weekOfYear = self return dateComponents } /// Returns a new NSDateComponents object containing the number of months as specified by the /// receiver /// public var months: NSDateComponents { let dateComponents = NSDateComponents() dateComponents.month = self return dateComponents } /// Returns a new NSDateComponents object containing the number of years as specified by the /// receiver /// public var years: NSDateComponents { let dateComponents = NSDateComponents() dateComponents.year = self return dateComponents } }
mit
a12825ca9781bfa9186e527c00690875
31.694444
105
0.67757
5.139738
false
false
false
false
daniele-pizziconi/AlamofireImage
Source/UIImageView+AlamofireImage.swift
1
27001
// // UIImageView+AlamofireImage.swift // // Copyright (c) 2015-2016 Alamofire Software Foundation (http://alamofire.org/) // // 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 Alamofire import Foundation import UIKit import CoreLocation import MapKit extension UIImageView { // MARK: - ImageTransition /// Used to wrap all `UIView` animation transition options alongside a duration. public enum ImageTransition { case noTransition case crossDissolve(TimeInterval) case curlDown(TimeInterval) case curlUp(TimeInterval) case flipFromBottom(TimeInterval) case flipFromLeft(TimeInterval) case flipFromRight(TimeInterval) case flipFromTop(TimeInterval) case custom( duration: TimeInterval, animationOptions: UIViewAnimationOptions, animations: (UIImageView, Image) -> Void, completion: ((Bool) -> Void)? ) /// The duration of the image transition in seconds. public var duration: TimeInterval { switch self { case .noTransition: return 0.0 case .crossDissolve(let duration): return duration case .curlDown(let duration): return duration case .curlUp(let duration): return duration case .flipFromBottom(let duration): return duration case .flipFromLeft(let duration): return duration case .flipFromRight(let duration): return duration case .flipFromTop(let duration): return duration case .custom(let duration, _, _, _): return duration } } /// The animation options of the image transition. public var animationOptions: UIViewAnimationOptions { switch self { case .noTransition: return UIViewAnimationOptions() case .crossDissolve: return .transitionCrossDissolve case .curlDown: return .transitionCurlDown case .curlUp: return .transitionCurlUp case .flipFromBottom: return .transitionFlipFromBottom case .flipFromLeft: return .transitionFlipFromLeft case .flipFromRight: return .transitionFlipFromRight case .flipFromTop: return .transitionFlipFromTop case .custom(_, let animationOptions, _, _): return animationOptions } } /// The animation options of the image transition. public var animations: ((UIImageView, Image) -> Void) { switch self { case .custom(_, _, let animations, _): return animations default: return { $0.image = $1 } } } /// The completion closure associated with the image transition. public var completion: ((Bool) -> Void)? { switch self { case .custom(_, _, _, let completion): return completion default: return nil } } } // MARK: - Private - AssociatedKeys private struct AssociatedKey { static var imageDownloader = "af_UIImageView.ImageDownloader" static var sharedImageDownloader = "af_UIImageView.SharedImageDownloader" static var mapSnapshotter = "af_UIImageView.MapSnapshotter" static var activeRequestReceipt = "af_UIImageView.ActiveRequestReceipt" static var activeRequestLocation = "af_UIImageView.ActiveRequestLocation" } // MARK: - Associated Properties /// The instance image downloader used to download all images. If this property is `nil`, the `UIImageView` will /// fallback on the `af_sharedImageDownloader` for all downloads. The most common use case for needing to use a /// custom instance image downloader is when images are behind different basic auth credentials. public var af_imageDownloader: ImageDownloader? { get { return objc_getAssociatedObject(self, &AssociatedKey.imageDownloader) as? ImageDownloader } set(downloader) { objc_setAssociatedObject(self, &AssociatedKey.imageDownloader, downloader, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } /// The shared image downloader used to download all images. By default, this is the default `ImageDownloader` /// instance backed with an `AutoPurgingImageCache` which automatically evicts images from the cache when the memory /// capacity is reached or memory warning notifications occur. The shared image downloader is only used if the /// `af_imageDownloader` is `nil`. public class var af_sharedImageDownloader: ImageDownloader { get { if let downloader = objc_getAssociatedObject(self, &AssociatedKey.sharedImageDownloader) as? ImageDownloader { return downloader } else { return ImageDownloader.default } } set { objc_setAssociatedObject(self, &AssociatedKey.sharedImageDownloader, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } /// The instance map snapshotter used to download all location images. public var af_mapSnapshotter: MKMapSnapshotter? { get { return objc_getAssociatedObject(self, &AssociatedKey.mapSnapshotter) as? MKMapSnapshotter } set(snapshotter) { objc_setAssociatedObject(self, &AssociatedKey.mapSnapshotter, snapshotter, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } var af_activeRequestReceipt: RequestReceipt? { get { return objc_getAssociatedObject(self, &AssociatedKey.activeRequestReceipt) as? RequestReceipt } set { objc_setAssociatedObject(self, &AssociatedKey.activeRequestReceipt, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } var af_activeRequestLocation: String? { get { return objc_getAssociatedObject(self, &AssociatedKey.activeRequestLocation) as? String } set { objc_setAssociatedObject(self, &AssociatedKey.activeRequestLocation, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } // MARK: - Image Download /// Asynchronously downloads an image from the specified URL, applies the specified image filter to the downloaded /// image and sets it once finished while executing the image transition. /// /// If the image is cached locally, the image is set immediately. Otherwise the specified placehoder image will be /// set immediately, and then the remote image will be set once the image request is finished. /// /// The `completion` closure is called after the image download and filtering are complete, but before the start of /// the image transition. Please note it is no longer the responsibility of the `completion` closure to set the /// image. It will be set automatically. If you require a second notification after the image transition completes, /// use a `.Custom` image transition with a `completion` closure. The `.Custom` `completion` closure is called when /// the image transition is finished. /// /// - parameter location: The CLLocation used for the image request. /// - parameter placeholderImage: The image to be set initially until the image request finished. If /// `nil`, the image view will not change its image until the image /// request finishes. Defaults to `nil`. /// - parameter filter: The image filter applied to the image after the image request is /// finished. Defaults to `nil`. /// - parameter region: The region of the location to be captured. /// - parameter snapshotSize: The size of the snapshot. /// - parameter imageTransition: The image transition animation applied to the image when set. /// - parameter queue: The dispatch queue to call the progress closure on. Defaults to the /// main queue. /// - parameter imageTransition: The image transition animation applied to the image when set. /// Defaults to `.None`. /// - parameter runImageTransitionIfCached: Whether to run the image transition if the image is cached. Defaults /// to `false`. /// - parameter completion: A closure to be executed when the image request finishes. The closure /// has no return value and takes three arguments: the original request, /// the response from the server and the result containing either the /// image or the error that occurred. If the image was returned from the /// image cache, the response will be `nil`. Defaults to `nil`. public func af_setImage( withLocation location: CLLocation, placeholderImage: UIImage? = nil, filter: ImageFilter? = nil, region: MKCoordinateRegion, snapshotSize: CGSize, queue: DispatchQueue = DispatchQueue.main, imageTransition: ImageTransition = .noTransition, runImageTransitionIfCached: Bool = false, completion: ((LocationResponse<UIImage, NSError>) -> Void)? = nil) { let request = locationRequest(with: location) guard !isLocationRequestEqualToActiveRequestLocation(request) else { return } af_cancelImageRequest() let imageDownloader = af_imageDownloader ?? UIImageView.af_sharedImageDownloader let imageCache = imageDownloader.imageCache // Use the image from the image cache if it exists if let image = imageCache?.image(for: request, withIdentifier: filter?.identifier) { let response = LocationResponse<UIImage, NSError>( location: location, snapshot: nil, result: .success(image) ) completion?(response) if runImageTransitionIfCached { let tinyDelay = DispatchTime.now() + Double(Int64(0.001 * Float(NSEC_PER_SEC))) / Double(NSEC_PER_SEC) // Need to let the runloop cycle for the placeholder image to take affect DispatchQueue.main.asyncAfter(deadline: tinyDelay) { self.run(imageTransition, with: image) } } else { self.image = image } return } if af_mapSnapshotter == nil { let options = MKMapSnapshotOptions() options.region = region options.size = snapshotSize options.scale = UIScreen.main.scale af_mapSnapshotter = MKMapSnapshotter(options: options) } // Set the placeholder since we're going to have to download if let placeholderImage = placeholderImage { self.image = placeholderImage } af_mapSnapshotter!.start(with: queue) {[weak self] snapshot, error in guard let strongSelf = self else { return } guard let snapshot = snapshot else { DispatchQueue.main.async { let response = LocationResponse<UIImage, NSError>( location: location, snapshot: nil, result: .failure(error as! NSError) ) completion?(response) } return } let pin = MKPinAnnotationView(annotation: nil, reuseIdentifier: nil) let image = snapshot.image UIGraphicsBeginImageContextWithOptions(image.size, true, image.scale) image.draw(at: CGPoint.zero) let visibleRect = CGRect(origin: CGPoint.zero, size: image.size) var point = snapshot.point(for: location.coordinate) if visibleRect.contains(point) { point.x = point.x + pin.centerOffset.x - (pin.bounds.size.width / 2) point.y = point.y + pin.centerOffset.y - (pin.bounds.size.height / 2) pin.image?.draw(at: point) } let compositeImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() if let image = compositeImage { imageCache?.addImage(image, for: request, withIdentifier: filter?.identifier) DispatchQueue.main.async { strongSelf.run(imageTransition, with: image) } } strongSelf.af_activeRequestLocation = nil } self.af_activeRequestLocation = request } /// Asynchronously downloads an image from the specified URL, applies the specified image filter to the downloaded /// image and sets it once finished while executing the image transition. /// /// If the image is cached locally, the image is set immediately. Otherwise the specified placehoder image will be /// set immediately, and then the remote image will be set once the image request is finished. /// /// The `completion` closure is called after the image download and filtering are complete, but before the start of /// the image transition. Please note it is no longer the responsibility of the `completion` closure to set the /// image. It will be set automatically. If you require a second notification after the image transition completes, /// use a `.Custom` image transition with a `completion` closure. The `.Custom` `completion` closure is called when /// the image transition is finished. /// /// - parameter url: The URL used for the image request. /// - parameter placeholderImage: The image to be set initially until the image request finished. If /// `nil`, the image view will not change its image until the image /// request finishes. Defaults to `nil`. /// - parameter filter: The image filter applied to the image after the image request is /// finished. Defaults to `nil`. /// - parameter progress: The closure to be executed periodically during the lifecycle of the /// request. Defaults to `nil`. /// - parameter progressQueue: The dispatch queue to call the progress closure on. Defaults to the /// main queue. /// - parameter imageTransition: The image transition animation applied to the image when set. /// Defaults to `.None`. /// - parameter runImageTransitionIfCached: Whether to run the image transition if the image is cached. Defaults /// to `false`. /// - parameter completion: A closure to be executed when the image request finishes. The closure /// has no return value and takes three arguments: the original request, /// the response from the server and the result containing either the /// image or the error that occurred. If the image was returned from the /// image cache, the response will be `nil`. Defaults to `nil`. public func af_setImage( withURL url: URL, placeholderImage: UIImage? = nil, filter: ImageFilter? = nil, progress: ImageDownloader.ProgressHandler? = nil, progressQueue: DispatchQueue = DispatchQueue.main, imageTransition: ImageTransition = .noTransition, runImageTransitionIfCached: Bool = false, completion: ((DataResponse<UIImage>) -> Void)? = nil) { af_setImage( withURLRequest: urlRequest(with: url), placeholderImage: placeholderImage, filter: filter, progress: progress, progressQueue: progressQueue, imageTransition: imageTransition, runImageTransitionIfCached: runImageTransitionIfCached, completion: completion ) } /// Asynchronously downloads an image from the specified URL Request, applies the specified image filter to the downloaded /// image and sets it once finished while executing the image transition. /// /// If the image is cached locally, the image is set immediately. Otherwise the specified placehoder image will be /// set immediately, and then the remote image will be set once the image request is finished. /// /// The `completion` closure is called after the image download and filtering are complete, but before the start of /// the image transition. Please note it is no longer the responsibility of the `completion` closure to set the /// image. It will be set automatically. If you require a second notification after the image transition completes, /// use a `.Custom` image transition with a `completion` closure. The `.Custom` `completion` closure is called when /// the image transition is finished. /// /// - parameter urlRequest: The URL request. /// - parameter placeholderImage: The image to be set initially until the image request finished. If /// `nil`, the image view will not change its image until the image /// request finishes. Defaults to `nil`. /// - parameter filter: The image filter applied to the image after the image request is /// finished. Defaults to `nil`. /// - parameter progress: The closure to be executed periodically during the lifecycle of the /// request. Defaults to `nil`. /// - parameter progressQueue: The dispatch queue to call the progress closure on. Defaults to the /// main queue. /// - parameter imageTransition: The image transition animation applied to the image when set. /// Defaults to `.None`. /// - parameter runImageTransitionIfCached: Whether to run the image transition if the image is cached. Defaults /// to `false`. /// - parameter completion: A closure to be executed when the image request finishes. The closure /// has no return value and takes three arguments: the original request, /// the response from the server and the result containing either the /// image or the error that occurred. If the image was returned from the /// image cache, the response will be `nil`. Defaults to `nil`. public func af_setImage( withURLRequest urlRequest: URLRequestConvertible, placeholderImage: UIImage? = nil, filter: ImageFilter? = nil, progress: ImageDownloader.ProgressHandler? = nil, progressQueue: DispatchQueue = DispatchQueue.main, imageTransition: ImageTransition = .noTransition, runImageTransitionIfCached: Bool = false, completion: ((DataResponse<UIImage>) -> Void)? = nil) { guard !isURLRequestURLEqualToActiveRequestURL(urlRequest) else { return } af_cancelImageRequest() let imageDownloader = af_imageDownloader ?? UIImageView.af_sharedImageDownloader let imageCache = imageDownloader.imageCache // Use the image from the image cache if it exists if let request = urlRequest.urlRequest, let image = imageCache?.image(for: request, withIdentifier: filter?.identifier) { let response = DataResponse<UIImage>(request: request, response: nil, data: nil, result: .success(image)) completion?(response) if runImageTransitionIfCached { let tinyDelay = DispatchTime.now() + Double(Int64(0.001 * Float(NSEC_PER_SEC))) / Double(NSEC_PER_SEC) // Need to let the runloop cycle for the placeholder image to take affect DispatchQueue.main.asyncAfter(deadline: tinyDelay) { self.run(imageTransition, with: image) } } else { self.image = image } return } // Set the placeholder since we're going to have to download if let placeholderImage = placeholderImage { self.image = placeholderImage } // Generate a unique download id to check whether the active request has changed while downloading let downloadID = UUID().uuidString // Download the image, then run the image transition or completion handler let requestReceipt = imageDownloader.download( urlRequest, receiptID: downloadID, filter: filter, progress: progress, progressQueue: progressQueue, completion: { [weak self] response in guard let strongSelf = self else { return } completion?(response) guard strongSelf.isURLRequestURLEqualToActiveRequestURL(response.request) && strongSelf.af_activeRequestReceipt?.receiptID == downloadID else { return } if let image = response.result.value { strongSelf.run(imageTransition, with: image) } strongSelf.af_activeRequestReceipt = nil } ) af_activeRequestReceipt = requestReceipt } // MARK: - Image Download Cancellation /// Cancels the active download request, if one exists. public func af_cancelImageRequest() { self.af_cancelLocationRequest() guard let activeRequestReceipt = af_activeRequestReceipt else { return } let imageDownloader = af_imageDownloader ?? UIImageView.af_sharedImageDownloader imageDownloader.cancelRequest(with: activeRequestReceipt) af_activeRequestReceipt = nil } private func af_cancelLocationRequest() { af_mapSnapshotter?.cancel() af_activeRequestLocation = nil } // MARK: - Image Transition /// Runs the image transition on the image view with the specified image. /// /// - parameter imageTransition: The image transition to ran on the image view. /// - parameter image: The image to use for the image transition. public func run(_ imageTransition: ImageTransition, with image: Image) { UIView.transition( with: self, duration: imageTransition.duration, options: imageTransition.animationOptions, animations: { imageTransition.animations(self, image) }, completion: imageTransition.completion ) } // MARK: - Private - URL Request Helper Methods private func urlRequest(with url: URL) -> URLRequest { var urlRequest = URLRequest(url: url) for mimeType in DataRequest.acceptableImageContentTypes { urlRequest.addValue(mimeType, forHTTPHeaderField: "Accept") } return urlRequest } private func isURLRequestURLEqualToActiveRequestURL(_ urlRequest: URLRequestConvertible?) -> Bool { if let currentRequestURL = af_activeRequestReceipt?.request.task?.originalRequest?.url, let requestURL = urlRequest?.urlRequest?.url, currentRequestURL == requestURL { return true } return false } private func locationRequest(with location: CLLocation) -> String { return "\(location.coordinate.latitude);\(location.coordinate.longitude)" } private func isLocationRequestEqualToActiveRequestLocation(_ locationRequest: String?) -> Bool { if let currentRequest = af_activeRequestLocation, currentRequest == locationRequest { return true } return false } } /// Used to store the response data returned from a completed `Request`. public struct LocationResponse<ValueType, ErrorType: Error> { /// The location request. public let location: CLLocation? /// The snapshot returned. public let snapshot: MKMapSnapshot? /// The result of response serialization. public let result: Result<ValueType> /** Initializes the `Response` instance with the specified URL request, URL response, server data and response serialization result. - parameter location: The location request sent to the server. - parameter snapshot: The snapshot returned by the server. - parameter result: The result of response serialization. - returns: the new `Response` instance. */ public init( location: CLLocation?, snapshot: MKMapSnapshot?, result: Result<ValueType>) { self.location = location self.snapshot = snapshot self.result = result } }
mit
27a0b2a92c5b46000e7c80557e82d585
45.473322
126
0.610792
5.682029
false
false
false
false
amratab/ThreeLevelAccordian
ThreeLevelAccordian/Classes/TLACell.swift
1
876
// // TLACell.swift // Pods // // Created by Amrata Baghel on 30/09/16. // Copyright (c) 2016 Amrata Baghel. All rights reserved. import Foundation open class TLACell { var isHidden: Bool var isExpanded: Bool var value: AnyObject var imageURL:String? public init(_ hidden: Bool = true, value: AnyObject, isExpanded: Bool = false, imageURL: String? = nil) { self.isHidden = hidden self.value = value self.isExpanded = isExpanded self.imageURL = imageURL } } open class TLAHeaderItem: TLACell { public init (value: AnyObject, imageURL: String? = nil) { super.init(false, value: value) self.imageURL = imageURL } } open class TLASubItem: TLACell { public init(value: AnyObject, imageURL: String? = nil) { super.init(true, value: value) self.imageURL = imageURL } }
mit
30ab038f7a803caf6f7dc0318ac7e1ec
22.675676
109
0.639269
3.74359
false
false
false
false
quran/quran-ios
Sources/QuranAudioKit/Downloads/ReciterAudioDownload.swift
1
1270
// // ReciterAudioDownload.swift // Quran // // Created by Mohamed Afifi on 4/17/17. // // Quran for iOS is a Quran reading application for iOS. // Copyright (C) 2017 Quran.com // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // public struct ReciterAudioDownload { public init(reciter: Reciter, downloadedSizeInBytes: UInt64, downloadedSuraCount: Int, surasCount: Int) { self.reciter = reciter self.downloadedSizeInBytes = downloadedSizeInBytes self.downloadedSuraCount = downloadedSuraCount self.surasCount = surasCount } public let reciter: Reciter public let downloadedSizeInBytes: UInt64 public let downloadedSuraCount: Int public let surasCount: Int public var isDownloaded: Bool { downloadedSuraCount == surasCount } }
apache-2.0
a969b10b69fdd0c78b1216fb51b23498
33.324324
109
0.724409
4.305085
false
false
false
false
liuche/FirefoxAccounts-ios
Sync/Records/EnvelopeJSON.swift
15
1799
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation import Shared import SwiftyJSON open class EnvelopeJSON { fileprivate let json: JSON public init(_ jsonString: String) { self.json = JSON(parseJSON: jsonString) } public init(_ json: JSON) { self.json = json } open func isValid() -> Bool { return !self.json.isError() && self.json["id"].isString() && //self["collection"].isString && self.json["payload"].isString() } open var id: String { return self.json["id"].string! } open var collection: String { return self.json["collection"].string ?? "" } open var payload: String { return self.json["payload"].string! } open var sortindex: Int { let s = self.json["sortindex"] return s.int ?? 0 } open var modified: Timestamp { // if let intValue = self.json["modified"].int64 { // return Timestamp(intValue) * 1000 // } if let doubleValue = self.json["modified"].double { return Timestamp(1000 * (doubleValue)) } return 0 } open func toString() -> String { return self.json.stringValue()! } open func withModified(_ now: Timestamp) -> EnvelopeJSON { if var d = self.json.dictionary { d["modified"] = JSON(Double(now) / 1000) return EnvelopeJSON(JSON(d)) } return EnvelopeJSON(JSON(parseJSON: "!")) // Intentionally bad JSON. } } extension EnvelopeJSON { func asJSON() -> JSON { return self.json } }
mpl-2.0
9a9620ac822fb10e2125b792753e503c
23.643836
76
0.574764
4.232941
false
false
false
false
shajrawi/swift
stdlib/public/core/ArrayBuffer.swift
3
16348
//===--- ArrayBuffer.swift - Dynamic storage for Swift Array --------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // // This is the class that implements the storage and object management for // Swift Array. // //===----------------------------------------------------------------------===// #if _runtime(_ObjC) import SwiftShims @usableFromInline internal typealias _ArrayBridgeStorage = _BridgeStorage<__ContiguousArrayStorageBase> @usableFromInline @_fixed_layout internal struct _ArrayBuffer<Element> : _ArrayBufferProtocol { /// Create an empty buffer. @inlinable internal init() { _storage = _ArrayBridgeStorage(native: _emptyArrayStorage) } @inlinable internal init(nsArray: AnyObject) { _internalInvariant(_isClassOrObjCExistential(Element.self)) _storage = _ArrayBridgeStorage(objC: nsArray) } /// Returns an `_ArrayBuffer<U>` containing the same elements. /// /// - Precondition: The elements actually have dynamic type `U`, and `U` /// is a class or `@objc` existential. @inlinable __consuming internal func cast<U>(toBufferOf _: U.Type) -> _ArrayBuffer<U> { _internalInvariant(_isClassOrObjCExistential(Element.self)) _internalInvariant(_isClassOrObjCExistential(U.self)) return _ArrayBuffer<U>(storage: _storage) } /// Returns an `_ArrayBuffer<U>` containing the same elements, /// deferring checking each element's `U`-ness until it is accessed. /// /// - Precondition: `U` is a class or `@objc` existential derived from /// `Element`. @inlinable __consuming internal func downcast<U>( toBufferWithDeferredTypeCheckOf _: U.Type ) -> _ArrayBuffer<U> { _internalInvariant(_isClassOrObjCExistential(Element.self)) _internalInvariant(_isClassOrObjCExistential(U.self)) // FIXME: can't check that U is derived from Element pending // <rdar://problem/20028320> generic metatype casting doesn't work // _internalInvariant(U.self is Element.Type) return _ArrayBuffer<U>( storage: _ArrayBridgeStorage(native: _native._storage, isFlagged: true)) } @inlinable internal var needsElementTypeCheck: Bool { // NSArray's need an element typecheck when the element type isn't AnyObject return !_isNativeTypeChecked && !(AnyObject.self is Element.Type) } //===--- private --------------------------------------------------------===// @inlinable internal init(storage: _ArrayBridgeStorage) { _storage = storage } @usableFromInline internal var _storage: _ArrayBridgeStorage } extension _ArrayBuffer { /// Adopt the storage of `source`. @inlinable internal init(_buffer source: NativeBuffer, shiftedToStartIndex: Int) { _internalInvariant(shiftedToStartIndex == 0, "shiftedToStartIndex must be 0") _storage = _ArrayBridgeStorage(native: source._storage) } /// `true`, if the array is native and does not need a deferred type check. @inlinable internal var arrayPropertyIsNativeTypeChecked: Bool { return _isNativeTypeChecked } /// Returns `true` iff this buffer's storage is uniquely-referenced. @inlinable internal mutating func isUniquelyReferenced() -> Bool { if !_isClassOrObjCExistential(Element.self) { return _storage.isUniquelyReferencedUnflaggedNative() } // This is a performance optimization. This code used to be: // // return _storage.isUniquelyReferencedNative() && _isNative. // // SR-6437 if !_storage.isUniquelyReferencedNative() { return false } return _isNative } /// Convert to an NSArray. /// /// O(1) if the element type is bridged verbatim, O(*n*) otherwise. @inlinable internal func _asCocoaArray() -> AnyObject { return _fastPath(_isNative) ? _native._asCocoaArray() : _nonNative.buffer } /// If this buffer is backed by a uniquely-referenced mutable /// `_ContiguousArrayBuffer` that can be grown in-place to allow the self /// buffer store minimumCapacity elements, returns that buffer. /// Otherwise, returns `nil`. @inlinable internal mutating func requestUniqueMutableBackingBuffer(minimumCapacity: Int) -> NativeBuffer? { if _fastPath(isUniquelyReferenced()) { let b = _native if _fastPath(b.capacity >= minimumCapacity) { return b } } return nil } @inlinable internal mutating func isMutableAndUniquelyReferenced() -> Bool { return isUniquelyReferenced() } /// If this buffer is backed by a `_ContiguousArrayBuffer` /// containing the same number of elements as `self`, return it. /// Otherwise, return `nil`. @inlinable internal func requestNativeBuffer() -> NativeBuffer? { if !_isClassOrObjCExistential(Element.self) { return _native } return _fastPath(_storage.isNative) ? _native : nil } // We have two versions of type check: one that takes a range and the other // checks one element. The reason for this is that the ARC optimizer does not // handle loops atm. and so can get blocked by the presence of a loop (over // the range). This loop is not necessary for a single element access. @inline(never) @usableFromInline internal func _typeCheckSlowPath(_ index: Int) { if _fastPath(_isNative) { let element: AnyObject = cast(toBufferOf: AnyObject.self)._native[index] precondition( element is Element, """ Down-casted Array element failed to match the target type Expected \(Element.self) but found \(type(of: element)) """ ) } else { let element = _nonNative[index] precondition( element is Element, """ NSArray element failed to match the Swift Array Element type Expected \(Element.self) but found \(type(of: element)) """ ) } } @inlinable internal func _typeCheck(_ subRange: Range<Int>) { if !_isClassOrObjCExistential(Element.self) { return } if _slowPath(needsElementTypeCheck) { // Could be sped up, e.g. by using // enumerateObjectsAtIndexes:options:usingBlock: in the // non-native case. for i in subRange.lowerBound ..< subRange.upperBound { _typeCheckSlowPath(i) } } } /// Copy the elements in `bounds` from this buffer into uninitialized /// memory starting at `target`. Return a pointer "past the end" of the /// just-initialized memory. @inlinable @discardableResult __consuming internal func _copyContents( subRange bounds: Range<Int>, initializing target: UnsafeMutablePointer<Element> ) -> UnsafeMutablePointer<Element> { _typeCheck(bounds) if _fastPath(_isNative) { return _native._copyContents(subRange: bounds, initializing: target) } let buffer = UnsafeMutableRawPointer(target) .assumingMemoryBound(to: AnyObject.self) let result = _nonNative._copyContents( subRange: bounds, initializing: buffer) return UnsafeMutableRawPointer(result).assumingMemoryBound(to: Element.self) } public __consuming func _copyContents( initializing buffer: UnsafeMutableBufferPointer<Element> ) -> (Iterator,UnsafeMutableBufferPointer<Element>.Index) { // This customization point is not implemented for internal types. // Accidentally calling it would be a catastrophic performance bug. fatalError("unsupported") } /// Returns a `_SliceBuffer` containing the given sub-range of elements in /// `bounds` from this buffer. @inlinable internal subscript(bounds: Range<Int>) -> _SliceBuffer<Element> { get { _typeCheck(bounds) if _fastPath(_isNative) { return _native[bounds] } return _nonNative[bounds].unsafeCastElements(to: Element.self) } set { fatalError("not implemented") } } /// A pointer to the first element. /// /// - Precondition: The elements are known to be stored contiguously. @inlinable internal var firstElementAddress: UnsafeMutablePointer<Element> { _internalInvariant(_isNative, "must be a native buffer") return _native.firstElementAddress } @inlinable internal var firstElementAddressIfContiguous: UnsafeMutablePointer<Element>? { return _fastPath(_isNative) ? firstElementAddress : nil } /// The number of elements the buffer stores. @inlinable internal var count: Int { @inline(__always) get { return _fastPath(_isNative) ? _native.count : _nonNative.count } set { _internalInvariant(_isNative, "attempting to update count of Cocoa array") _native.count = newValue } } /// Traps if an inout violation is detected or if the buffer is /// native and the subscript is out of range. /// /// wasNative == _isNative in the absence of inout violations. /// Because the optimizer can hoist the original check it might have /// been invalidated by illegal user code. @inlinable internal func _checkInoutAndNativeBounds(_ index: Int, wasNative: Bool) { _precondition( _isNative == wasNative, "inout rules were violated: the array was overwritten") if _fastPath(wasNative) { _native._checkValidSubscript(index) } } // TODO: gyb this /// Traps if an inout violation is detected or if the buffer is /// native and typechecked and the subscript is out of range. /// /// wasNativeTypeChecked == _isNativeTypeChecked in the absence of /// inout violations. Because the optimizer can hoist the original /// check it might have been invalidated by illegal user code. @inlinable internal func _checkInoutAndNativeTypeCheckedBounds( _ index: Int, wasNativeTypeChecked: Bool ) { _precondition( _isNativeTypeChecked == wasNativeTypeChecked, "inout rules were violated: the array was overwritten") if _fastPath(wasNativeTypeChecked) { _native._checkValidSubscript(index) } } /// The number of elements the buffer can store without reallocation. @inlinable internal var capacity: Int { return _fastPath(_isNative) ? _native.capacity : _nonNative.count } @inlinable @inline(__always) internal func getElement(_ i: Int, wasNativeTypeChecked: Bool) -> Element { if _fastPath(wasNativeTypeChecked) { return _nativeTypeChecked[i] } return unsafeBitCast(_getElementSlowPath(i), to: Element.self) } @inline(never) @inlinable // @specializable internal func _getElementSlowPath(_ i: Int) -> AnyObject { _internalInvariant( _isClassOrObjCExistential(Element.self), "Only single reference elements can be indexed here.") let element: AnyObject if _isNative { // _checkInoutAndNativeTypeCheckedBounds does no subscript // checking for the native un-typechecked case. Therefore we // have to do it here. _native._checkValidSubscript(i) element = cast(toBufferOf: AnyObject.self)._native[i] precondition( element is Element, """ Down-casted Array element failed to match the target type Expected \(Element.self) but found \(type(of: element)) """ ) } else { // ObjC arrays do their own subscript checking. element = _nonNative[i] precondition( element is Element, """ NSArray element failed to match the Swift Array Element type Expected \(Element.self) but found \(type(of: element)) """ ) } return element } /// Get or set the value of the ith element. @inlinable internal subscript(i: Int) -> Element { get { return getElement(i, wasNativeTypeChecked: _isNativeTypeChecked) } nonmutating set { if _fastPath(_isNative) { _native[i] = newValue } else { var refCopy = self refCopy.replaceSubrange( i..<(i + 1), with: 1, elementsOf: CollectionOfOne(newValue)) } } } /// Call `body(p)`, where `p` is an `UnsafeBufferPointer` over the /// underlying contiguous storage. If no such storage exists, it is /// created on-demand. @inlinable internal func withUnsafeBufferPointer<R>( _ body: (UnsafeBufferPointer<Element>) throws -> R ) rethrows -> R { if _fastPath(_isNative) { defer { _fixLifetime(self) } return try body( UnsafeBufferPointer(start: firstElementAddress, count: count)) } return try ContiguousArray(self).withUnsafeBufferPointer(body) } /// Call `body(p)`, where `p` is an `UnsafeMutableBufferPointer` /// over the underlying contiguous storage. /// /// - Precondition: Such contiguous storage exists or the buffer is empty. @inlinable internal mutating func withUnsafeMutableBufferPointer<R>( _ body: (UnsafeMutableBufferPointer<Element>) throws -> R ) rethrows -> R { _internalInvariant( _isNative || count == 0, "Array is bridging an opaque NSArray; can't get a pointer to the elements" ) defer { _fixLifetime(self) } return try body(UnsafeMutableBufferPointer( start: firstElementAddressIfContiguous, count: count)) } /// An object that keeps the elements stored in this buffer alive. @inlinable internal var owner: AnyObject { return _fastPath(_isNative) ? _native._storage : _nonNative.buffer } /// An object that keeps the elements stored in this buffer alive. /// /// - Precondition: This buffer is backed by a `_ContiguousArrayBuffer`. @inlinable internal var nativeOwner: AnyObject { _internalInvariant(_isNative, "Expect a native array") return _native._storage } /// A value that identifies the storage used by the buffer. Two /// buffers address the same elements when they have the same /// identity and count. @inlinable internal var identity: UnsafeRawPointer { if _isNative { return _native.identity } else { return UnsafeRawPointer( Unmanaged.passUnretained(_nonNative.buffer).toOpaque()) } } //===--- Collection conformance -------------------------------------===// /// The position of the first element in a non-empty collection. /// /// In an empty collection, `startIndex == endIndex`. @inlinable internal var startIndex: Int { return 0 } /// The collection's "past the end" position. /// /// `endIndex` is not a valid argument to `subscript`, and is always /// reachable from `startIndex` by zero or more applications of /// `index(after:)`. @inlinable internal var endIndex: Int { return count } @usableFromInline internal typealias Indices = Range<Int> //===--- private --------------------------------------------------------===// internal typealias Storage = _ContiguousArrayStorage<Element> @usableFromInline internal typealias NativeBuffer = _ContiguousArrayBuffer<Element> @inlinable internal var _isNative: Bool { if !_isClassOrObjCExistential(Element.self) { return true } else { return _storage.isNative } } /// `true`, if the array is native and does not need a deferred type check. @inlinable internal var _isNativeTypeChecked: Bool { if !_isClassOrObjCExistential(Element.self) { return true } else { return _storage.isUnflaggedNative } } /// Our native representation. /// /// - Precondition: `_isNative`. @inlinable internal var _native: NativeBuffer { return NativeBuffer( _isClassOrObjCExistential(Element.self) ? _storage.nativeInstance : _storage.unflaggedNativeInstance) } /// Fast access to the native representation. /// /// - Precondition: `_isNativeTypeChecked`. @inlinable internal var _nativeTypeChecked: NativeBuffer { return NativeBuffer(_storage.unflaggedNativeInstance) } @inlinable internal var _nonNative: _CocoaArrayWrapper { @inline(__always) get { _internalInvariant(_isClassOrObjCExistential(Element.self)) return _CocoaArrayWrapper(_storage.objCInstance) } } } #endif
apache-2.0
e82c7b9fc04139f8abd691354f991e1a
30.438462
81
0.665647
4.803996
false
false
false
false
IngmarStein/swift
benchmark/single-source/SortStrings.swift
3
38755
//===--- SortStrings.swift ------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // Sort an array of strings using an explicit sort predicate. var stringBenchmarkWords: [String] = [ "woodshed", "lakism", "gastroperiodynia", "afetal", "ramsch", "Nickieben", "undutifulness", "birdglue", "ungentlemanize", "menacingly", "heterophile", "leoparde", "Casearia", "decorticate", "neognathic", "mentionable", "tetraphenol", "pseudonymal", "dislegitimate", "Discoidea", "intitule", "ionium", "Lotuko", "timbering", "nonliquidating", "oarialgia", "Saccobranchus", "reconnoiter", "criminative", "disintegratory", "executer", "Cylindrosporium", "complimentation", "Ixiama", "Araceae", "silaginoid", "derencephalus", "Lamiidae", "marrowlike", "ninepin", "dynastid", "lampfly", "feint", "trihemimer", "semibarbarous", "heresy", "tritanope", "indifferentist", "confound", "hyperbolaeon", "planirostral", "philosophunculist", "existence", "fretless", "Leptandra", "Amiranha", "handgravure", "gnash", "unbelievability", "orthotropic", "Susumu", "teleutospore", "sleazy", "shapeliness", "hepatotomy", "exclusivism", "stifler", "cunning", "isocyanuric", "pseudepigraphy", "carpetbagger", "respectiveness", "Jussi", "vasotomy", "proctotomy", "ovatotriangular", "aesthetic", "schizogamy", "disengagement", "foray", "haplocaulescent", "noncoherent", "astrocyte", "unreverberated", "presenile", "lanson", "enkraal", "contemplative", "Syun", "sartage", "unforgot", "wyde", "homeotransplant", "implicational", "forerunnership", "calcaneum", "stomatodeum", "pharmacopedia", "preconcessive", "trypanosomatic", "intracollegiate", "rampacious", "secundipara", "isomeric", "treehair", "pulmonal", "uvate", "dugway", "glucofrangulin", "unglory", "Amandus", "icterogenetic", "quadrireme", "Lagostomus", "brakeroot", "anthracemia", "fluted", "protoelastose", "thro", "pined", "Saxicolinae", "holidaymaking", "strigil", "uncurbed", "starling", "redeemeress", "Liliaceae", "imparsonee", "obtusish", "brushed", "mesally", "probosciformed", "Bourbonesque", "histological", "caroba", "digestion", "Vindemiatrix", "triactinal", "tattling", "arthrobacterium", "unended", "suspectfulness", "movelessness", "chartist", "Corynebacterium", "tercer", "oversaturation", "Congoleum", "antiskeptical", "sacral", "equiradiate", "whiskerage", "panidiomorphic", "unplanned", "anilopyrine", "Queres", "tartronyl", "Ing", "notehead", "finestiller", "weekender", "kittenhood", "competitrix", "premillenarian", "convergescence", "microcoleoptera", "slirt", "asteatosis", "Gruidae", "metastome", "ambuscader", "untugged", "uneducated", "redistill", "rushlight", "freakish", "dosology", "papyrine", "iconologist", "Bidpai", "prophethood", "pneumotropic", "chloroformize", "intemperance", "spongiform", "superindignant", "divider", "starlit", "merchantish", "indexless", "unidentifiably", "coumarone", "nomism", "diaphanous", "salve", "option", "anallantoic", "paint", "thiofurfuran", "baddeleyite", "Donne", "heterogenicity", "decess", "eschynite", "mamma", "unmonarchical", "Archiplata", "widdifow", "apathic", "overline", "chaetophoraceous", "creaky", "trichosporange", "uninterlined", "cometwise", "hermeneut", "unbedraggled", "tagged", "Sminthurus", "somniloquacious", "aphasiac", "Inoperculata", "photoactivity", "mobship", "unblightedly", "lievrite", "Khoja", "Falerian", "milfoil", "protectingly", "householder", "cathedra", "calmingly", "tordrillite", "rearhorse", "Leonard", "maracock", "youngish", "kammererite", "metanephric", "Sageretia", "diplococcoid", "accelerative", "choreal", "metalogical", "recombination", "unimprison", "invocation", "syndetic", "toadback", "vaned", "cupholder", "metropolitanship", "paramandelic", "dermolysis", "Sheriyat", "rhabdus", "seducee", "encrinoid", "unsuppliable", "cololite", "timesaver", "preambulate", "sampling", "roaster", "springald", "densher", "protraditional", "naturalesque", "Hydrodamalis", "cytogenic", "shortly", "cryptogrammatical", "squat", "genual", "backspier", "solubleness", "macroanalytical", "overcovetousness", "Natalie", "cuprobismutite", "phratriac", "Montanize", "hymnologist", "karyomiton", "podger", "unofficiousness", "antisplasher", "supraclavicular", "calidity", "disembellish", "antepredicament", "recurvirostral", "pulmonifer", "coccidial", "botonee", "protoglobulose", "isonym", "myeloid", "premiership", "unmonopolize", "unsesquipedalian", "unfelicitously", "theftbote", "undauntable", "lob", "praenomen", "underriver", "gorfly", "pluckage", "radiovision", "tyrantship", "fraught", "doppelkummel", "rowan", "allosyndetic", "kinesiology", "psychopath", "arrent", "amusively", "preincorporation", "Montargis", "pentacron", "neomedievalism", "sima", "lichenicolous", "Ecclesiastes", "woofed", "cardinalist", "sandaracin", "gymnasial", "lithoglyptics", "centimeter", "quadrupedous", "phraseology", "tumuli", "ankylotomy", "myrtol", "cohibitive", "lepospondylous", "silvendy", "inequipotential", "entangle", "raveling", "Zeugobranchiata", "devastating", "grainage", "amphisbaenian", "blady", "cirrose", "proclericalism", "governmentalist", "carcinomorphic", "nurtureship", "clancular", "unsteamed", "discernibly", "pleurogenic", "impalpability", "Azotobacterieae", "sarcoplasmic", "alternant", "fitly", "acrorrheuma", "shrapnel", "pastorize", "gulflike", "foreglow", "unrelated", "cirriped", "cerviconasal", "sexuale", "pussyfooter", "gadolinic", "duplicature", "codelinquency", "trypanolysis", "pathophobia", "incapsulation", "nonaerating", "feldspar", "diaphonic", "epiglottic", "depopulator", "wisecracker", "gravitational", "kuba", "lactesce", "Toxotes", "periomphalic", "singstress", "fannier", "counterformula", "Acemetae", "repugnatorial", "collimator", "Acinetina", "unpeace", "drum", "tetramorphic", "descendentalism", "cementer", "supraloral", "intercostal", "Nipponize", "negotiator", "vacationless", "synthol", "fissureless", "resoap", "pachycarpous", "reinspiration", "misappropriation", "disdiazo", "unheatable", "streng", "Detroiter", "infandous", "loganiaceous", "desugar", "Matronalia", "myxocystoma", "Gandhiism", "kiddier", "relodge", "counterreprisal", "recentralize", "foliously", "reprinter", "gender", "edaciousness", "chondriomite", "concordant", "stockrider", "pedary", "shikra", "blameworthiness", "vaccina", "Thamnophilinae", "wrongwise", "unsuperannuated", "convalescency", "intransmutable", "dropcloth", "Ceriomyces", "ponderal", "unstentorian", "mem", "deceleration", "ethionic", "untopped", "wetback", "bebar", "undecaying", "shoreside", "energize", "presacral", "undismay", "agricolite", "cowheart", "hemibathybian", "postexilian", "Phacidiaceae", "offing", "redesignation", "skeptically", "physicianless", "bronchopathy", "marabuto", "proprietory", "unobtruded", "funmaker", "plateresque", "preadventure", "beseeching", "cowpath", "pachycephalia", "arthresthesia", "supari", "lengthily", "Nepa", "liberation", "nigrify", "belfry", "entoolitic", "bazoo", "pentachromic", "distinguishable", "slideable", "galvanoscope", "remanage", "cetene", "bocardo", "consummation", "boycottism", "perplexity", "astay", "Gaetuli", "periplastic", "consolidator", "sluggarding", "coracoscapular", "anangioid", "oxygenizer", "Hunanese", "seminary", "periplast", "Corylus", "unoriginativeness", "persecutee", "tweaker", "silliness", "Dabitis", "facetiousness", "thymy", "nonimperial", "mesoblastema", "turbiniform", "churchway", "cooing", "frithbot", "concomitantly", "stalwartize", "clingfish", "hardmouthed", "parallelepipedonal", "coracoacromial", "factuality", "curtilage", "arachnoidean", "semiaridity", "phytobacteriology", "premastery", "hyperpurist", "mobed", "opportunistic", "acclimature", "outdistance", "sophister", "condonement", "oxygenerator", "acetonic", "emanatory", "periphlebitis", "nonsociety", "spectroradiometric", "superaverage", "cleanness", "posteroventral", "unadvised", "unmistakedly", "pimgenet", "auresca", "overimitate", "dipnoan", "chromoxylograph", "triakistetrahedron", "Suessiones", "uncopiable", "oligomenorrhea", "fribbling", "worriable", "flot", "ornithotrophy", "phytoteratology", "setup", "lanneret", "unbraceleted", "gudemother", "Spica", "unconsolatory", "recorruption", "premenstrual", "subretinal", "millennialist", "subjectibility", "rewardproof", "counterflight", "pilomotor", "carpetbaggery", "macrodiagonal", "slim", "indiscernible", "cuckoo", "moted", "controllingly", "gynecopathy", "porrectus", "wanworth", "lutfisk", "semiprivate", "philadelphy", "abdominothoracic", "coxcomb", "dambrod", "Metanemertini", "balminess", "homotypy", "waremaker", "absurdity", "gimcrack", "asquat", "suitable", "perimorphous", "kitchenwards", "pielum", "salloo", "paleontologic", "Olson", "Tellinidae", "ferryman", "peptonoid", "Bopyridae", "fallacy", "ictuate", "aguinaldo", "rhyodacite", "Ligydidae", "galvanometric", "acquisitor", "muscology", "hemikaryon", "ethnobotanic", "postganglionic", "rudimentarily", "replenish", "phyllorhine", "popgunnery", "summar", "quodlibetary", "xanthochromia", "autosymbolically", "preloreal", "extent", "strawberry", "immortalness", "colicwort", "frisca", "electiveness", "heartbroken", "affrightingly", "reconfiscation", "jacchus", "imponderably", "semantics", "beennut", "paleometeorological", "becost", "timberwright", "resuppose", "syncategorematical", "cytolymph", "steinbok", "explantation", "hyperelliptic", "antescript", "blowdown", "antinomical", "caravanserai", "unweariedly", "isonymic", "keratoplasty", "vipery", "parepigastric", "endolymphatic", "Londonese", "necrotomy", "angelship", "Schizogregarinida", "steeplebush", "sparaxis", "connectedness", "tolerance", "impingent", "agglutinin", "reviver", "hieroglyphical", "dialogize", "coestate", "declamatory", "ventilation", "tauromachy", "cotransubstantiate", "pome", "underseas", "triquadrantal", "preconfinemnt", "electroindustrial", "selachostomous", "nongolfer", "mesalike", "hamartiology", "ganglioblast", "unsuccessive", "yallow", "bacchanalianly", "platydactyl", "Bucephala", "ultraurgent", "penalist", "catamenial", "lynnhaven", "unrelevant", "lunkhead", "metropolitan", "hydro", "outsoar", "vernant", "interlanguage", "catarrhal", "Ionicize", "keelless", "myomantic", "booker", "Xanthomonas", "unimpeded", "overfeminize", "speronaro", "diaconia", "overholiness", "liquefacient", "Spartium", "haggly", "albumose", "nonnecessary", "sulcalization", "decapitate", "cellated", "unguirostral", "trichiurid", "loveproof", "amakebe", "screet", "arsenoferratin", "unfrizz", "undiscoverable", "procollectivistic", "tractile", "Winona", "dermostosis", "eliminant", "scomberoid", "tensile", "typesetting", "xylic", "dermatopathology", "cycloplegic", "revocable", "fissate", "afterplay", "screwship", "microerg", "bentonite", "stagecoaching", "beglerbeglic", "overcharitably", "Plotinism", "Veddoid", "disequalize", "cytoproct", "trophophore", "antidote", "allerion", "famous", "convey", "postotic", "rapillo", "cilectomy", "penkeeper", "patronym", "bravely", "ureteropyelitis", "Hildebrandine", "missileproof", "Conularia", "deadening", "Conrad", "pseudochylous", "typologically", "strummer", "luxuriousness", "resublimation", "glossiness", "hydrocauline", "anaglyph", "personifiable", "seniority", "formulator", "datiscaceous", "hydracrylate", "Tyranni", "Crawthumper", "overprove", "masher", "dissonance", "Serpentinian", "malachite", "interestless", "stchi", "ogum", "polyspermic", "archegoniate", "precogitation", "Alkaphrah", "craggily", "delightfulness", "bioplast", "diplocaulescent", "neverland", "interspheral", "chlorhydric", "forsakenly", "scandium", "detubation", "telega", "Valeriana", "centraxonial", "anabolite", "neger", "miscellanea", "whalebacker", "stylidiaceous", "unpropelled", "Kennedya", "Jacksonite", "ghoulish", "Dendrocalamus", "paynimhood", "rappist", "unluffed", "falling", "Lyctus", "uncrown", "warmly", "pneumatism", "Morisonian", "notate", "isoagglutinin", "Pelidnota", "previsit", "contradistinctly", "utter", "porometer", "gie", "germanization", "betwixt", "prenephritic", "underpier", "Eleutheria", "ruthenious", "convertor", "antisepsin", "winterage", "tetramethylammonium", "Rockaway", "Penaea", "prelatehood", "brisket", "unwishful", "Minahassa", "Briareus", "semiaxis", "disintegrant", "peastick", "iatromechanical", "fastus", "thymectomy", "ladyless", "unpreened", "overflutter", "sicker", "apsidally", "thiazine", "guideway", "pausation", "tellinoid", "abrogative", "foraminulate", "omphalos", "Monorhina", "polymyarian", "unhelpful", "newslessness", "oryctognosy", "octoradial", "doxology", "arrhythmy", "gugal", "mesityl", "hexaplaric", "Cabirian", "hordeiform", "eddyroot", "internarial", "deservingness", "jawbation", "orographically", "semiprecious", "seasick", "thermically", "grew", "tamability", "egotistically", "fip", "preabsorbent", "leptochroa", "ethnobotany", "podolite", "egoistic", "semitropical", "cero", "spinelessness", "onshore", "omlah", "tintinnabulist", "machila", "entomotomy", "nubile", "nonscholastic", "burnt", "Alea", "befume", "doctorless", "Napoleonic", "scenting", "apokreos", "cresylene", "paramide", "rattery", "disinterested", "idiopathetic", "negatory", "fervid", "quintato", "untricked", "Metrosideros", "mescaline", "midverse", "Musophagidae", "fictionary", "branchiostegous", "yoker", "residuum", "culmigenous", "fleam", "suffragism", "Anacreon", "sarcodous", "parodistic", "writmaking", "conversationism", "retroposed", "tornillo", "presuspect", "didymous", "Saumur", "spicing", "drawbridge", "cantor", "incumbrancer", "heterospory", "Turkeydom", "anteprandial", "neighbourship", "thatchless", "drepanoid", "lusher", "paling", "ecthlipsis", "heredosyphilitic", "although", "garetta", "temporarily", "Monotropa", "proglottic", "calyptro", "persiflage", "degradable", "paraspecific", "undecorative", "Pholas", "myelon", "resteal", "quadrantly", "scrimped", "airer", "deviless", "caliciform", "Sefekhet", "shastaite", "togate", "macrostructure", "bipyramid", "wey", "didynamy", "knacker", "swage", "supermanism", "epitheton", "overpresumptuous" ] @inline(never) func benchSortStrings(_ words: [String]) { // Notice that we _copy_ the array of words before we sort it. // Pass an explicit '<' predicate to benchmark reabstraction thunks. var tempwords = words tempwords.sort(by: <) } public func run_SortStrings(_ N: Int) { for _ in 1...5*N { benchSortStrings(stringBenchmarkWords) } } var stringBenchmarkWordsUnicode: [String] = [ "❄️woodshed", "❄️lakism", "❄️gastroperiodynia", "❄️afetal", "❄️ramsch", "❄️Nickieben", "❄️undutifulness", "❄️birdglue", "❄️ungentlemanize", "❄️menacingly", "❄️heterophile", "❄️leoparde", "❄️Casearia", "❄️decorticate", "❄️neognathic", "❄️mentionable", "❄️tetraphenol", "❄️pseudonymal", "❄️dislegitimate", "❄️Discoidea", "❄️intitule", "❄️ionium", "❄️Lotuko", "❄️timbering", "❄️nonliquidating", "❄️oarialgia", "❄️Saccobranchus", "❄️reconnoiter", "❄️criminative", "❄️disintegratory", "❄️executer", "❄️Cylindrosporium", "❄️complimentation", "❄️Ixiama", "❄️Araceae", "❄️silaginoid", "❄️derencephalus", "❄️Lamiidae", "❄️marrowlike", "❄️ninepin", "❄️dynastid", "❄️lampfly", "❄️feint", "❄️trihemimer", "❄️semibarbarous", "❄️heresy", "❄️tritanope", "❄️indifferentist", "❄️confound", "❄️hyperbolaeon", "❄️planirostral", "❄️philosophunculist", "❄️existence", "❄️fretless", "❄️Leptandra", "❄️Amiranha", "❄️handgravure", "❄️gnash", "❄️unbelievability", "❄️orthotropic", "❄️Susumu", "❄️teleutospore", "❄️sleazy", "❄️shapeliness", "❄️hepatotomy", "❄️exclusivism", "❄️stifler", "❄️cunning", "❄️isocyanuric", "❄️pseudepigraphy", "❄️carpetbagger", "❄️respectiveness", "❄️Jussi", "❄️vasotomy", "❄️proctotomy", "❄️ovatotriangular", "❄️aesthetic", "❄️schizogamy", "❄️disengagement", "❄️foray", "❄️haplocaulescent", "❄️noncoherent", "❄️astrocyte", "❄️unreverberated", "❄️presenile", "❄️lanson", "❄️enkraal", "❄️contemplative", "❄️Syun", "❄️sartage", "❄️unforgot", "❄️wyde", "❄️homeotransplant", "❄️implicational", "❄️forerunnership", "❄️calcaneum", "❄️stomatodeum", "❄️pharmacopedia", "❄️preconcessive", "❄️trypanosomatic", "❄️intracollegiate", "❄️rampacious", "❄️secundipara", "❄️isomeric", "❄️treehair", "❄️pulmonal", "❄️uvate", "❄️dugway", "❄️glucofrangulin", "❄️unglory", "❄️Amandus", "❄️icterogenetic", "❄️quadrireme", "❄️Lagostomus", "❄️brakeroot", "❄️anthracemia", "❄️fluted", "❄️protoelastose", "❄️thro", "❄️pined", "❄️Saxicolinae", "❄️holidaymaking", "❄️strigil", "❄️uncurbed", "❄️starling", "❄️redeemeress", "❄️Liliaceae", "❄️imparsonee", "❄️obtusish", "❄️brushed", "❄️mesally", "❄️probosciformed", "❄️Bourbonesque", "❄️histological", "❄️caroba", "❄️digestion", "❄️Vindemiatrix", "❄️triactinal", "❄️tattling", "❄️arthrobacterium", "❄️unended", "❄️suspectfulness", "❄️movelessness", "❄️chartist", "❄️Corynebacterium", "❄️tercer", "❄️oversaturation", "❄️Congoleum", "❄️antiskeptical", "❄️sacral", "❄️equiradiate", "❄️whiskerage", "❄️panidiomorphic", "❄️unplanned", "❄️anilopyrine", "❄️Queres", "❄️tartronyl", "❄️Ing", "❄️notehead", "❄️finestiller", "❄️weekender", "❄️kittenhood", "❄️competitrix", "❄️premillenarian", "❄️convergescence", "❄️microcoleoptera", "❄️slirt", "❄️asteatosis", "❄️Gruidae", "❄️metastome", "❄️ambuscader", "❄️untugged", "❄️uneducated", "❄️redistill", "❄️rushlight", "❄️freakish", "❄️dosology", "❄️papyrine", "❄️iconologist", "❄️Bidpai", "❄️prophethood", "❄️pneumotropic", "❄️chloroformize", "❄️intemperance", "❄️spongiform", "❄️superindignant", "❄️divider", "❄️starlit", "❄️merchantish", "❄️indexless", "❄️unidentifiably", "❄️coumarone", "❄️nomism", "❄️diaphanous", "❄️salve", "❄️option", "❄️anallantoic", "❄️paint", "❄️thiofurfuran", "❄️baddeleyite", "❄️Donne", "❄️heterogenicity", "❄️decess", "❄️eschynite", "❄️mamma", "❄️unmonarchical", "❄️Archiplata", "❄️widdifow", "❄️apathic", "❄️overline", "❄️chaetophoraceous", "❄️creaky", "❄️trichosporange", "❄️uninterlined", "❄️cometwise", "❄️hermeneut", "❄️unbedraggled", "❄️tagged", "❄️Sminthurus", "❄️somniloquacious", "❄️aphasiac", "❄️Inoperculata", "❄️photoactivity", "❄️mobship", "❄️unblightedly", "❄️lievrite", "❄️Khoja", "❄️Falerian", "❄️milfoil", "❄️protectingly", "❄️householder", "❄️cathedra", "❄️calmingly", "❄️tordrillite", "❄️rearhorse", "❄️Leonard", "❄️maracock", "❄️youngish", "❄️kammererite", "❄️metanephric", "❄️Sageretia", "❄️diplococcoid", "❄️accelerative", "❄️choreal", "❄️metalogical", "❄️recombination", "❄️unimprison", "❄️invocation", "❄️syndetic", "❄️toadback", "❄️vaned", "❄️cupholder", "❄️metropolitanship", "❄️paramandelic", "❄️dermolysis", "❄️Sheriyat", "❄️rhabdus", "❄️seducee", "❄️encrinoid", "❄️unsuppliable", "❄️cololite", "❄️timesaver", "❄️preambulate", "❄️sampling", "❄️roaster", "❄️springald", "❄️densher", "❄️protraditional", "❄️naturalesque", "❄️Hydrodamalis", "❄️cytogenic", "❄️shortly", "❄️cryptogrammatical", "❄️squat", "❄️genual", "❄️backspier", "❄️solubleness", "❄️macroanalytical", "❄️overcovetousness", "❄️Natalie", "❄️cuprobismutite", "❄️phratriac", "❄️Montanize", "❄️hymnologist", "❄️karyomiton", "❄️podger", "❄️unofficiousness", "❄️antisplasher", "❄️supraclavicular", "❄️calidity", "❄️disembellish", "❄️antepredicament", "❄️recurvirostral", "❄️pulmonifer", "❄️coccidial", "❄️botonee", "❄️protoglobulose", "❄️isonym", "❄️myeloid", "❄️premiership", "❄️unmonopolize", "❄️unsesquipedalian", "❄️unfelicitously", "❄️theftbote", "❄️undauntable", "❄️lob", "❄️praenomen", "❄️underriver", "❄️gorfly", "❄️pluckage", "❄️radiovision", "❄️tyrantship", "❄️fraught", "❄️doppelkummel", "❄️rowan", "❄️allosyndetic", "❄️kinesiology", "❄️psychopath", "❄️arrent", "❄️amusively", "❄️preincorporation", "❄️Montargis", "❄️pentacron", "❄️neomedievalism", "❄️sima", "❄️lichenicolous", "❄️Ecclesiastes", "❄️woofed", "❄️cardinalist", "❄️sandaracin", "❄️gymnasial", "❄️lithoglyptics", "❄️centimeter", "❄️quadrupedous", "❄️phraseology", "❄️tumuli", "❄️ankylotomy", "❄️myrtol", "❄️cohibitive", "❄️lepospondylous", "❄️silvendy", "❄️inequipotential", "❄️entangle", "❄️raveling", "❄️Zeugobranchiata", "❄️devastating", "❄️grainage", "❄️amphisbaenian", "❄️blady", "❄️cirrose", "❄️proclericalism", "❄️governmentalist", "❄️carcinomorphic", "❄️nurtureship", "❄️clancular", "❄️unsteamed", "❄️discernibly", "❄️pleurogenic", "❄️impalpability", "❄️Azotobacterieae", "❄️sarcoplasmic", "❄️alternant", "❄️fitly", "❄️acrorrheuma", "❄️shrapnel", "❄️pastorize", "❄️gulflike", "❄️foreglow", "❄️unrelated", "❄️cirriped", "❄️cerviconasal", "❄️sexuale", "❄️pussyfooter", "❄️gadolinic", "❄️duplicature", "❄️codelinquency", "❄️trypanolysis", "❄️pathophobia", "❄️incapsulation", "❄️nonaerating", "❄️feldspar", "❄️diaphonic", "❄️epiglottic", "❄️depopulator", "❄️wisecracker", "❄️gravitational", "❄️kuba", "❄️lactesce", "❄️Toxotes", "❄️periomphalic", "❄️singstress", "❄️fannier", "❄️counterformula", "❄️Acemetae", "❄️repugnatorial", "❄️collimator", "❄️Acinetina", "❄️unpeace", "❄️drum", "❄️tetramorphic", "❄️descendentalism", "❄️cementer", "❄️supraloral", "❄️intercostal", "❄️Nipponize", "❄️negotiator", "❄️vacationless", "❄️synthol", "❄️fissureless", "❄️resoap", "❄️pachycarpous", "❄️reinspiration", "❄️misappropriation", "❄️disdiazo", "❄️unheatable", "❄️streng", "❄️Detroiter", "❄️infandous", "❄️loganiaceous", "❄️desugar", "❄️Matronalia", "❄️myxocystoma", "❄️Gandhiism", "❄️kiddier", "❄️relodge", "❄️counterreprisal", "❄️recentralize", "❄️foliously", "❄️reprinter", "❄️gender", "❄️edaciousness", "❄️chondriomite", "❄️concordant", "❄️stockrider", "❄️pedary", "❄️shikra", "❄️blameworthiness", "❄️vaccina", "❄️Thamnophilinae", "❄️wrongwise", "❄️unsuperannuated", "❄️convalescency", "❄️intransmutable", "❄️dropcloth", "❄️Ceriomyces", "❄️ponderal", "❄️unstentorian", "❄️mem", "❄️deceleration", "❄️ethionic", "❄️untopped", "❄️wetback", "❄️bebar", "❄️undecaying", "❄️shoreside", "❄️energize", "❄️presacral", "❄️undismay", "❄️agricolite", "❄️cowheart", "❄️hemibathybian", "❄️postexilian", "❄️Phacidiaceae", "❄️offing", "❄️redesignation", "❄️skeptically", "❄️physicianless", "❄️bronchopathy", "❄️marabuto", "❄️proprietory", "❄️unobtruded", "❄️funmaker", "❄️plateresque", "❄️preadventure", "❄️beseeching", "❄️cowpath", "❄️pachycephalia", "❄️arthresthesia", "❄️supari", "❄️lengthily", "❄️Nepa", "❄️liberation", "❄️nigrify", "❄️belfry", "❄️entoolitic", "❄️bazoo", "❄️pentachromic", "❄️distinguishable", "❄️slideable", "❄️galvanoscope", "❄️remanage", "❄️cetene", "❄️bocardo", "❄️consummation", "❄️boycottism", "❄️perplexity", "❄️astay", "❄️Gaetuli", "❄️periplastic", "❄️consolidator", "❄️sluggarding", "❄️coracoscapular", "❄️anangioid", "❄️oxygenizer", "❄️Hunanese", "❄️seminary", "❄️periplast", "❄️Corylus", "❄️unoriginativeness", "❄️persecutee", "❄️tweaker", "❄️silliness", "❄️Dabitis", "❄️facetiousness", "❄️thymy", "❄️nonimperial", "❄️mesoblastema", "❄️turbiniform", "❄️churchway", "❄️cooing", "❄️frithbot", "❄️concomitantly", "❄️stalwartize", "❄️clingfish", "❄️hardmouthed", "❄️parallelepipedonal", "❄️coracoacromial", "❄️factuality", "❄️curtilage", "❄️arachnoidean", "❄️semiaridity", "❄️phytobacteriology", "❄️premastery", "❄️hyperpurist", "❄️mobed", "❄️opportunistic", "❄️acclimature", "❄️outdistance", "❄️sophister", "❄️condonement", "❄️oxygenerator", "❄️acetonic", "❄️emanatory", "❄️periphlebitis", "❄️nonsociety", "❄️spectroradiometric", "❄️superaverage", "❄️cleanness", "❄️posteroventral", "❄️unadvised", "❄️unmistakedly", "❄️pimgenet", "❄️auresca", "❄️overimitate", "❄️dipnoan", "❄️chromoxylograph", "❄️triakistetrahedron", "❄️Suessiones", "❄️uncopiable", "❄️oligomenorrhea", "❄️fribbling", "❄️worriable", "❄️flot", "❄️ornithotrophy", "❄️phytoteratology", "❄️setup", "❄️lanneret", "❄️unbraceleted", "❄️gudemother", "❄️Spica", "❄️unconsolatory", "❄️recorruption", "❄️premenstrual", "❄️subretinal", "❄️millennialist", "❄️subjectibility", "❄️rewardproof", "❄️counterflight", "❄️pilomotor", "❄️carpetbaggery", "❄️macrodiagonal", "❄️slim", "❄️indiscernible", "❄️cuckoo", "❄️moted", "❄️controllingly", "❄️gynecopathy", "❄️porrectus", "❄️wanworth", "❄️lutfisk", "❄️semiprivate", "❄️philadelphy", "❄️abdominothoracic", "❄️coxcomb", "❄️dambrod", "❄️Metanemertini", "❄️balminess", "❄️homotypy", "❄️waremaker", "❄️absurdity", "❄️gimcrack", "❄️asquat", "❄️suitable", "❄️perimorphous", "❄️kitchenwards", "❄️pielum", "❄️salloo", "❄️paleontologic", "❄️Olson", "❄️Tellinidae", "❄️ferryman", "❄️peptonoid", "❄️Bopyridae", "❄️fallacy", "❄️ictuate", "❄️aguinaldo", "❄️rhyodacite", "❄️Ligydidae", "❄️galvanometric", "❄️acquisitor", "❄️muscology", "❄️hemikaryon", "❄️ethnobotanic", "❄️postganglionic", "❄️rudimentarily", "❄️replenish", "❄️phyllorhine", "❄️popgunnery", "❄️summar", "❄️quodlibetary", "❄️xanthochromia", "❄️autosymbolically", "❄️preloreal", "❄️extent", "❄️strawberry", "❄️immortalness", "❄️colicwort", "❄️frisca", "❄️electiveness", "❄️heartbroken", "❄️affrightingly", "❄️reconfiscation", "❄️jacchus", "❄️imponderably", "❄️semantics", "❄️beennut", "❄️paleometeorological", "❄️becost", "❄️timberwright", "❄️resuppose", "❄️syncategorematical", "❄️cytolymph", "❄️steinbok", "❄️explantation", "❄️hyperelliptic", "❄️antescript", "❄️blowdown", "❄️antinomical", "❄️caravanserai", "❄️unweariedly", "❄️isonymic", "❄️keratoplasty", "❄️vipery", "❄️parepigastric", "❄️endolymphatic", "❄️Londonese", "❄️necrotomy", "❄️angelship", "❄️Schizogregarinida", "❄️steeplebush", "❄️sparaxis", "❄️connectedness", "❄️tolerance", "❄️impingent", "❄️agglutinin", "❄️reviver", "❄️hieroglyphical", "❄️dialogize", "❄️coestate", "❄️declamatory", "❄️ventilation", "❄️tauromachy", "❄️cotransubstantiate", "❄️pome", "❄️underseas", "❄️triquadrantal", "❄️preconfinemnt", "❄️electroindustrial", "❄️selachostomous", "❄️nongolfer", "❄️mesalike", "❄️hamartiology", "❄️ganglioblast", "❄️unsuccessive", "❄️yallow", "❄️bacchanalianly", "❄️platydactyl", "❄️Bucephala", "❄️ultraurgent", "❄️penalist", "❄️catamenial", "❄️lynnhaven", "❄️unrelevant", "❄️lunkhead", "❄️metropolitan", "❄️hydro", "❄️outsoar", "❄️vernant", "❄️interlanguage", "❄️catarrhal", "❄️Ionicize", "❄️keelless", "❄️myomantic", "❄️booker", "❄️Xanthomonas", "❄️unimpeded", "❄️overfeminize", "❄️speronaro", "❄️diaconia", "❄️overholiness", "❄️liquefacient", "❄️Spartium", "❄️haggly", "❄️albumose", "❄️nonnecessary", "❄️sulcalization", "❄️decapitate", "❄️cellated", "❄️unguirostral", "❄️trichiurid", "❄️loveproof", "❄️amakebe", "❄️screet", "❄️arsenoferratin", "❄️unfrizz", "❄️undiscoverable", "❄️procollectivistic", "❄️tractile", "❄️Winona", "❄️dermostosis", "❄️eliminant", "❄️scomberoid", "❄️tensile", "❄️typesetting", "❄️xylic", "❄️dermatopathology", "❄️cycloplegic", "❄️revocable", "❄️fissate", "❄️afterplay", "❄️screwship", "❄️microerg", "❄️bentonite", "❄️stagecoaching", "❄️beglerbeglic", "❄️overcharitably", "❄️Plotinism", "❄️Veddoid", "❄️disequalize", "❄️cytoproct", "❄️trophophore", "❄️antidote", "❄️allerion", "❄️famous", "❄️convey", "❄️postotic", "❄️rapillo", "❄️cilectomy", "❄️penkeeper", "❄️patronym", "❄️bravely", "❄️ureteropyelitis", "❄️Hildebrandine", "❄️missileproof", "❄️Conularia", "❄️deadening", "❄️Conrad", "❄️pseudochylous", "❄️typologically", "❄️strummer", "❄️luxuriousness", "❄️resublimation", "❄️glossiness", "❄️hydrocauline", "❄️anaglyph", "❄️personifiable", "❄️seniority", "❄️formulator", "❄️datiscaceous", "❄️hydracrylate", "❄️Tyranni", "❄️Crawthumper", "❄️overprove", "❄️masher", "❄️dissonance", "❄️Serpentinian", "❄️malachite", "❄️interestless", "❄️stchi", "❄️ogum", "❄️polyspermic", "❄️archegoniate", "❄️precogitation", "❄️Alkaphrah", "❄️craggily", "❄️delightfulness", "❄️bioplast", "❄️diplocaulescent", "❄️neverland", "❄️interspheral", "❄️chlorhydric", "❄️forsakenly", "❄️scandium", "❄️detubation", "❄️telega", "❄️Valeriana", "❄️centraxonial", "❄️anabolite", "❄️neger", "❄️miscellanea", "❄️whalebacker", "❄️stylidiaceous", "❄️unpropelled", "❄️Kennedya", "❄️Jacksonite", "❄️ghoulish", "❄️Dendrocalamus", "❄️paynimhood", "❄️rappist", "❄️unluffed", "❄️falling", "❄️Lyctus", "❄️uncrown", "❄️warmly", "❄️pneumatism", "❄️Morisonian", "❄️notate", "❄️isoagglutinin", "❄️Pelidnota", "❄️previsit", "❄️contradistinctly", "❄️utter", "❄️porometer", "❄️gie", "❄️germanization", "❄️betwixt", "❄️prenephritic", "❄️underpier", "❄️Eleutheria", "❄️ruthenious", "❄️convertor", "❄️antisepsin", "❄️winterage", "❄️tetramethylammonium", "❄️Rockaway", "❄️Penaea", "❄️prelatehood", "❄️brisket", "❄️unwishful", "❄️Minahassa", "❄️Briareus", "❄️semiaxis", "❄️disintegrant", "❄️peastick", "❄️iatromechanical", "❄️fastus", "❄️thymectomy", "❄️ladyless", "❄️unpreened", "❄️overflutter", "❄️sicker", "❄️apsidally", "❄️thiazine", "❄️guideway", "❄️pausation", "❄️tellinoid", "❄️abrogative", "❄️foraminulate", "❄️omphalos", "❄️Monorhina", "❄️polymyarian", "❄️unhelpful", "❄️newslessness", "❄️oryctognosy", "❄️octoradial", "❄️doxology", "❄️arrhythmy", "❄️gugal", "❄️mesityl", "❄️hexaplaric", "❄️Cabirian", "❄️hordeiform", "❄️eddyroot", "❄️internarial", "❄️deservingness", "❄️jawbation", "❄️orographically", "❄️semiprecious", "❄️seasick", "❄️thermically", "❄️grew", "❄️tamability", "❄️egotistically", "❄️fip", "❄️preabsorbent", "❄️leptochroa", "❄️ethnobotany", "❄️podolite", "❄️egoistic", "❄️semitropical", "❄️cero", "❄️spinelessness", "❄️onshore", "❄️omlah", "❄️tintinnabulist", "❄️machila", "❄️entomotomy", "❄️nubile", "❄️nonscholastic", "❄️burnt", "❄️Alea", "❄️befume", "❄️doctorless", "❄️Napoleonic", "❄️scenting", "❄️apokreos", "❄️cresylene", "❄️paramide", "❄️rattery", "❄️disinterested", "❄️idiopathetic", "❄️negatory", "❄️fervid", "❄️quintato", "❄️untricked", "❄️Metrosideros", "❄️mescaline", "❄️midverse", "❄️Musophagidae", "❄️fictionary", "❄️branchiostegous", "❄️yoker", "❄️residuum", "❄️culmigenous", "❄️fleam", "❄️suffragism", "❄️Anacreon", "❄️sarcodous", "❄️parodistic", "❄️writmaking", "❄️conversationism", "❄️retroposed", "❄️tornillo", "❄️presuspect", "❄️didymous", "❄️Saumur", "❄️spicing", "❄️drawbridge", "❄️cantor", "❄️incumbrancer", "❄️heterospory", "❄️Turkeydom", "❄️anteprandial", "❄️neighbourship", "❄️thatchless", "❄️drepanoid", "❄️lusher", "❄️paling", "❄️ecthlipsis", "❄️heredosyphilitic", "❄️although", "❄️garetta", "❄️temporarily", "❄️Monotropa", "❄️proglottic", "❄️calyptro", "❄️persiflage", "❄️degradable", "❄️paraspecific", "❄️undecorative", "❄️Pholas", "❄️myelon", "❄️resteal", "❄️quadrantly", "❄️scrimped", "❄️airer", "❄️deviless", "❄️caliciform", "❄️Sefekhet", "❄️shastaite", "❄️togate", "❄️macrostructure", "❄️bipyramid", "❄️wey", "❄️didynamy", "❄️knacker", "❄️swage", "❄️supermanism", "❄️epitheton", "❄️overpresumptuous" ] public func run_SortStringsUnicode(_ N: Int) { for _ in 1...5*N { benchSortStrings(stringBenchmarkWordsUnicode) } }
apache-2.0
4729cdc60a0a162a93fd28e7034fdf38
16.036765
80
0.58475
2.535751
false
false
false
false
AdamZikmund/strv
strv/strv/Classes/Handler/ForecastHandler.swift
1
1989
// // ForecastHandler.swift // strv // // Created by Adam Zikmund on 14.05.15. // Copyright (c) 2015 Adam Zikmund. All rights reserved. // import UIKit import CoreLocation import Alamofire class ForecastHandler: NSObject { class func getWeatherForCity(city : City, completionHandler : (Weather) -> Void){ let url = "http://api.openweathermap.org/data/2.5/weather" let parameters = ["q" : "\(city.name),\(city.stateCode)", "units" : "metric"] Alamofire.request(.GET, url, parameters: parameters, encoding: ParameterEncoding.URL) .responseJSON(options: NSJSONReadingOptions.MutableContainers) { (_, _, json, error) -> Void in if error == nil { if let json = json as? [String : AnyObject] { let weather = Weather(weatherJson: json) completionHandler(weather) } } } } class func getForecastForCity(city : City, completionHandler : ([Weather]) -> Void){ let url = "http://api.openweathermap.org/data/2.5/forecast/daily" let parameters : [String : AnyObject] = ["q" : "\(city.name),\(city.stateCode)", "cnt" : 7, "units" : "metric"] Alamofire.request(.GET, url, parameters: parameters , encoding: ParameterEncoding.URL) .responseJSON(options: NSJSONReadingOptions.MutableContainers) { (_, _, json, error) -> Void in if error == nil { if let json = json as? [String : AnyObject] { if let list = json["list"] as? [[String : AnyObject]] { var forecast = [Weather]() for object in list { forecast.append(Weather(forecastJson: object)) } completionHandler(forecast) } } } } } }
mit
53d110fc027fd90e326499b4026b1b16
39.591837
119
0.524384
4.758373
false
false
false
false
weirenxin/QRcode
QRcode/QRcode/Classes/ScanQRCode/ViewController/ScanQRCodeVC.swift
1
5946
// // ScanQRCodeVC.swift // QRcode // // Created by weirenxin on 2016/11/3. // Copyright © 2016年 广西家饰宝科技有限公司. All rights reserved. // import UIKit import AVFoundation class ScanQRCodeVC: UIViewController { @IBOutlet weak var scanBackView: UIView! @IBOutlet weak var scanView: UIImageView! @IBOutlet weak var scanViewBottomConstraint: NSLayoutConstraint! var session: AVCaptureSession? weak var layer: AVCaptureVideoPreviewLayer? @IBAction func startAction(_ sender: UIButton) { startAnimation() //startScan() QRCodeTool.shareInstance.setRectInterest(scanBackView.frame) QRCodeTool.shareInstance.scanQRCode(view, true, resultBlock:{ (resultStrs) in print(resultStrs) }); } @IBAction func stopAction(_ sender: UIButton) { removeAnimation() } } // MARK: - 扫描区域 边框 extension ScanQRCodeVC { fileprivate func startScan() { // 1.设置输入/获取摄像头设备 let cameraDevice = AVCaptureDevice.defaultDevice(withMediaType: AVMediaTypeVideo) // 把摄像头设备当做输入设备 var input: AVCaptureDeviceInput? do { input = try AVCaptureDeviceInput(device: cameraDevice) } catch { print(error) return } // 2.设置输出 let output = AVCaptureMetadataOutput() output.setMetadataObjectsDelegate(self, queue: DispatchQueue.main) // 3.创建会话/ 连接输入输出 session = AVCaptureSession() if session!.canAddInput(input) && session!.canAddOutput(output) { session?.addInput(input) session?.addOutput(output) }else { return } /**** 设置识别类型,必须在添加输入输出之后 ****/ // 4.设置二维码可以识别的码制 output.metadataObjectTypes = [AVMetadataObjectTypeQRCode] // 5.设置扫描区域 let bounds = UIScreen.main.bounds let x: CGFloat = scanBackView.frame.origin.x / bounds.size.width let y: CGFloat = scanBackView.frame.origin.y / bounds.size.height let width: CGFloat = scanBackView.frame.size.width / bounds.size.width let height: CGFloat = scanBackView.frame.size.height / bounds.size.height output.rectOfInterest = CGRect(x: y, y: x, width: height, height: width) // 6.添加视频预览图层 let layer = AVCaptureVideoPreviewLayer(session: session) layer?.frame = view.layer.bounds view.layer.insertSublayer(layer!, at: 0) self.layer = layer // 7.启动会话 [让输入开始采集数据, 输出对象,开始处理数据] session?.startRunning() } } // MARK: - AVCaptureMetadataOutputObjectsDelegate extension ScanQRCodeVC : AVCaptureMetadataOutputObjectsDelegate { // 扫描到结果之后调用 func captureOutput(_ captureOutput: AVCaptureOutput!, didOutputMetadataObjects metadataObjects: [Any]!, from connection: AVCaptureConnection!) { removeFrameLayer() for obj in metadataObjects { if (obj as AnyObject).isKind(of: AVMetadataMachineReadableCodeObject.self) { // 转换成为, 二维码, 在预览图层上的真正坐标 // qrCodeObj.corners 代表二维码的四个角, // 但是, 需要借助视频预览 图层,转换成为,我们需要的可以用的坐标 let resultObj = self.layer?.transformedMetadataObject(for: obj as! AVMetadataObject) let qrCodeObj = resultObj as! AVMetadataMachineReadableCodeObject print(qrCodeObj.stringValue) print(qrCodeObj.corners) drawFrame(qrCodeObj) } } } private func drawFrame(_ qrCodeObj: AVMetadataMachineReadableCodeObject) { let corners = qrCodeObj.corners // 1. 借助一个图形层, 来绘制 let shapLayer = CAShapeLayer() shapLayer.fillColor = UIColor.clear.cgColor shapLayer.strokeColor = UIColor.red.cgColor shapLayer.lineWidth = 6 // 2. 根据四个点, 创建一个路径 let path = UIBezierPath() var index = 0 for corner in corners! { let pointDic = corner as! CFDictionary let point = CGPoint(dictionaryRepresentation: pointDic)! // 第一个点 if index == 0 { path.move(to: point) }else { path.addLine(to: point) } index += 1 } path.close() // 3. 给图形图层的路径赋值, 代表, 图层展示怎样的形状 shapLayer.path = path.cgPath // 4. 直接添加图形图层到需要展示的图层 layer?.addSublayer(shapLayer) } private func removeFrameLayer() -> () { guard let subLayers = layer?.sublayers else {return} for subLayer in subLayers { if subLayer.isKind(of: CAShapeLayer.self) { subLayer.removeFromSuperlayer() } } } } extension ScanQRCodeVC { fileprivate func startAnimation() { scanViewBottomConstraint.constant = scanBackView.frame.size.height view.layoutIfNeeded() scanViewBottomConstraint.constant = -scanBackView.frame.size.height UIView.animate(withDuration: 1, animations:{ UIView.setAnimationRepeatCount(MAXFLOAT) self.view.layoutIfNeeded() }); } fileprivate func removeAnimation() { scanView.layer.removeAllAnimations() } }
apache-2.0
5457d99244cac07112183c252c19a284
29.283333
148
0.589433
4.794195
false
false
false
false
vmanot/swift-package-manager
Sources/Basic/PathShims.swift
1
12686
/* This source file is part of the Swift.org open source project Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors Licensed under Apache License v2.0 with Runtime Library Exception See http://swift.org/LICENSE.txt for license information See http://swift.org/CONTRIBUTORS.txt for Swift project authors */ import libc import POSIX import Foundation /// This file contains temporary shim functions for use during the adoption of /// AbsolutePath and RelativePath. The eventual plan is to use the FileSystem /// API for all of this, at which time this file will go way. But since it is /// important to have a quality FileSystem API, we will evolve it slowly. /// /// Meanwhile this file bridges the gap to let call sites be as clean as pos- /// sible, while making it fairly easy to find those calls later. /// Returns a structure containing information about the file system entity at `path`, or nil /// if that path doesn't exist in the file system. Read, write or execute permission of the /// file system entity at `path` itself is not required, but all ancestor directories must be searchable. /// If they are not, or if any other file system error occurs, this function throws a SystemError. /// If `followSymlink` is true and the file system entity at `path` is a symbolic link, it is traversed; /// otherwise it is not (any symbolic links in path components other than the last one are always traversed). /// If symbolic links are followed and the file system entity at `path` is a symbolic link that points to a /// non-existent path, then this function returns nil. private func stat(_ path: AbsolutePath, followSymlink: Bool = true) throws -> libc.stat { if followSymlink { return try stat(path.asString) } return try lstat(path.asString) } /// Returns true if and only if `path` refers to an existent file system entity. /// If `followSymlink` is true, and the last path component is a symbolic link, the result pertains /// to the destination of the symlink; otherwise it pertains to the symlink itself. /// If any file system error other than non-existence occurs, this function throws an error. public func exists(_ path: AbsolutePath, followSymlink: Bool = true) -> Bool { return (try? stat(path, followSymlink: followSymlink)) != nil } /// Returns true if and only if `path` refers to an existent file system entity and that entity is a regular file. /// If `followSymlink` is true, and the last path component is a symbolic link, the result pertains to the destination /// of the symlink; otherwise it pertains to the symlink itself. If any file system error other than non-existence /// occurs, this function throws an error. public func isFile(_ path: AbsolutePath, followSymlink: Bool = true) -> Bool { guard let status = try? stat(path, followSymlink: followSymlink), status.kind == .file else { return false } return true } /// Returns true if and only if `path` refers to an existent file system entity and that entity is a directory. /// If `followSymlink` is true, and the last path component is a symbolic link, the result pertains to the destination /// of the symlink; otherwise it pertains to the symlink itself. If any file system error other than non-existence /// occurs, this function throws an error. public func isDirectory(_ path: AbsolutePath, followSymlink: Bool = true) -> Bool { guard let status = try? stat(path, followSymlink: followSymlink), status.kind == .directory else { return false } return true } /// Returns true if and only if `path` refers to an existent file system entity and that entity is a symbolic link. /// If any file system error other than non-existence occurs, this function throws an error. public func isSymlink(_ path: AbsolutePath) -> Bool { guard let status = try? stat(path, followSymlink: false), status.kind == .symlink else { return false } return true } /// Returns the "real path" corresponding to `path` by resolving any symbolic links. public func resolveSymlinks(_ path: AbsolutePath) -> AbsolutePath { let pathStr = path.asString guard let resolvedPathStr = try? POSIX.realpath(pathStr) else { return path } // FIXME: We should measure if it's really more efficient to compare the strings first. return (resolvedPathStr == pathStr) ? path : AbsolutePath(resolvedPathStr) } /// Creates a new, empty directory at `path`. If needed, any non-existent ancestor paths are also created. If there is /// already a directory at `path`, this function does nothing (in particular, this is not considered to be an error). public func makeDirectories(_ path: AbsolutePath) throws { try FileManager.default.createDirectory(atPath: path.asString, withIntermediateDirectories: true, attributes: [:]) } /// Recursively deletes the file system entity at `path`. If there is no file system entity at `path`, this function /// does nothing (in particular, this is not considered to be an error). public func removeFileTree(_ path: AbsolutePath) throws { try FileManager.default.removeItem(atPath: path.asString) } /// Creates a symbolic link at `path` whose content points to `dest`. If `relative` is true, the symlink contents will /// be a relative path, otherwise it will be absolute. public func createSymlink(_ path: AbsolutePath, pointingAt dest: AbsolutePath, relative: Bool = true) throws { let destString = relative ? dest.relative(to: path.parentDirectory).asString : dest.asString let rv = libc.symlink(destString, path.asString) guard rv == 0 else { throw SystemError.symlink(errno, path.asString, dest: destString) } } public func rename(_ path: AbsolutePath, to dest: AbsolutePath) throws { let rv = libc.rename(path.asString, dest.asString) guard rv == 0 else { throw SystemError.rename(errno, old: path.asString, new: dest.asString) } } public func unlink(_ path: AbsolutePath) throws { let rv = libc.unlink(path.asString) guard rv == 0 else { throw SystemError.unlink(errno, path.asString) } } /// The current working directory of the process (same as returned by POSIX' `getcwd()` function or Foundation's /// `currentDirectoryPath` method). /// FIXME: This should probably go onto `FileSystem`, under the assumption that each file system has its own notion of /// the `current` working directory. public var currentWorkingDirectory: AbsolutePath { let cwdStr = FileManager.default.currentDirectoryPath return AbsolutePath(cwdStr) } /** - Returns: a generator that walks the specified directory producing all files therein. If recursively is true will enter any directories encountered recursively. - Warning: directories that cannot be entered due to permission problems are silently ignored. So keep that in mind. - Warning: Symbolic links that point to directories are *not* followed. - Note: setting recursively to `false` still causes the generator to feed you the directory; just not its contents. */ public func walk( _ path: AbsolutePath, fileSystem: FileSystem = localFileSystem, recursively: Bool = true ) throws -> RecursibleDirectoryContentsGenerator { return try RecursibleDirectoryContentsGenerator( path: path, fileSystem: fileSystem, recursionFilter: { _ in recursively }) } /** - Returns: a generator that walks the specified directory producing all files therein. Directories are recursed based on the return value of `recursing`. - Warning: directories that cannot be entered due to permissions problems are silently ignored. So keep that in mind. - Warning: Symbolic links that point to directories are *not* followed. - Note: returning `false` from `recursing` still produces that directory from the generator; just not its contents. */ public func walk( _ path: AbsolutePath, fileSystem: FileSystem = localFileSystem, recursing: @escaping (AbsolutePath) -> Bool ) throws -> RecursibleDirectoryContentsGenerator { return try RecursibleDirectoryContentsGenerator(path: path, fileSystem: fileSystem, recursionFilter: recursing) } /** Produced by `walk`. */ public class RecursibleDirectoryContentsGenerator: IteratorProtocol, Sequence { private var current: (path: AbsolutePath, iterator: IndexingIterator<[String]>) private var towalk = [AbsolutePath]() private let shouldRecurse: (AbsolutePath) -> Bool private let fileSystem: FileSystem fileprivate init( path: AbsolutePath, fileSystem: FileSystem, recursionFilter: @escaping (AbsolutePath) -> Bool ) throws { self.fileSystem = fileSystem // FIXME: getDirectoryContents should have an iterator version. current = (path, try fileSystem.getDirectoryContents(path).makeIterator()) shouldRecurse = recursionFilter } public func next() -> AbsolutePath? { outer: while true { guard let entry = current.iterator.next() else { while !towalk.isEmpty { // FIXME: This looks inefficient. let path = towalk.removeFirst() guard shouldRecurse(path) else { continue } // Ignore if we can't get content for this path. guard let current = try? fileSystem.getDirectoryContents(path).makeIterator() else { continue } self.current = (path, current) continue outer } return nil } let path = current.path.appending(component: entry) if fileSystem.isDirectory(path) && !fileSystem.isSymlink(path) { towalk.append(path) } return path } } } extension AbsolutePath { /// Returns a path suitable for display to the user (if possible, it is made /// to be relative to the current working directory). /// - Note: Therefore this function relies on the working directory's not /// changing during execution. public var prettyPath: String { let currDir = currentWorkingDirectory // FIXME: Instead of string prefix comparison we should add a proper API // to AbsolutePath to determine ancestry. if self == currDir { return "." } else if self.asString.hasPrefix(currDir.asString + "/") { return "./" + self.relative(to: currDir).asString } else { return self.asString } } } // FIXME: All of the following will move to the FileSystem class. public enum FileAccessError: Swift.Error { case unicodeDecodingError case unicodeEncodingError case couldNotCreateFile(path: String) case fileDoesNotExist(path: String) } extension FileAccessError: CustomStringConvertible { public var description: String { switch self { case .unicodeDecodingError: return "could not decode input file into unicode" case .unicodeEncodingError: return "could not encode string into unicode" case .couldNotCreateFile(let path): return "could not create file: \(path)" case .fileDoesNotExist(let path): return "file does not exist: \(path)" } } } public enum FopenMode: String { case read = "r" case write = "w" } public func fopen(_ path: AbsolutePath, mode: FopenMode = .read) throws -> FileHandle { let handle: FileHandle! switch mode { case .read: handle = FileHandle(forReadingAtPath: path.asString) case .write: let success = FileManager.default.createFile(atPath: path.asString, contents: nil) guard success else { throw FileAccessError.couldNotCreateFile(path: path.asString) } handle = FileHandle(forWritingAtPath: path.asString) } guard handle != nil else { throw FileAccessError.fileDoesNotExist(path: path.asString) } return handle } public func fopen<T>(_ path: AbsolutePath, mode: FopenMode = .read, body: (FileHandle) throws -> T) throws -> T { let fp = try fopen(path, mode: mode) defer { fp.closeFile() } return try body(fp) } public func fputs(_ string: String, _ handle: FileHandle) throws { guard let data = string.data(using: .utf8) else { throw FileAccessError.unicodeEncodingError } handle.write(data) } public func fputs(_ bytes: [UInt8], _ handle: FileHandle) throws { handle.write(Data(bytes: bytes)) } extension FileHandle { public func readFileContents() throws -> String { guard let contents = String(data: readDataToEndOfFile(), encoding: .utf8) else { throw FileAccessError.unicodeDecodingError } return contents } }
apache-2.0
3e07383b309ef5019779b805cb3437da
41.286667
120
0.70361
4.525865
false
false
false
false
russbishop/swift
stdlib/public/SDK/Dispatch/Source.swift
1
16410
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // import Foundation public extension DispatchSourceType { typealias DispatchSourceHandler = @convention(block) () -> Void public func setEventHandler(qos: DispatchQoS = .unspecified, flags: DispatchWorkItemFlags = [], handler: DispatchSourceHandler?) { if #available(OSX 10.10, iOS 8.0, *), let h = handler, qos != .unspecified || !flags.isEmpty { let item = DispatchWorkItem(qos: qos, flags: flags, block: h) __dispatch_source_set_event_handler(self as! DispatchSource, item._block) } else { __dispatch_source_set_event_handler(self as! DispatchSource, handler) } } @available(OSX 10.10, iOS 8.0, *) public func setEventHandler(handler: DispatchWorkItem) { __dispatch_source_set_event_handler(self as! DispatchSource, handler._block) } public func setCancelHandler(qos: DispatchQoS = .unspecified, flags: DispatchWorkItemFlags = [], handler: DispatchSourceHandler?) { if #available(OSX 10.10, iOS 8.0, *), let h = handler, qos != .unspecified || !flags.isEmpty { let item = DispatchWorkItem(qos: qos, flags: flags, block: h) __dispatch_source_set_cancel_handler(self as! DispatchSource, item._block) } else { __dispatch_source_set_cancel_handler(self as! DispatchSource, handler) } } @available(OSX 10.10, iOS 8.0, *) public func setCancelHandler(handler: DispatchWorkItem) { __dispatch_source_set_cancel_handler(self as! DispatchSource, handler._block) } public func setRegistrationHandler(qos: DispatchQoS = .unspecified, flags: DispatchWorkItemFlags = [], handler: DispatchSourceHandler?) { if #available(OSX 10.10, iOS 8.0, *), let h = handler, qos != .unspecified || !flags.isEmpty { let item = DispatchWorkItem(qos: qos, flags: flags, block: h) __dispatch_source_set_registration_handler(self as! DispatchSource, item._block) } else { __dispatch_source_set_registration_handler(self as! DispatchSource, handler) } } @available(OSX 10.10, iOS 8.0, *) public func setRegistrationHandler(handler: DispatchWorkItem) { __dispatch_source_set_registration_handler(self as! DispatchSource, handler._block) } @available(OSX 10.12, iOS 10.0, tvOS 10.0, watchOS 3.0, *) public func activate() { (self as! DispatchSource).activate() } public func cancel() { __dispatch_source_cancel(self as! DispatchSource) } public func resume() { (self as! DispatchSource).resume() } public func suspend() { (self as! DispatchSource).suspend() } public var handle: UInt { return __dispatch_source_get_handle(self as! DispatchSource) } public var mask: UInt { return __dispatch_source_get_mask(self as! DispatchSource) } public var data: UInt { return __dispatch_source_get_data(self as! DispatchSource) } public var isCancelled: Bool { return __dispatch_source_testcancel(self as! DispatchSource) != 0 } } public extension DispatchSource { public struct MachSendEvent : OptionSet, RawRepresentable { public let rawValue: UInt public init(rawValue: UInt) { self.rawValue = rawValue } public static let dead = MachSendEvent(rawValue: 0x1) } public struct MemoryPressureEvent : OptionSet, RawRepresentable { public let rawValue: UInt public init(rawValue: UInt) { self.rawValue = rawValue } public static let normal = MemoryPressureEvent(rawValue: 0x1) public static let warning = MemoryPressureEvent(rawValue: 0x2) public static let critical = MemoryPressureEvent(rawValue: 0x4) public static let all: MemoryPressureEvent = [.normal, .warning, .critical] } public struct ProcessEvent : OptionSet, RawRepresentable { public let rawValue: UInt public init(rawValue: UInt) { self.rawValue = rawValue } public static let exit = ProcessEvent(rawValue: 0x80000000) public static let fork = ProcessEvent(rawValue: 0x40000000) public static let exec = ProcessEvent(rawValue: 0x20000000) public static let signal = ProcessEvent(rawValue: 0x08000000) public static let all: ProcessEvent = [.exit, .fork, .exec, .signal] } public struct TimerFlags : OptionSet, RawRepresentable { public let rawValue: UInt public init(rawValue: UInt) { self.rawValue = rawValue } public static let strict = TimerFlags(rawValue: 1) } public struct FileSystemEvent : OptionSet, RawRepresentable { public let rawValue: UInt public init(rawValue: UInt) { self.rawValue = rawValue } public static let delete = FileSystemEvent(rawValue: 0x1) public static let write = FileSystemEvent(rawValue: 0x2) public static let extend = FileSystemEvent(rawValue: 0x4) public static let attrib = FileSystemEvent(rawValue: 0x8) public static let link = FileSystemEvent(rawValue: 0x10) public static let rename = FileSystemEvent(rawValue: 0x20) public static let revoke = FileSystemEvent(rawValue: 0x40) public static let funlock = FileSystemEvent(rawValue: 0x100) public static let all: FileSystemEvent = [ .delete, .write, .extend, .attrib, .link, .rename, .revoke] } public class func machSend(port: mach_port_t, eventMask: MachSendEvent, queue: DispatchQueue? = nil) -> DispatchSourceMachSend { return __dispatch_source_create( _swift_dispatch_source_type_mach_send(), UInt(port), eventMask.rawValue, queue) as DispatchSourceMachSend } public class func machReceive(port: mach_port_t, queue: DispatchQueue? = nil) -> DispatchSourceMachReceive { return __dispatch_source_create( _swift_dispatch_source_type_mach_recv(), UInt(port), 0, queue) as DispatchSourceMachReceive } public class func memoryPressure(eventMask: MemoryPressureEvent, queue: DispatchQueue? = nil) -> DispatchSourceMemoryPressure { return __dispatch_source_create( _swift_dispatch_source_type_memorypressure(), 0, eventMask.rawValue, queue) as DispatchSourceMemoryPressure } public class func process(identifier: pid_t, eventMask: ProcessEvent, queue: DispatchQueue? = nil) -> DispatchSourceProcess { return __dispatch_source_create( _swift_dispatch_source_type_proc(), UInt(identifier), eventMask.rawValue, queue) as DispatchSourceProcess } public class func read(fileDescriptor: Int32, queue: DispatchQueue? = nil) -> DispatchSourceRead { return __dispatch_source_create( _swift_dispatch_source_type_read(), UInt(fileDescriptor), 0, queue) as DispatchSourceRead } public class func signal(signal: Int32, queue: DispatchQueue? = nil) -> DispatchSourceSignal { return __dispatch_source_create( _swift_dispatch_source_type_read(), UInt(signal), 0, queue) as DispatchSourceSignal } public class func timer(flags: TimerFlags = [], queue: DispatchQueue? = nil) -> DispatchSourceTimer { return __dispatch_source_create(_swift_dispatch_source_type_timer(), 0, flags.rawValue, queue) as DispatchSourceTimer } public class func userDataAdd(queue: DispatchQueue? = nil) -> DispatchSourceUserDataAdd { return __dispatch_source_create(_swift_dispatch_source_type_data_add(), 0, 0, queue) as DispatchSourceUserDataAdd } public class func userDataOr(queue: DispatchQueue? = nil) -> DispatchSourceUserDataOr { return __dispatch_source_create(_swift_dispatch_source_type_data_or(), 0, 0, queue) as DispatchSourceUserDataOr } public class func fileSystemObject(fileDescriptor: Int32, eventMask: FileSystemEvent, queue: DispatchQueue? = nil) -> DispatchSourceFileSystemObject { return __dispatch_source_create( _swift_dispatch_source_type_vnode(), UInt(fileDescriptor), eventMask.rawValue, queue) as DispatchSourceFileSystemObject } public class func write(fileDescriptor: Int32, queue: DispatchQueue? = nil) -> DispatchSourceWrite { return __dispatch_source_create( _swift_dispatch_source_type_write(), UInt(fileDescriptor), 0, queue) as DispatchSourceWrite } } public extension DispatchSourceMachSend { public var handle: mach_port_t { return mach_port_t(__dispatch_source_get_handle(self as! DispatchSource)) } public var data: DispatchSource.MachSendEvent { let data = __dispatch_source_get_data(self as! DispatchSource) return DispatchSource.MachSendEvent(rawValue: data) } public var mask: DispatchSource.MachSendEvent { let mask = __dispatch_source_get_mask(self as! DispatchSource) return DispatchSource.MachSendEvent(rawValue: mask) } } public extension DispatchSourceMachReceive { public var handle: mach_port_t { return mach_port_t(__dispatch_source_get_handle(self as! DispatchSource)) } } public extension DispatchSourceMemoryPressure { public var data: DispatchSource.MemoryPressureEvent { let data = __dispatch_source_get_data(self as! DispatchSource) return DispatchSource.MemoryPressureEvent(rawValue: data) } public var mask: DispatchSource.MemoryPressureEvent { let mask = __dispatch_source_get_mask(self as! DispatchSource) return DispatchSource.MemoryPressureEvent(rawValue: mask) } } public extension DispatchSourceProcess { public var handle: pid_t { return pid_t(__dispatch_source_get_handle(self as! DispatchSource)) } public var data: DispatchSource.ProcessEvent { let data = __dispatch_source_get_data(self as! DispatchSource) return DispatchSource.ProcessEvent(rawValue: data) } public var mask: DispatchSource.ProcessEvent { let mask = __dispatch_source_get_mask(self as! DispatchSource) return DispatchSource.ProcessEvent(rawValue: mask) } } public extension DispatchSourceTimer { public func scheduleOneshot(deadline: DispatchTime, leeway: DispatchTimeInterval = .nanoseconds(0)) { __dispatch_source_set_timer(self as! DispatchSource, deadline.rawValue, ~0, UInt64(leeway.rawValue)) } public func scheduleOneshot(wallDeadline: DispatchWallTime, leeway: DispatchTimeInterval = .nanoseconds(0)) { __dispatch_source_set_timer(self as! DispatchSource, wallDeadline.rawValue, ~0, UInt64(leeway.rawValue)) } public func scheduleRepeating(deadline: DispatchTime, interval: DispatchTimeInterval, leeway: DispatchTimeInterval = .nanoseconds(0)) { __dispatch_source_set_timer(self as! DispatchSource, deadline.rawValue, interval.rawValue, UInt64(leeway.rawValue)) } public func scheduleRepeating(deadline: DispatchTime, interval: Double, leeway: DispatchTimeInterval = .nanoseconds(0)) { __dispatch_source_set_timer(self as! DispatchSource, deadline.rawValue, UInt64(interval * Double(NSEC_PER_SEC)), UInt64(leeway.rawValue)) } public func scheduleRepeating(wallDeadline: DispatchWallTime, interval: DispatchTimeInterval, leeway: DispatchTimeInterval = .nanoseconds(0)) { __dispatch_source_set_timer(self as! DispatchSource, wallDeadline.rawValue, interval.rawValue, UInt64(leeway.rawValue)) } public func scheduleRepeating(wallDeadline: DispatchWallTime, interval: Double, leeway: DispatchTimeInterval = .nanoseconds(0)) { __dispatch_source_set_timer(self as! DispatchSource, wallDeadline.rawValue, UInt64(interval * Double(NSEC_PER_SEC)), UInt64(leeway.rawValue)) } } public extension DispatchSourceTimer { @available(*, deprecated, renamed: "DispatchSourceTimer.scheduleOneshot(self:deadline:leeway:)") public func setTimer(start: DispatchTime, leeway: DispatchTimeInterval = .nanoseconds(0)) { scheduleOneshot(deadline: start, leeway: leeway) } @available(*, deprecated, renamed: "DispatchSourceTimer.scheduleOneshot(self:wallDeadline:leeway:)") public func setTimer(walltime start: DispatchWallTime, leeway: DispatchTimeInterval = .nanoseconds(0)) { scheduleOneshot(wallDeadline: start, leeway: leeway) } @available(*, deprecated, renamed: "DispatchSourceTimer.scheduleRepeating(self:deadline:interval:leeway:)") public func setTimer(start: DispatchTime, interval: DispatchTimeInterval, leeway: DispatchTimeInterval = .nanoseconds(0)) { scheduleRepeating(deadline: start, interval: interval, leeway: leeway) } @available(*, deprecated, renamed: "DispatchSourceTimer.scheduleRepeating(self:deadline:interval:leeway:)") public func setTimer(start: DispatchTime, interval: Double, leeway: DispatchTimeInterval = .nanoseconds(0)) { scheduleRepeating(deadline: start, interval: interval, leeway: leeway) } @available(*, deprecated, renamed: "DispatchSourceTimer.scheduleRepeating(self:wallDeadline:interval:leeway:)") public func setTimer(walltime start: DispatchWallTime, interval: DispatchTimeInterval, leeway: DispatchTimeInterval = .nanoseconds(0)) { scheduleRepeating(wallDeadline: start, interval: interval, leeway: leeway) } @available(*, deprecated, renamed: "DispatchSourceTimer.scheduleRepeating(self:wallDeadline:interval:leeway:)") public func setTimer(walltime start: DispatchWalltime, interval: Double, leeway: DispatchTimeInterval = .nanoseconds(0)) { scheduleRepeating(wallDeadline: start, interval: interval, leeway: leeway) } } public extension DispatchSourceFileSystemObject { public var handle: Int32 { return Int32(__dispatch_source_get_handle(self as! DispatchSource)) } public var data: DispatchSource.FileSystemEvent { let data = __dispatch_source_get_data(self as! DispatchSource) return DispatchSource.FileSystemEvent(rawValue: data) } public var mask: DispatchSource.FileSystemEvent { let data = __dispatch_source_get_mask(self as! DispatchSource) return DispatchSource.FileSystemEvent(rawValue: data) } } public extension DispatchSourceUserDataAdd { /// @function mergeData /// /// @abstract /// Merges data into a dispatch source of type DISPATCH_SOURCE_TYPE_DATA_ADD or /// DISPATCH_SOURCE_TYPE_DATA_OR and submits its event handler block to its /// target queue. /// /// @param value /// The value to coalesce with the pending data using a logical OR or an ADD /// as specified by the dispatch source type. A value of zero has no effect /// and will not result in the submission of the event handler block. public func mergeData(value: UInt) { __dispatch_source_merge_data(self as! DispatchSource, value) } } public extension DispatchSourceUserDataOr { /// @function mergeData /// /// @abstract /// Merges data into a dispatch source of type DISPATCH_SOURCE_TYPE_DATA_ADD or /// DISPATCH_SOURCE_TYPE_DATA_OR and submits its event handler block to its /// target queue. /// /// @param value /// The value to coalesce with the pending data using a logical OR or an ADD /// as specified by the dispatch source type. A value of zero has no effect /// and will not result in the submission of the event handler block. public func mergeData(value: UInt) { __dispatch_source_merge_data(self as! DispatchSource, value) } } @_silgen_name("_swift_dispatch_source_type_DATA_ADD") internal func _swift_dispatch_source_type_data_add() -> __dispatch_source_type_t @_silgen_name("_swift_dispatch_source_type_DATA_OR") internal func _swift_dispatch_source_type_data_or() -> __dispatch_source_type_t @_silgen_name("_swift_dispatch_source_type_MACH_SEND") internal func _swift_dispatch_source_type_mach_send() -> __dispatch_source_type_t @_silgen_name("_swift_dispatch_source_type_MACH_RECV") internal func _swift_dispatch_source_type_mach_recv() -> __dispatch_source_type_t @_silgen_name("_swift_dispatch_source_type_MEMORYPRESSURE") internal func _swift_dispatch_source_type_memorypressure() -> __dispatch_source_type_t @_silgen_name("_swift_dispatch_source_type_PROC") internal func _swift_dispatch_source_type_proc() -> __dispatch_source_type_t @_silgen_name("_swift_dispatch_source_type_READ") internal func _swift_dispatch_source_type_read() -> __dispatch_source_type_t @_silgen_name("_swift_dispatch_source_type_SIGNAL") internal func _swift_dispatch_source_type_signal() -> __dispatch_source_type_t @_silgen_name("_swift_dispatch_source_type_TIMER") internal func _swift_dispatch_source_type_timer() -> __dispatch_source_type_t @_silgen_name("_swift_dispatch_source_type_VNODE") internal func _swift_dispatch_source_type_vnode() -> __dispatch_source_type_t @_silgen_name("_swift_dispatch_source_type_WRITE") internal func _swift_dispatch_source_type_write() -> __dispatch_source_type_t
apache-2.0
c1ca4b2e795cad1652b772123cfa4a5e
40.544304
151
0.743998
3.875768
false
false
false
false
mtzaquia/MTZTableViewManager
Example/Example/Cells/ActionCell.swift
1
2742
// // ActionCell.swift // MTZTableManager // // Copyright (c) 2017 Mauricio Tremea Zaquia (@mtzaquia) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import UIKit import MTZTableViewManager class ActionCell: UITableViewCell, MTZModelDisplaying { var labelActionTitle: UILabel! override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) labelActionTitle = UILabel() labelActionTitle.translatesAutoresizingMaskIntoConstraints = false labelActionTitle.textColor = UIApplication.shared.keyWindow?.rootViewController?.view.tintColor labelActionTitle.textAlignment = .center labelActionTitle.numberOfLines = 0 self.contentView.addSubview(labelActionTitle) let bottomConstraint = labelActionTitle.bottomAnchor.constraint(equalTo: self.contentView.bottomAnchor) bottomConstraint.priority = UILayoutPriority(rawValue: 999) NSLayoutConstraint.activate([ labelActionTitle.leadingAnchor.constraint(equalTo: self.contentView.leadingAnchor), labelActionTitle.trailingAnchor.constraint(equalTo: self.contentView.trailingAnchor), labelActionTitle.topAnchor.constraint(equalTo: self.contentView.topAnchor), labelActionTitle.heightAnchor.constraint(equalToConstant: 44), bottomConstraint ]) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func configure(with model: MTZModel?) { let model = model as? ActionCellModel labelActionTitle.text = model?.actionTitle } }
mit
838629c048c615f285592d534ec2ff32
42.52381
111
0.734136
5.106145
false
false
false
false
dsantosp12/DResume
Sources/App/Controllers/UserController.swift
1
5908
import Vapor import FluentProvider class UserController { func addRoutes(to drop: Droplet) { let userGroup = drop.grouped("api", "v1", "user") // Post userGroup.post(handler: createUser) userGroup.post(User.parameter, "skills", handler: addSkill) userGroup.post(User.parameter, "languages", handler: addLanguage) userGroup.post(User.parameter, "educations", handler: addEducation) userGroup.post(User.parameter, "attachments", handler: addAttachment) // Get userGroup.get(User.parameter, handler: getUser) userGroup.get(User.parameter, "skills", handler: getUserSkills) userGroup.get(User.parameter, "languages", handler: getLanguages) userGroup.get(User.parameter, "educations", handler: getEducation) userGroup.get(User.parameter, "attachments", handler: getAttachment) // Delete userGroup.delete(User.parameter, handler: removeUser) userGroup.delete("skill", Skill.parameter, handler: removeSkill) userGroup.delete("language", Language.parameter, handler: removeLanguage) userGroup.delete("education", Education.parameter, handler: removeEducation) userGroup.delete("attachment", Attachment.parameter, handler: removeAttachment) // Put userGroup.put(User.parameter, handler: updateUser) userGroup.put("skill", Skill.parameter, handler: updateSkill) userGroup.put("language", Language.parameter, handler: updateLanguage) userGroup.put("education", Education.parameter, handler: updateEducation) } // MARK: POSTERS func createUser(_ req: Request) throws -> ResponseRepresentable { guard let json = req.json else { throw Abort.badRequest } let user = try User(json: json) try user.save() return user } func addSkill(_ req: Request) throws -> ResponseRepresentable { guard let json = req.json else { throw Abort.badRequest } let skill = try Skill(json: json) try skill.save() return skill } func addLanguage(_ req: Request) throws -> ResponseRepresentable { let user = try req.parameters.next(User.self) guard var json = req.json else { throw Abort.badRequest } try json.set(Language.userIDKey, user.id) let language = try Language(json: json) try language.save() return language } func addEducation(_ req: Request) throws -> ResponseRepresentable { guard let json = req.json else { throw Abort.badRequest } let education = try Education(json: json) try education.save() return education } func addAttachment(_ req: Request) throws -> ResponseRepresentable { guard let json = req.json else { throw Abort.badRequest } let attachment = try Attachment(json: json) try attachment.save() return attachment } // MARK: GETTERS func getUser(_ req: Request) throws -> ResponseRepresentable { let user = try req.parameters.next(User.self) return user } func getUserSkills(_ req: Request) throws -> ResponseRepresentable { let user = try req.parameters.next(User.self) return try user.skills.all().makeJSON() } func getLanguages(_ req: Request) throws -> ResponseRepresentable { let user = try req.parameters.next(User.self) return try user.languages.all().makeJSON() } func getEducation(_ req: Request) throws -> ResponseRepresentable { let user = try req.parameters.next(User.self) return try user.educations.all().makeJSON() } func getAttachment(_ req: Request) throws -> ResponseRepresentable { let user = try req.parameters.next(User.self) return try user.attachments.all().makeJSON() } // MARK: DELETERS func removeUser(_ req: Request) throws -> ResponseRepresentable { let user = try req.parameters.next(User.self) try user.delete() return Response(status: .ok) } func removeSkill(_ req: Request) throws -> ResponseRepresentable { let skill = try req.parameters.next(Skill.self) try skill.delete() return Response(status: .ok) } func removeLanguage(_ req: Request) throws -> ResponseRepresentable { let language = try req.parameters.next(Language.self) try language.delete() return Response(status: .ok) } func removeEducation(_ req: Request) throws -> ResponseRepresentable { let education = try req.parameters.next(Education.self) try education.delete() return Response(status: .ok) } func removeAttachment(_ req: Request) throws -> ResponseRepresentable { let attachment = try req.parameters.next(Attachment.self) try attachment.delete() return Response(status: .ok) } // MARK: PUTTERS func updateUser(_ req: Request) throws -> ResponseRepresentable { let user = try req.parameters.next(User.self) guard let json = req.json else { throw Abort.badRequest } try user.update(with: json) return user } func updateSkill(_ req: Request) throws -> ResponseRepresentable { let skill = try req.parameters.next(Skill.self) guard let json = req.json else { throw Abort.badRequest } try skill.update(with: json) return skill } func updateLanguage(_ req: Request) throws -> ResponseRepresentable { let language = try req.parameters.next(Language.self) guard let json = req.json else { throw Abort.badRequest } try language.update(with: json) return language } func updateEducation(_ req: Request) throws -> ResponseRepresentable { let education = try req.parameters.next(Education.self) guard let json = req.json else { throw Abort.badRequest } try education.update(with: json) return education } }
mit
a47160bb4e41f13c986ed44b2691714f
24.033898
80
0.663846
4.369822
false
false
false
false
denizztret/ObjectiveHexagon
ObjectiveHexagonDemo/ObjectiveHexagonDemo/ViewController.swift
1
3655
// // ViewController.swift // ObjectiveHexagonDemo // // Created by Denis Tretyakov on 17.03.15. // Copyright (c) 2015 pythongem. All rights reserved. // import UIKit import ObjectiveHexagonKit let HEX_SIZE: CGFloat = 58.0 let HEX_RADIUS: CGFloat = 45.0 let DATA_COUNT: Int = 100 let DEBUG_DRAW = false let CELL_IS_CIRCLE = false let CELL_DRAW_TEXT = true class ViewController: UIViewController { @IBOutlet weak var collectionView: UICollectionView! var itemsGrid: HKHexagonGrid! var items: [HKHexagon]! override func viewDidLoad() { super.viewDidLoad() // Collection View if CELL_IS_CIRCLE { self.collectionView.registerClass(CollectionViewCellCircle.self, forCellWithReuseIdentifier: "CollectionViewCell") } else { self.collectionView.registerClass(CollectionViewCellHexagon.self, forCellWithReuseIdentifier: "CollectionViewCell") } self.collectionView.decelerationRate = UIScrollViewDecelerationRateFast self.collectionView.dataSource = self self.collectionView.delegate = self // Grid with Rectanglar Map let params = HKHexagonGrid.rectParamsForDataCount(DATA_COUNT, ratio: CGSizeMake(5, 4)) let points = HKHexagonGrid.generateRectangularMap(params, convert: { (p) -> HKHexagonCoordinate3D in return hexConvertEvenRToCube(p) }) self.itemsGrid = HKHexagonGrid(points: points, hexSize: HEX_SIZE, orientation: .Pointy, map: .Rectangle) // Items ordered by distance from central hex (cell) self.items = self.itemsGrid.hexesBySpirals() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() self.collectionView.scrollToItemAtIndexPath(NSIndexPath(forItem: 0, inSection: 0), atScrollPosition: .CenteredVertically | .CenteredHorizontally, animated: false) } override func prefersStatusBarHidden() -> Bool { return true } } extension ViewController: UICollectionViewDataSource { func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int { return 1 } func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return self.items.count } func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { if CELL_IS_CIRCLE { let cell = collectionView.dequeueReusableCellWithReuseIdentifier("CollectionViewCell", forIndexPath: indexPath) as CollectionViewCellCircle let hexObj = items[indexPath.item] cell.hexagon = hexObj cell.labelText = CELL_DRAW_TEXT ? hexObj.hashID : "" return cell } else { let cell = collectionView.dequeueReusableCellWithReuseIdentifier("CollectionViewCell", forIndexPath: indexPath) as CollectionViewCellHexagon let hexObj = items[indexPath.item] cell.hexagon = hexObj cell.labelText = CELL_DRAW_TEXT ? hexObj.hashID : "" cell.borderWidth = 3.0 cell.borderGapOuter = 5.0 cell.borderColor = UIColor.brownColor() return cell } } } extension ViewController: UICollectionViewDelegate { }
mit
18af1e95689c4c72e7d5071c9d575694
31.633929
170
0.65554
5.327988
false
false
false
false
genedelisa/Swift2MIDI
Swift2MIDI/MIDIManager.swift
1
33522
// // MIDIManager.swift // Swift2MIDI // // Created by Gene De Lisa on 6/9/15. // Copyright © 2015 Gene De Lisa. All rights reserved. // import Foundation import CoreMIDI import CoreAudio import AudioToolbox /// The `Singleton` instance private let MIDIManagerInstance = MIDIManager() // this works. func myGlobalProc (notification:UnsafePointer<MIDINotification>, refcon:UnsafeMutablePointer<Void>) { } /** # MIDIManager > Here is an initial cut at using the new Swift 2.0 MIDI frobs. */ class MIDIManager : NSObject { class var sharedInstance:MIDIManager { return MIDIManagerInstance } var midiClient = MIDIClientRef() var outputPort = MIDIPortRef() var inputPort = MIDIPortRef() var destEndpointRef = MIDIEndpointRef() var midiInputPortref = MIDIPortRef() var musicPlayer:MusicPlayer? var processingGraph = AUGraph() var samplerUnit = AudioUnit() // @convention(c) func myNotifyProc (notification:UnsafePointer<MIDINotification>, refcon:UnsafeMutablePointer<Void>) { } // typealias MIDIReadProc = (UnsafePointer<MIDIPacketList>, UnsafeMutablePointer<Void>, UnsafeMutablePointer<Void>) -> Void /** This will initialize the midiClient, outputPort, and inputPort variables. */ func initWithFunc() { var status = OSStatus(noErr) // or with the "original" factory function let np:MIDINotifyProc = { (notification:UnsafePointer<MIDINotification>, refcon:UnsafeMutablePointer<Void>) in } status = MIDIClientCreate("MyMIDIClient", np, nil, &midiClient) // nope: // let np2: @convention(c) (notification:UnsafePointer<MIDINotification>, refcon:UnsafeMutablePointer<Void>) = myproc // let np2: @convention(c) (MIDINotifyProc) = myproc // let np2:MIDINotifyProc @convention(c) {} // let np2:MIDINotifyProc = @convention(c) myproc // let np2 :@convention(c) MIDINotifyProc = myproc status = MIDIClientCreate("MyMIDIClient", myGlobalProc, nil, &midiClient) // status = MIDIClientCreate("MyMIDIClient", myNotifyProc, nil, &midiClient) // status = MIDIClientCreate("MyMIDIClient", np2, nil, &midiClient) // func MIDIClientCreate(name: CFString, _ notifyProc: MIDINotifyProc?, _ notifyRefCon: UnsafeMutablePointer<Void>, _ outClient: UnsafeMutablePointer<MIDIClientRef>) -> OSStatus // let swiftCallback : @convention(c) (CGFloat, CGFloat) -> CGFloat = { // (x, y) -> CGFloat in // return x + y // } } //TODO: does this work? func createThru(source:MIDIEndpointRef?, dest:MIDIEndpointRef?) { var status = OSStatus(noErr) var thru = MIDIThruConnectionRef() var params = MIDIThruConnectionParams() MIDIThruConnectionParamsInitialize(&params) if let s = source { params.sources.0.endpointRef = s // it's a tuple params.numSources = 1 } if let d = dest { params.destinations.0.endpointRef = d params.numDestinations = 1 } params.lowNote = 65 let size = MIDIThruConnectionParamsSize(&params) let nsdata = withUnsafePointer(&params) { p in NSData(bytes: p, length: MIDIThruConnectionParamsSize(&params)) } let pointer = UnsafeMutablePointer<MIDIThruConnectionParams>.alloc(size) // let pointer = UnsafeMutablePointer<MIDIThruConnectionParams>.alloc(sizeof(MIDIThruConnectionParams.Type)) nsdata.getBytes(pointer, length:MIDIThruConnectionParamsSize(&params)) let data = CFDataCreate(kCFAllocatorDefault, UnsafePointer<UInt8>(pointer), size) status = MIDIThruConnectionCreate("MyMIDIThru", data, &thru) if status == noErr { print("created thru \(thru)") } else { print("error creating thru \(status)") } // func MIDIThruConnectionCreate(inPersistentOwnerID: CFString?, _ inConnectionParams: CFData, _ outConnection: UnsafeMutablePointer<MIDIThruConnectionRef>) -> OSStatus } func createThru2(source:MIDIEndpointRef?, dest:MIDIEndpointRef?) { var status = OSStatus(noErr) var thru = MIDIThruConnectionRef() var params = MIDIThruConnectionParams() MIDIThruConnectionParamsInitialize(&params) if let s = source { params.sources.0.endpointRef = s // it's a tuple params.numSources = 1 } if let d = dest { params.destinations.0.endpointRef = d params.numDestinations = 1 } params.lowNote = 65 let nsdata = withUnsafePointer(&params) { p in NSData(bytes: p, length: MIDIThruConnectionParamsSize(&params)) } // toll free bridge from CFData to NSData status = MIDIThruConnectionCreate("MyMIDIThru", nsdata, &thru) if status == noErr { print("created thru \(thru)") } else { print("error creating thru \(status)") } } /* func meta() { //func MusicTrackNewMetaEvent(inTrack: MusicTrack, _ inTimeStamp: MusicTimeStamp, _ inMetaEvent: UnsafePointer<MIDIMetaEvent>) -> OSStatus let track = MusicTrack() let name = "Track name" var byteArray = [UInt8]() // var byteArray = (UInt8)() for char in name.utf8{ byteArray += [char] } let data = name.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)! // let bytes:(UInt8) = data.bytes.memory let meta = MIDIMetaEvent(UInt8(0x03), unused1:UInt8(0), unused2:UInt8(0), unused3:UInt8(0), dataLength:UInt32(name.characters.count), data:byteArray) // data:data.bytes.memory) MusicTrackNewMetaEvent(track, MusicTimeStamp(0), &meta) } */ /* struct MIDIMetaEvent { var metaEventType: UInt8 var unused1: UInt8 var unused2: UInt8 var unused3: UInt8 var dataLength: UInt32 var data: (UInt8) init() init(metaEventType: UInt8, unused1: UInt8, unused2: UInt8, unused3: UInt8, dataLength: UInt32, data: (UInt8)) } */ func initMIDI(midiNotifier: MIDINotifyBlock? = nil, reader: MIDIReadBlock? = nil) { enableNetwork() var notifyBlock: MIDINotifyBlock if midiNotifier != nil { notifyBlock = midiNotifier! } else { notifyBlock = MyMIDINotifyBlock } var readBlock: MIDIReadBlock if reader != nil { readBlock = reader! } else { readBlock = MyMIDIReadBlock } var status = OSStatus(noErr) status = MIDIClientCreateWithBlock("com.rockhoppertech.MyMIDIClient", &midiClient, notifyBlock) // or with the "original" factory function // let np:MIDINotifyProc = { (notification:UnsafePointer<MIDINotification>, refcon:UnsafeMutablePointer<Void>) in // } // status = MIDIClientCreate("MyMIDIClient", np, nil, &midiClient) // nope: //let np2 = myproc //status = MIDIClientCreate("MyMIDIClient", np2, nil, &midiClient) if status == OSStatus(noErr) { print("created client") } else { print("error creating client : \(status)") showError(status) } if status == OSStatus(noErr) { status = MIDIInputPortCreateWithBlock(midiClient, "com.rockhoppertech.InputPort", &inputPort, readBlock) if status == OSStatus(noErr) { print("created input port") } else { print("error creating input port : \(status)") showError(status) } status = MIDIOutputPortCreate(midiClient, "com.rockhoppertech.OutputPort", &outputPort) if status == OSStatus(noErr) { print("created output port \(outputPort)") } else { print("error creating output port : \(status)") showError(status) } createThru(inputPort, dest: outputPort) status = MIDIDestinationCreateWithBlock(midiClient, "com.rockhoppertech.VirtualDest", &destEndpointRef, readBlock) // or if you want to use a closure // status = MIDIDestinationCreateWithBlock(midiClient, // "Virtual Dest", // &destEndpointRef, // { (packetList:UnsafePointer<MIDIPacketList>, src:UnsafeMutablePointer<Void>) -> Void in // // let packets = packetList.memory // let packet:MIDIPacket = packets.packet.0 // // // do the loop here... // // self.handle(packet) // // }) if status != noErr { print("error creating virtual destination: \(status)") } else { print("midi virtual destination created \(destEndpointRef)") } connectSourcesToInputPort() initGraph() } } // typealias MIDINotifyProc = (UnsafePointer<MIDINotification>, UnsafeMutablePointer<Void>) -> Void // @convention(c) // func myproc (notification:UnsafePointer<MIDINotification>, refcon:UnsafeMutablePointer<Void>) { // // } func initGraph() { augraphSetup() graphStart() // after the graph starts loadSF2Preset(0) CAShow(UnsafeMutablePointer<MusicSequence>(self.processingGraph)) } // typealias MIDIReadBlock = (UnsafePointer<MIDIPacketList>, UnsafeMutablePointer<Void>) -> Void func MyMIDIReadBlock(packetList: UnsafePointer<MIDIPacketList>, srcConnRefCon: UnsafeMutablePointer<Void>) -> Void { //debugPrint("MyMIDIReadBlock \(packetList)") let packets = packetList.memory let packet:MIDIPacket = packets.packet // don't do this // print("packet \(packet)") var ap = UnsafeMutablePointer<MIDIPacket>.alloc(1) ap.initialize(packet) for _ in 0 ..< packets.numPackets { let p = ap.memory print("timestamp \(p.timeStamp)", terminator: "") var hex = String(format:"0x%X", p.data.0) print(" \(hex)", terminator: "") hex = String(format:"0x%X", p.data.1) print(" \(hex)", terminator: "") hex = String(format:"0x%X", p.data.2) print(" \(hex)") handle(p) ap = MIDIPacketNext(ap) } } func handle(packet:MIDIPacket) { let status = packet.data.0 let d1 = packet.data.1 let d2 = packet.data.2 let rawStatus = status & 0xF0 // without channel let channel = status & 0x0F switch rawStatus { case 0x80: print("Note off. Channel \(channel) note \(d1) velocity \(d2)") // forward to sampler playNoteOff(UInt32(channel), noteNum: UInt32(d1)) case 0x90: print("Note on. Channel \(channel) note \(d1) velocity \(d2)") // forward to sampler playNoteOn(UInt32(channel), noteNum:UInt32(d1), velocity: UInt32(d2)) case 0xA0: print("Polyphonic Key Pressure (Aftertouch). Channel \(channel) note \(d1) pressure \(d2)") case 0xB0: print("Control Change. Channel \(channel) controller \(d1) value \(d2)") case 0xC0: print("Program Change. Channel \(channel) program \(d1)") case 0xD0: print("Channel Pressure (Aftertouch). Channel \(channel) pressure \(d1)") case 0xE0: print("Pitch Bend Change. Channel \(channel) lsb \(d1) msb \(d2)") default: print("Unhandled message \(status)") } } //typealias MIDINotifyBlock = (UnsafePointer<MIDINotification>) -> Void func MyMIDINotifyBlock(midiNotification: UnsafePointer<MIDINotification>) { print("got a MIDINotification!") let notification = midiNotification.memory print("MIDI Notify, messageId= \(notification.messageID)") print("MIDI Notify, messageSize= \(notification.messageSize)") // values are now an enum! switch (notification.messageID) { case .MsgSetupChanged: print("MIDI setup changed") break //TODO: so how to "downcast" to MIDIObjectAddRemoveNotification case .MsgObjectAdded: print("added") var mem = midiNotification.memory withUnsafePointer(&mem) { ptr -> Void in let mp = unsafeBitCast(ptr, UnsafePointer<MIDIObjectAddRemoveNotification>.self) let m = mp.memory print("id \(m.messageID)") print("size \(m.messageSize)") print("child \(m.child)") print("child type \(m.childType)") print("parent \(m.parent)") print("parentType \(m.parentType)") } break case .MsgObjectRemoved: print("kMIDIMsgObjectRemoved") break case .MsgPropertyChanged: print("kMIDIMsgPropertyChanged") var mem = midiNotification.memory withUnsafePointer(&mem) { ptr -> Void in let mp = unsafeBitCast(ptr, UnsafePointer<MIDIObjectPropertyChangeNotification>.self) let m = mp.memory print("id \(m.messageID)") print("size \(m.messageSize)") print("object \(m.object)") print("objectType \(m.objectType)") if m.propertyName.takeUnretainedValue() == kMIDIPropertyOffline { var value = Int32(0) let status = MIDIObjectGetIntegerProperty(m.object, kMIDIPropertyOffline, &value) if status != noErr { print("oops") } print("The offline property is \(value)") } } break case .MsgThruConnectionsChanged: print("MIDI thru connections changed.") break case .MsgSerialPortOwnerChanged: print("MIDI serial port owner changed.") break case .MsgIOError: print("MIDI I/O error.") //MIDIIOErrorNotification break } } func showError(status:OSStatus) { switch status { case OSStatus(kMIDIInvalidClient): print("invalid client") break case OSStatus(kMIDIInvalidPort): print("invalid port") break case OSStatus(kMIDIWrongEndpointType): print("invalid endpoint type") break case OSStatus(kMIDINoConnection): print("no connection") break case OSStatus(kMIDIUnknownEndpoint): print("unknown endpoint") break case OSStatus(kMIDIUnknownProperty): print("unknown property") break case OSStatus(kMIDIWrongPropertyType): print("wrong property type") break case OSStatus(kMIDINoCurrentSetup): print("no current setup") break case OSStatus(kMIDIMessageSendErr): print("message send") break case OSStatus(kMIDIServerStartErr): print("server start") break case OSStatus(kMIDISetupFormatErr): print("setup format") break case OSStatus(kMIDIWrongThread): print("wrong thread") break case OSStatus(kMIDIObjectNotFound): print("object not found") break case OSStatus(kMIDIIDNotUnique): print("not unique") break case OSStatus(kMIDINotPermitted): print("not permitted") break default: print("dunno \(status)") } } func enableNetwork() { let session = MIDINetworkSession.defaultSession() session.enabled = true session.connectionPolicy = .Anyone print("net session enabled \(MIDINetworkSession.defaultSession().enabled)") } func connectSourcesToInputPort() { var status = OSStatus(noErr) let sourceCount = MIDIGetNumberOfSources() print("source count \(sourceCount)") for srcIndex in 0 ..< sourceCount { let midiEndPoint = MIDIGetSource(srcIndex) status = MIDIPortConnectSource(inputPort, midiEndPoint, nil) if status == OSStatus(noErr) { print("yay connected endpoint to inputPort!") } else { print("oh crap!") } } } // Testing virtual destination func playWithMusicPlayer() { let sequence = createMusicSequence() self.musicPlayer = createMusicPlayer(sequence) playMusicPlayer() } func createMusicPlayer(musicSequence:MusicSequence) -> MusicPlayer { var musicPlayer = MusicPlayer() var status = OSStatus(noErr) status = NewMusicPlayer(&musicPlayer) if status != OSStatus(noErr) { print("bad status \(status) creating player") } status = MusicPlayerSetSequence(musicPlayer, musicSequence) if status != OSStatus(noErr) { print("setting sequence \(status)") } status = MusicPlayerPreroll(musicPlayer) if status != OSStatus(noErr) { print("prerolling player \(status)") } status = MusicSequenceSetMIDIEndpoint(musicSequence, self.destEndpointRef) if status != OSStatus(noErr) { print("error setting sequence endpoint \(status)") } return musicPlayer } func playMusicPlayer() { var status = OSStatus(noErr) var playing = DarwinBoolean(false) if let player = self.musicPlayer { status = MusicPlayerIsPlaying(player, &playing) if playing != false { print("music player is playing. stopping") status = MusicPlayerStop(player) if status != OSStatus(noErr) { print("Error stopping \(status)") return } } else { print("music player is not playing.") } status = MusicPlayerSetTime(player, 0) if status != OSStatus(noErr) { print("setting time \(status)") return } status = MusicPlayerStart(player) if status != OSStatus(noErr) { print("Error starting \(status)") return } } } func createMusicSequence() -> MusicSequence { var musicSequence = MusicSequence() var status = NewMusicSequence(&musicSequence) if status != OSStatus(noErr) { print("\(__LINE__) bad status \(status) creating sequence") } // just for fun, add a tempo track. var tempoTrack = MusicTrack() if MusicSequenceGetTempoTrack(musicSequence, &tempoTrack) != noErr { assert(tempoTrack != nil, "Cannot get tempo track") } //MusicTrackClear(tempoTrack, 0, 1) if MusicTrackNewExtendedTempoEvent(tempoTrack, 0.0, 128.0) != noErr { print("could not set tempo") } if MusicTrackNewExtendedTempoEvent(tempoTrack, 4.0, 256.0) != noErr { print("could not set tempo") } // add a track var track = MusicTrack() status = MusicSequenceNewTrack(musicSequence, &track) if status != OSStatus(noErr) { print("error creating track \(status)") } // bank select msb var chanmess = MIDIChannelMessage(status: 0xB0, data1: 0, data2: 0, reserved: 0) status = MusicTrackNewMIDIChannelEvent(track, 0, &chanmess) if status != OSStatus(noErr) { print("creating bank select event \(status)") } // bank select lsb chanmess = MIDIChannelMessage(status: 0xB0, data1: 32, data2: 0, reserved: 0) status = MusicTrackNewMIDIChannelEvent(track, 0, &chanmess) if status != OSStatus(noErr) { print("creating bank select event \(status)") } // program change. first data byte is the patch, the second data byte is unused for program change messages. chanmess = MIDIChannelMessage(status: 0xC0, data1: 0, data2: 0, reserved: 0) status = MusicTrackNewMIDIChannelEvent(track, 0, &chanmess) if status != OSStatus(noErr) { print("creating program change event \(status)") } // now make some notes and put them on the track var beat = MusicTimeStamp(0.0) for i:UInt8 in 60...72 { var mess = MIDINoteMessage(channel: 0, note: i, velocity: 64, releaseVelocity: 0, duration: 1.0 ) status = MusicTrackNewMIDINoteEvent(track, beat, &mess) if status != OSStatus(noErr) { print("creating new midi note event \(status)") } beat++ } // associate the AUGraph with the sequence. MusicSequenceSetAUGraph(musicSequence, self.processingGraph) // Let's see it CAShow(UnsafeMutablePointer<MusicSequence>(musicSequence)) return musicSequence } func augraphSetup() { var status = OSStatus(noErr) status = NewAUGraph(&self.processingGraph) CheckError(status) // create the sampler //https://developer.apple.com/library/prerelease/ios/documentation/AudioUnit/Reference/AudioComponentServicesReference/index.html#//apple_ref/swift/struct/AudioComponentDescription var samplerNode = AUNode() var cd = AudioComponentDescription( componentType: OSType(kAudioUnitType_MusicDevice), componentSubType: OSType(kAudioUnitSubType_Sampler), componentManufacturer: OSType(kAudioUnitManufacturer_Apple), componentFlags: 0, componentFlagsMask: 0) status = AUGraphAddNode(self.processingGraph, &cd, &samplerNode) CheckError(status) // create the ionode var ioNode = AUNode() var ioUnitDescription = AudioComponentDescription( componentType: OSType(kAudioUnitType_Output), componentSubType: OSType(kAudioUnitSubType_RemoteIO), componentManufacturer: OSType(kAudioUnitManufacturer_Apple), componentFlags: 0, componentFlagsMask: 0) status = AUGraphAddNode(self.processingGraph, &ioUnitDescription, &ioNode) CheckError(status) // now do the wiring. The graph needs to be open before you call AUGraphNodeInfo status = AUGraphOpen(self.processingGraph) CheckError(status) status = AUGraphNodeInfo(self.processingGraph, samplerNode, nil, &self.samplerUnit) CheckError(status) var ioUnit = AudioUnit() status = AUGraphNodeInfo(self.processingGraph, ioNode, nil, &ioUnit) CheckError(status) let ioUnitOutputElement = AudioUnitElement(0) let samplerOutputElement = AudioUnitElement(0) status = AUGraphConnectNodeInput(self.processingGraph, samplerNode, samplerOutputElement, // srcnode, inSourceOutputNumber ioNode, ioUnitOutputElement) // destnode, inDestInputNumber CheckError(status) } func graphStart() { //https://developer.apple.com/library/prerelease/ios/documentation/AudioToolbox/Reference/AUGraphServicesReference/index.html#//apple_ref/c/func/AUGraphIsInitialized var status = OSStatus(noErr) var outIsInitialized:DarwinBoolean = false status = AUGraphIsInitialized(self.processingGraph, &outIsInitialized) print("isinit status is \(status)") print("bool is \(outIsInitialized)") if outIsInitialized == false { status = AUGraphInitialize(self.processingGraph) CheckError(status) } var isRunning = DarwinBoolean(false) AUGraphIsRunning(self.processingGraph, &isRunning) print("running bool is \(isRunning)") if isRunning == false { status = AUGraphStart(self.processingGraph) CheckError(status) } } func playNoteOn(channel:UInt32, noteNum:UInt32, velocity:UInt32) { let noteCommand = UInt32(0x90 | channel) var status = OSStatus(noErr) status = MusicDeviceMIDIEvent(self.samplerUnit, noteCommand, noteNum, velocity, 0) CheckError(status) } func playNoteOff(channel:UInt32, noteNum:UInt32) { let noteCommand = UInt32(0x80 | channel) var status : OSStatus = OSStatus(noErr) status = MusicDeviceMIDIEvent(self.samplerUnit, noteCommand, noteNum, 0, 0) CheckError(status) } /// loads preset into self.samplerUnit func loadSF2Preset(preset:UInt8) { // This is the MuseCore soundfont. Change it to the one you have. if let bankURL = NSBundle.mainBundle().URLForResource("GeneralUser GS MuseScore v1.442", withExtension: "sf2") { var instdata = AUSamplerInstrumentData(fileURL: Unmanaged.passUnretained(bankURL), instrumentType: UInt8(kInstrumentType_DLSPreset), bankMSB: UInt8(kAUSampler_DefaultMelodicBankMSB), bankLSB: UInt8(kAUSampler_DefaultBankLSB), presetID: preset) let status = AudioUnitSetProperty( self.samplerUnit, AudioUnitPropertyID(kAUSamplerProperty_LoadInstrument), AudioUnitScope(kAudioUnitScope_Global), 0, &instdata, UInt32(sizeof(AUSamplerInstrumentData))) CheckError(status) } } /** Not as detailed as Adamson's CheckError, but adequate. For other projects you can uncomment the Core MIDI constants. */ func CheckError(error:OSStatus) { if error == 0 {return} switch(error) { case kMIDIInvalidClient : print( "kMIDIInvalidClient ") case kMIDIInvalidPort : print( "kMIDIInvalidPort ") case kMIDIWrongEndpointType : print( "kMIDIWrongEndpointType") case kMIDINoConnection : print( "kMIDINoConnection ") case kMIDIUnknownEndpoint : print( "kMIDIUnknownEndpoint ") case kMIDIUnknownProperty : print( "kMIDIUnknownProperty ") case kMIDIWrongPropertyType : print( "kMIDIWrongPropertyType ") case kMIDINoCurrentSetup : print( "kMIDINoCurrentSetup ") case kMIDIMessageSendErr : print( "kMIDIMessageSendErr ") case kMIDIServerStartErr : print( "kMIDIServerStartErr ") case kMIDISetupFormatErr : print( "kMIDISetupFormatErr ") case kMIDIWrongThread : print( "kMIDIWrongThread ") case kMIDIObjectNotFound : print( "kMIDIObjectNotFound ") case kMIDIIDNotUnique : print( "kMIDIIDNotUnique ") default: print( "huh? \(error) ") } switch(error) { //AUGraph.h case kAUGraphErr_NodeNotFound: print("Error:kAUGraphErr_NodeNotFound \n") case kAUGraphErr_OutputNodeErr: print( "Error:kAUGraphErr_OutputNodeErr \n") case kAUGraphErr_InvalidConnection: print("Error:kAUGraphErr_InvalidConnection \n") case kAUGraphErr_CannotDoInCurrentContext: print( "Error:kAUGraphErr_CannotDoInCurrentContext \n") case kAUGraphErr_InvalidAudioUnit: print( "Error:kAUGraphErr_InvalidAudioUnit \n") // core audio case kAudio_UnimplementedError: print("kAudio_UnimplementedError") case kAudio_FileNotFoundError: print("kAudio_FileNotFoundError") case kAudio_FilePermissionError: print("kAudio_FilePermissionError") case kAudio_TooManyFilesOpenError: print("kAudio_TooManyFilesOpenError") case kAudio_BadFilePathError: print("kAudio_BadFilePathError") case kAudio_ParamError: print("kAudio_ParamError") case kAudio_MemFullError: print("kAudio_MemFullError") // AudioToolbox case kAudioToolboxErr_InvalidSequenceType : print( " kAudioToolboxErr_InvalidSequenceType ") case kAudioToolboxErr_TrackIndexError : print( " kAudioToolboxErr_TrackIndexError ") case kAudioToolboxErr_TrackNotFound : print( " kAudioToolboxErr_TrackNotFound ") case kAudioToolboxErr_EndOfTrack : print( " kAudioToolboxErr_EndOfTrack ") case kAudioToolboxErr_StartOfTrack : print( " kAudioToolboxErr_StartOfTrack ") case kAudioToolboxErr_IllegalTrackDestination : print( " kAudioToolboxErr_IllegalTrackDestination") case kAudioToolboxErr_NoSequence : print( " kAudioToolboxErr_NoSequence ") case kAudioToolboxErr_InvalidEventType : print( " kAudioToolboxErr_InvalidEventType") case kAudioToolboxErr_InvalidPlayerState : print( " kAudioToolboxErr_InvalidPlayerState") // AudioUnit case kAudioUnitErr_InvalidProperty : print( " kAudioUnitErr_InvalidProperty") case kAudioUnitErr_InvalidParameter : print( " kAudioUnitErr_InvalidParameter") case kAudioUnitErr_InvalidElement : print( " kAudioUnitErr_InvalidElement") case kAudioUnitErr_NoConnection : print( " kAudioUnitErr_NoConnection") case kAudioUnitErr_FailedInitialization : print( " kAudioUnitErr_FailedInitialization") case kAudioUnitErr_TooManyFramesToProcess : print( " kAudioUnitErr_TooManyFramesToProcess") case kAudioUnitErr_InvalidFile : print( " kAudioUnitErr_InvalidFile") case kAudioUnitErr_FormatNotSupported : print( " kAudioUnitErr_FormatNotSupported") case kAudioUnitErr_Uninitialized : print( " kAudioUnitErr_Uninitialized") case kAudioUnitErr_InvalidScope : print( " kAudioUnitErr_InvalidScope") case kAudioUnitErr_PropertyNotWritable : print( " kAudioUnitErr_PropertyNotWritable") case kAudioUnitErr_InvalidPropertyValue : print( " kAudioUnitErr_InvalidPropertyValue") case kAudioUnitErr_PropertyNotInUse : print( " kAudioUnitErr_PropertyNotInUse") case kAudioUnitErr_Initialized : print( " kAudioUnitErr_Initialized") case kAudioUnitErr_InvalidOfflineRender : print( " kAudioUnitErr_InvalidOfflineRender") case kAudioUnitErr_Unauthorized : print( " kAudioUnitErr_Unauthorized") default: print("huh?") } } }
mit
e51f3e056a1ee2be37370eb1d4727028
32.222002
188
0.564303
4.920153
false
false
false
false