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
cismet/belis-app
belis-app/GenericFormViewController.swift
1
3217
// // GenericFormViewController.swift // belis-app // // Created by Thorsten Hell on 18.11.15. // Copyright © 2015 cismet. All rights reserved. // import Foundation import SwiftForms class GenericFormViewController: FormViewController, Refreshable { var saveHandler : (()->())? var cancelHandler : (()->())? var preSaveCheck: ()->CheckResult={ return CheckResult(passed: true) } var preCancelCheck: ()->CheckResult={ return CheckResult(passed: true) } required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override func viewDidLoad() { super.viewDidLoad() self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Speichern", style: .plain, target: self, action: #selector(GenericFormViewController.save)) let image=GlyphTools.sharedInstance().getGlyphedImage("icon-chevron-left", fontsize: 11, size: CGSize(width: 14, height: 14)) self.navigationItem.leftBarButtonItem = UIBarButtonItem(image: image, style: UIBarButtonItemStyle.plain , target: self, action: #selector(GenericFormViewController.cancel)) } func save() { let check=preSaveCheck() if (check.passed) { self.dismiss(animated: true) { () -> Void in if let sh=self.saveHandler { sh() } else { //should not happen >> log it } } } else { let alert = UIAlertController(title: check.title, message: check.message, preferredStyle: UIAlertControllerStyle.alert) alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.default, handler:{ (ACTION :UIAlertAction)in })) present(alert, animated: true, completion: nil) } } func cancel() { // self.dismiss(animated: true) { () -> Void in // if let ch=self.cancelHandler { // ch() // } // else { // //should not happen >> log it // } // } let check=preCancelCheck() if (check.passed) { self.dismiss(animated: true) { () -> Void in if let sh=self.cancelHandler { sh() } else { //should not happen >> log it } } } else { let alert = UIAlertController(title: check.title, message: check.message, preferredStyle: UIAlertControllerStyle.alert) alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.default, handler:{ (ACTION :UIAlertAction)in })) present(alert, animated: true, completion: nil) } } func refresh() { super.tableView.reloadData() navigationController?.isModalInPopover=true } } class CheckResult { var passed: Bool var message: String var title: String init(passed: Bool, title:String="", withMessage:String = ""){ self.passed=passed self.title=title self.message=withMessage } }
mit
ed2e1cbecaebe9820c2313e6ee939d29
29.056075
184
0.562811
4.722467
false
false
false
false
benlangmuir/swift
test/Reflection/conformance_descriptors_of_external_types.swift
3
1266
// REQUIRES: objc_interop, OS=macosx // Temporarily disable on arm64e (rdar://88579818) // UNSUPPORTED: CPU=arm64e // RUN: %empty-directory(%t) // RUN: %empty-directory(%t/includes) // Build external Swift library/module // RUN: %target-build-swift %S/Inputs/swiftmodules/testModB.swift -parse-as-library -emit-module -emit-library -module-name testModB -o %t/includes/testModB.o // Build external Clang library // RUN: %target-clang %S/Inputs/cmodules/testModA.m -c -o %t/testModA.o // Build the test into a binary // RUN: %target-build-swift %s -parse-as-library -emit-module -emit-library -module-name ExternalConformanceCheck -I %t/includes -I %S/Inputs/cmodules -o %t/ExternalConformances %t/testModA.o %t/includes/testModB.o // RUN: %target-swift-reflection-dump -binary-filename %t/ExternalConformances -binary-filename %platform-module-dir/%target-library-name(swiftCore) | %FileCheck %s import testModA import testModB protocol myTestProto {} extension testModBStruct : myTestProto {} extension testModAClass : myTestProto {} // CHECK: CONFORMANCES: // CHECK: ============= // CHECK-DAG: (__C.testModAClass) : ExternalConformanceCheck.myTestProto // CHECK-DAG: 8testModB0aB7BStructV (testModB.testModBStruct) : ExternalConformanceCheck.myTestProto
apache-2.0
fd4c03582c2394771d210498d1502a74
42.655172
214
0.754344
3.172932
false
true
false
false
alexzatsepin/omim
iphone/Maps/Classes/CustomViews/NavigationDashboard/Views/NavigationControlView.swift
3
9941
@objc(MWMNavigationControlView) final class NavigationControlView: SolidTouchView, MWMTextToSpeechObserver, MWMTrafficManagerObserver { @IBOutlet private weak var distanceLabel: UILabel! @IBOutlet private weak var distanceLegendLabel: UILabel! @IBOutlet private weak var distanceWithLegendLabel: UILabel! @IBOutlet private weak var progressView: UIView! @IBOutlet private weak var routingProgress: NSLayoutConstraint! @IBOutlet private weak var speedLabel: UILabel! @IBOutlet private weak var speedBackground: UIView! @IBOutlet private weak var speedLegendLabel: UILabel! @IBOutlet private weak var speedWithLegendLabel: UILabel! @IBOutlet private weak var timeLabel: UILabel! @IBOutlet private weak var timePageControl: UIPageControl! @IBOutlet private weak var extendButton: UIButton! { didSet { setExtendButtonImage() } } @IBOutlet private weak var ttsButton: UIButton! { didSet { ttsButton.setImage(#imageLiteral(resourceName: "ic_voice_off"), for: .normal) ttsButton.setImage(#imageLiteral(resourceName: "ic_voice_on"), for: .selected) ttsButton.setImage(#imageLiteral(resourceName: "ic_voice_on"), for: [.selected, .highlighted]) onTTSStatusUpdated() } } @IBOutlet private weak var trafficButton: UIButton! { didSet { trafficButton.setImage(#imageLiteral(resourceName: "ic_setting_traffic_off"), for: .normal) trafficButton.setImage(#imageLiteral(resourceName: "ic_setting_traffic_on"), for: .selected) trafficButton.setImage(#imageLiteral(resourceName: "ic_setting_traffic_on"), for: [.selected, .highlighted]) onTrafficStateUpdated() } } private lazy var dimBackground: DimBackground = { DimBackground(mainView: self, tapAction: { [weak self] in self?.diminish() }) }() @objc weak var ownerView: UIView! @IBOutlet private weak var extendedView: UIView! private weak var navigationInfo: MWMNavigationDashboardEntity? private var hiddenConstraint: NSLayoutConstraint! private var extendedConstraint: NSLayoutConstraint! @objc var isVisible = false { didSet { guard isVisible != oldValue else { return } if isVisible { addView() } else { removeView() } alpha = isVisible ? 0 : 1 DispatchQueue.main.async { self.superview?.animateConstraints { self.alpha = self.isVisible ? 1 : 0 self.hiddenConstraint.isActive = !self.isVisible } } } } private var isExtended = false { willSet { guard isExtended != newValue else { return } morphExtendButton() } didSet { guard isVisible && superview != nil else { return } guard isExtended != oldValue else { return } dimBackground.setVisible(isExtended, completion: nil) extendedView.isHidden = !isExtended superview!.animateConstraints(animations: { self.extendedConstraint.isActive = self.isExtended }) } } private func addView() { guard superview != ownerView else { return } ownerView.addSubview(self) var lAnchor = ownerView.leadingAnchor var tAnchor = ownerView.trailingAnchor var bAnchor = ownerView.bottomAnchor if #available(iOS 11.0, *) { let layoutGuide = ownerView.safeAreaLayoutGuide lAnchor = layoutGuide.leadingAnchor tAnchor = layoutGuide.trailingAnchor bAnchor = layoutGuide.bottomAnchor } leadingAnchor.constraint(equalTo: lAnchor).isActive = true trailingAnchor.constraint(equalTo: tAnchor).isActive = true hiddenConstraint = topAnchor.constraint(equalTo: ownerView.bottomAnchor) hiddenConstraint.isActive = true let visibleConstraint = progressView.bottomAnchor.constraint(equalTo: bAnchor) visibleConstraint.priority = UILayoutPriority.defaultLow visibleConstraint.isActive = true extendedConstraint = bottomAnchor.constraint(equalTo: bAnchor) extendedConstraint.priority = UILayoutPriority(rawValue: UILayoutPriority.RawValue(Int(UILayoutPriority.defaultHigh.rawValue) - 1)) ownerView.layoutIfNeeded() } private func removeView() { dimBackground.setVisible(false, completion: { self.removeFromSuperview() }) } override func mwm_refreshUI() { if isVisible { super.mwm_refreshUI() } } override func awakeFromNib() { super.awakeFromNib() translatesAutoresizingMaskIntoConstraints = false MWMTextToSpeech.add(self) MWMTrafficManager.add(self) } override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) { super.traitCollectionDidChange(previousTraitCollection) let isCompact = traitCollection.verticalSizeClass == .compact distanceLabel.isHidden = isCompact distanceLegendLabel.isHidden = isCompact distanceWithLegendLabel.isHidden = !isCompact speedLabel.isHidden = isCompact speedLegendLabel.isHidden = isCompact speedWithLegendLabel.isHidden = !isCompact let pgScale: CGFloat = isCompact ? 0.7 : 1 timePageControl.transform = CGAffineTransform(scaleX: pgScale, y: pgScale) } @objc func onNavigationInfoUpdated(_ info: MWMNavigationDashboardEntity) { navigationInfo = info guard !MWMRouter.isTaxi() else { return } let routingNumberAttributes: [NSAttributedStringKey: Any] = [ NSAttributedStringKey.foregroundColor: UIColor.blackPrimaryText(), NSAttributedStringKey.font: UIFont.bold24(), ] let routingLegendAttributes: [NSAttributedStringKey: Any] = [ NSAttributedStringKey.foregroundColor: UIColor.blackSecondaryText(), NSAttributedStringKey.font: UIFont.bold14(), ] if timePageControl.currentPage == 0 { timeLabel.text = info.eta } else { timeLabel.text = info.arrival } var distanceWithLegend: NSMutableAttributedString? if let targetDistance = info.targetDistance { distanceLabel.text = targetDistance distanceWithLegend = NSMutableAttributedString(string: targetDistance, attributes: routingNumberAttributes) } if let targetUnits = info.targetUnits { distanceLegendLabel.text = targetUnits if let distanceWithLegend = distanceWithLegend { distanceWithLegend.append(NSAttributedString(string: targetUnits, attributes: routingLegendAttributes)) distanceWithLegendLabel.attributedText = distanceWithLegend } } let speed = info.speed ?? "0" speedLabel.text = speed speedLegendLabel.text = info.speedUnits let speedWithLegend = NSMutableAttributedString(string: speed, attributes: routingNumberAttributes) speedWithLegend.append(NSAttributedString(string: info.speedUnits, attributes: routingLegendAttributes)) speedWithLegendLabel.attributedText = speedWithLegend let speedLimitExceeded = info.isSpeedLimitExceeded let textColor = speedLimitExceeded ? UIColor.white() : UIColor.blackPrimaryText() speedBackground.backgroundColor = speedLimitExceeded ? UIColor.buttonRed() : UIColor.clear speedLabel.textColor = textColor speedLegendLabel.textColor = textColor speedWithLegendLabel.textColor = textColor self.routingProgress.constant = self.progressView.width * info.progress / 100 } @IBAction private func toggleInfoAction() { if let navigationInfo = navigationInfo { timePageControl.currentPage = (timePageControl.currentPage + 1) % timePageControl.numberOfPages onNavigationInfoUpdated(navigationInfo) } refreshDiminishTimer() } @IBAction private func extendAction() { isExtended = !isExtended refreshDiminishTimer() } private func morphExtendButton() { guard let imageView = extendButton.imageView else { return } let morphImagesCount = 6 let startValue = isExtended ? morphImagesCount : 1 let endValue = isExtended ? 0 : morphImagesCount + 1 let stepValue = isExtended ? -1 : 1 var morphImages: [UIImage] = [] let nightMode = UIColor.isNightMode() ? "dark" : "light" for i in stride(from: startValue, to: endValue, by: stepValue) { let imageName = "ic_menu_\(i)_\(nightMode)" morphImages.append(UIImage(named: imageName)!) } imageView.animationImages = morphImages imageView.animationRepeatCount = 1 imageView.image = morphImages.last imageView.startAnimating() setExtendButtonImage() } private func setExtendButtonImage() { DispatchQueue.main.async { guard let imageView = self.extendButton.imageView else { return } if imageView.isAnimating { self.setExtendButtonImage() } else { self.extendButton.setImage(self.isExtended ? #imageLiteral(resourceName: "ic_menu_down") : #imageLiteral(resourceName: "ic_menu"), for: .normal) } } } private func refreshDiminishTimer() { let sel = #selector(diminish) NSObject.cancelPreviousPerformRequests(withTarget: self, selector: sel, object: self) perform(sel, with: self, afterDelay: 5) } @objc private func diminish() { isExtended = false } func onTTSStatusUpdated() { guard MWMRouter.isRoutingActive() else { return } let isPedestrianRouting = MWMRouter.type() == .pedestrian ttsButton.isHidden = isPedestrianRouting || !MWMTextToSpeech.isTTSEnabled() if !ttsButton.isHidden { ttsButton.isSelected = MWMTextToSpeech.tts().active } refreshDiminishTimer() } func onTrafficStateUpdated() { guard MWMRouter.isRoutingActive() else { return } let isPedestrianRouting = MWMRouter.type() == .pedestrian trafficButton.isHidden = isPedestrianRouting trafficButton.isSelected = MWMTrafficManager.trafficState() != .disabled refreshDiminishTimer() } override var sideButtonsAreaAffectDirections: MWMAvailableAreaAffectDirections { return .bottom } override var widgetsAreaAffectDirections: MWMAvailableAreaAffectDirections { return alternative(iPhone: .bottom, iPad: []) } }
apache-2.0
916e3bd292bbfadded58628ffe23f81e
34.127208
152
0.723368
4.70246
false
false
false
false
mozilla-mobile/firefox-ios
Providers/Pocket/Model/PocketFeedStory.swift
2
1580
// 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 /* The Pocket class is used to fetch stories from the Pocked API. Right now this only supports the global feed For a sample feed item check ClientTests/pocketglobalfeed.json */ struct PocketFeedStory { let title: String let url: URL let domain: String let timeToRead: Int64 let storyDescription: String let imageURL: URL static func parseJSON(list: [[String: Any]]) -> [PocketFeedStory] { return list.compactMap({ (storyDict) -> PocketFeedStory? in guard let urlS = storyDict["url"] as? String, let domain = storyDict["domain"] as? String, let imageURLS = storyDict["image_src"] as? String, let title = storyDict["title"] as? String, let timeToRead = storyDict["time_to_read"] as? Int64, let description = storyDict["excerpt"] as? String else { return nil } guard let url = URL(string: urlS), let imageURL = URL(string: imageURLS) else { return nil } return PocketFeedStory( title: title, url: url, domain: domain, timeToRead: timeToRead, storyDescription: description, imageURL: imageURL ) }) } }
mpl-2.0
9c1cb75523ae94525e29bcff86864ee6
32.617021
74
0.575949
4.633431
false
false
false
false
finn-no/Finjinon
Tests/FinjinonTests.swift
1
2968
// // Copyright (c) 2017 FINN.no AS. All rights reserved. // import UIKit import XCTest import Finjinon class FinjinonTests: XCTestCase { func testViewRotateToDeviceOrientationExtension() { let view = UIView(frame: CGRect.zero) view.rotateToDeviceOrientation(.portrait) let portraitTransform = view.transform view.rotateToDeviceOrientation(.portraitUpsideDown) let portraitUpsideDownTransform = view.transform view.rotateToDeviceOrientation(.landscapeLeft) let landscapeLeftTransform = view.transform view.rotateToDeviceOrientation(.landscapeRight) let landscapRightTransform = view.transform // portrait vs. portraitUpsideDown XCTAssertEqual(portraitTransform.a, portraitUpsideDownTransform.a) XCTAssertEqual(portraitTransform.b, portraitUpsideDownTransform.b) XCTAssertEqual(portraitTransform.c, portraitUpsideDownTransform.c) // portrait vs. landscape XCTAssertNotEqual(portraitTransform.a, landscapeLeftTransform.a) XCTAssertNotEqual(portraitTransform.b, landscapeLeftTransform.b) XCTAssertNotEqual(portraitTransform.c, landscapeLeftTransform.c) XCTAssertNotEqual(portraitUpsideDownTransform.a, landscapeLeftTransform.a) XCTAssertNotEqual(portraitUpsideDownTransform.b, landscapeLeftTransform.b) XCTAssertNotEqual(portraitUpsideDownTransform.c, landscapeLeftTransform.c) XCTAssertNotEqual(portraitTransform.a, landscapRightTransform.a) XCTAssertNotEqual(portraitTransform.b, landscapRightTransform.b) XCTAssertNotEqual(portraitTransform.c, landscapRightTransform.c) XCTAssertNotEqual(portraitUpsideDownTransform.a, landscapRightTransform.a) XCTAssertNotEqual(portraitUpsideDownTransform.b, landscapRightTransform.b) XCTAssertNotEqual(portraitUpsideDownTransform.c, landscapRightTransform.c) // landscapeLeft vs. landscapeRight XCTAssertEqual(landscapRightTransform.a, landscapeLeftTransform.a) XCTAssertNotEqual(landscapRightTransform.b, landscapeLeftTransform.b) XCTAssertNotEqual(landscapRightTransform.c, landscapeLeftTransform.c) // Test that .FaceUp & .FaceDown does not trigger any changes. view.rotateToDeviceOrientation(.portrait) let unchangeableTransform = view.transform view.rotateToDeviceOrientation(.faceDown) let faceDownTransform = view.transform view.rotateToDeviceOrientation(.faceUp) let faceUpTransform = view.transform XCTAssertEqual(unchangeableTransform.a, faceDownTransform.a) XCTAssertEqual(unchangeableTransform.b, faceDownTransform.b) XCTAssertEqual(unchangeableTransform.c, faceDownTransform.c) XCTAssertEqual(unchangeableTransform.a, faceUpTransform.a) XCTAssertEqual(unchangeableTransform.b, faceUpTransform.b) XCTAssertEqual(unchangeableTransform.c, faceUpTransform.c) } }
mit
a4aeb33e38a4076a0794a782a8d2b52a
48.466667
82
0.765162
4.988235
false
true
false
false
TinyDragonApps/Usages
Stats/TableViewCells/UsageTableViewCell.swift
1
2108
// // UsageTableViewCell.swift // Stats // // Created by Joseph Pintozzi on 9/28/14. // Copyright (c) 2014 Tiny Dragon Apps. All rights reserved. // import UIKit class UsageTableViewCell: UITableViewCell { let nameLabel: UILabel = UILabel() let detailLabel: UILabel = UILabel() let iconView: UIImageView = UIImageView() let progressBar: TYMProgressBarView = TYMProgressBarView() override init(frame: CGRect) { super.init(frame: frame) } override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) var frame = self.frame //name label nameLabel.frame = CGRectMake(60.0, 0.0, frame.size.width - 120.0, 20.0) nameLabel.text = "Override Me" self.addSubview(nameLabel) detailLabel.frame = CGRectMake(frame.size.width - 120, 0.0, 105, 20.0) detailLabel.text = "25/50" detailLabel.autoresizingMask = UIViewAutoresizing.FlexibleLeftMargin detailLabel.textColor = UIColor.darkGrayColor() detailLabel.textAlignment = NSTextAlignment.Right detailLabel.font = UIFont.italicSystemFontOfSize(13.0) self.addSubview(detailLabel) // icon view iconView.frame = CGRectMake(5, 5, frame.size.height - 10, frame.size.height - 10) self.addSubview(iconView) // progress bar progressBar.frame = CGRectMake(60.0, 20.0, frame.size.width - 75.0, frame.size.height - 25.0) progressBar.barBorderWidth = 1.0 progressBar.progress = 0.25 progressBar.autoresizingMask = UIViewAutoresizing.FlexibleWidth self.addSubview(progressBar) } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func awakeFromNib() { super.awakeFromNib() // Initialization code } override func setSelected(selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } }
gpl-2.0
18760cc9d88f50e87d4abf07179655d9
33
101
0.664137
4.485106
false
false
false
false
daniel-beard/2049
2049/GameScene.swift
1
8421
// // GameScene.swift // 2049 // // Created by Daniel Beard on 12/6/14. // Copyright (c) 2014 DanielBeard. All rights reserved. // import SpriteKit func afterDelay(_ delay: TimeInterval, performBlock block:@escaping () -> Void) { let dispatchTime = DispatchTime.now() + Double(Int64(delay * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC) DispatchQueue.main.asyncAfter(deadline: dispatchTime, execute: block) } // The number tile, with a rounded rect around it final class SKNumberNode: SKShapeNode, Codable { var labelNode: SKLabelNode! init(rectOfSize: CGSize, text: String) { super.init() let rect = CGRect(origin: .zero, size: rectOfSize).insetBy(dx: 20, dy: 20) self.path = CGPath(roundedRect: rect, cornerWidth: 5, cornerHeight: 5, transform: nil) self.fillColor = .orange labelNode = SKLabelNode(text: text) addChild(labelNode) labelNode.zPosition = 100 labelNode.fontColor = .white labelNode.fontName = "DamascusBold" labelNode.fontSize = text.count == 1 ? 32 : 20 if text.count == 1 { labelNode.position = CGPoint(x: (rect.size.width), y: (rect.size.height / 2) + ((labelNode.frame.size.height / 2) - 2)) } else { labelNode.position = CGPoint(x: rect.size.width, y: rect.size.height - (labelNode.frame.size.height / 2)) } } // Dummy Codable conformance, we just want to use this in an Array2DTyped. private var _dummy: String = "" private enum CodingKeys: String, CodingKey { case _dummy } required init(coder: NSCoder) { fatalError("Not implemented") } } // Tappable Label final class TappableLabel: SKLabelNode { var action: (() -> Void)? init(action: @escaping () -> Void) { super.init() self.action = action isUserInteractionEnabled = true } required init?(coder aDecoder: NSCoder) { fatalError("Not implemented") } override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) { action?() } } class GameScene: SKScene { // Constants let gridStartX = 355 let gridStartY = 440 let gridWidth = 80 let gridHeight = 80 let gridSize = 4 let tileTransitionDuration = 0.2 let updateDuration = 0.2 // Variables var gameManager: GameManager! var gameViewInfo: GameViewInfo? var numberTiles: Array2DTyped<SKNumberNode?>! var isAnimating = false var scoreLabel: SKLabelNode! var highScoreLabel: SKLabelNode! var titleLabel: SKLabelNode! var resetLabel: SKLabelNode! override func didMove(to view: SKView) { numberTiles = Array2DTyped(cols: gridSize, rows: gridSize, defaultValue: nil) if let savedGameState = Persistence.savedGameState() { gameManager = savedGameState gameManager.viewDelegate = self setupGrid() gameManager.startFromRestoredState() } else { gameManager = GameManager(size: gridSize, viewDelegate: self) setupGrid() gameManager.restart() } } func setupGrid() { titleLabel = SKLabelNode(text: "2049") titleLabel.fontColor = .white titleLabel.fontSize = 60 titleLabel.fontName = "DamascusBold" titleLabel.position = CGPoint(x: self.frame.midX, y: self.frame.height - 100) addChild(titleLabel) for (x, y) in gameManager.grid { // Setup grid squares let currentPoint = CGPoint(x: x, y: y) let currentRect = gridElementRectForPoint(currentPoint) let shapeNode = SKShapeNode(rect: currentRect) shapeNode.fillColor = .white shapeNode.strokeColor = .black shapeNode.lineWidth = 2 addChild(shapeNode) } scoreLabel = SKLabelNode(text: "Score: 0") scoreLabel.fontColor = .white scoreLabel.fontSize = 32 scoreLabel.fontName = "DamascusRegular" scoreLabel.position = CGPoint(x: self.frame.midX, y: gridLabelPositionForPoint(CGPoint(x: 0, y: gridSize)).y + 10) addChild(scoreLabel) highScoreLabel = SKLabelNode(text: "High Score: \(Persistence.currentHighScore())") highScoreLabel.fontColor = .white highScoreLabel.fontSize = 32 highScoreLabel.fontName = "DamascusRegular" highScoreLabel.position = CGPoint(x: scoreLabel.position.x, y: scoreLabel.position.y - 35) addChild(highScoreLabel) resetLabel = TappableLabel(action: { [weak self] in self?.alertRestartGame() }) resetLabel.text = "RESET" resetLabel.fontName = "DamascusBold" resetLabel.fontSize = 32 resetLabel.fontColor = .white resetLabel.position = CGPoint(x: scoreLabel.position.x, y: highScoreLabel.position.y - 65) addChild(resetLabel) } func alertRestartGame() { let alert = UIAlertController() alert.title = "Restart game?" alert.addAction(UIAlertAction(title: "Really reset?", style: .destructive, handler: { [weak self] (_) in self?.gameManager.restart() })) alert.addAction(UIAlertAction(title: "Cancel", style: .cancel)) UIApplication.shared.keyWindow?.rootViewController?.present(alert, animated: true, completion: nil) } // Note: Returns center point of the frame! // Returns a CGPoint for a label in the grid given an input point. func gridLabelPositionForPoint(_ point: CGPoint) -> CGPoint { let gridElementRect = gridElementRectForPoint(point) let centerPosition = CGPoint(x: gridElementRect.midX, y: gridElementRect.midY) return centerPosition } func gridElementRectForPoint(_ point: CGPoint) -> CGRect { let x = gridStartX + (gridWidth * Int(point.x)) let y = gridStartY - (gridHeight * Int(point.y)) return CGRect(x: x, y: y, width: gridWidth, height: gridHeight) } } //MARK: View Delegate Extension extension GameScene : GameViewDelegate { func updateViewState(_ gameViewInfo: GameViewInfo) { guard isAnimating == false else { return } isAnimating = true self.gameViewInfo = gameViewInfo // Game ended if self.gameViewInfo?.terminated ?? false { //TODODB: Create restart game overlay here... } // Animate moving labels for transition in gameViewInfo.positionTransitions where transition.type == .Moved { moveTile(transition) } // Update static labels afterDelay(updateDuration, performBlock: { self.updateNumberTiles() self.isAnimating = false self.updateScore(self.gameViewInfo?.score ?? 0) }) } func moveTile(_ transition: PositionTransition) { guard let node = numberTiles[transition.start.x, transition.start.y] else { return } node.run(SKAction.move(to: gridElementRectForPoint(transition.end.asPoint()).origin, duration: tileTransitionDuration)) } func updateScore(_ newScore: Int) { // Save game & highscore Persistence.writeGameState(state: gameManager) Persistence.updateHighScoreIfNeeded(gameManager.score) // Update labels scoreLabel.text = "Score: \(newScore)" highScoreLabel.text = "High Score: \(Persistence.currentHighScore())" } } extension GameScene { func updateNumberTiles() { for (x, y) in gameManager.grid { // If we have an existing label, remove it if let node = numberTiles[x, y] { node.removeFromParent() } numberTiles[x, y] = nil // If we have content, add a new tile if let content = gameViewInfo?.grid.cellContent(Position(x: x, y: y)) { let gridRect = gridElementRectForPoint(CGPoint(x: x, y: y)) let numberNode = SKNumberNode(rectOfSize: gridRect.size, text: "\(content.value)") numberNode.position = gridRect.origin numberTiles[x, y] = numberNode self.addChild(numberNode) } } } }
mit
5ecb140713eb087de29ddc14954972b9
34.23431
122
0.614773
4.486414
false
false
false
false
DukeLenny/Weibo
Weibo/Weibo/Class/View(视图和控制器)/Main/Controller/WBTabBarController.swift
1
5194
// // WBTabBarController.swift // Weibo // // Created by LiDinggui on 2017/9/1. // Copyright © 2017年 DAQSoft. All rights reserved. // import UIKit class WBTabBarController: UITabBarController { fileprivate let errorTolerantRate: CGFloat = 1.0 fileprivate lazy var middleButton: UIButton = UIButton.button(imageName: "tabbar_compose_icon_add", backgroundImageName: "tabbar_compose_button", highlightedImageName: "tabbar_compose_icon_add_highlighted", highlightedBackgroundImageName: "tabbar_compose_button_highlighted") override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. setChildViewControllers() setMiddleButton() } @objc fileprivate func middleButtonClicked() { print("展示出发布微博的界面") } 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. } */ } extension WBTabBarController { fileprivate func setChildViewControllers() { let dictionaryArray = [ ["className" : "WBHomeViewController", "title" : "首页", "imageName" : "tabbar_home", "selectedImageName" : "tabbar_home_selected"], ["className" : "WBMessageViewController", "title" : "消息", "imageName" : "tabbar_message_center", "selectedImageName" : "tabbar_message_center_selected"], ["className" : "WBBaseViewController"], ["className" : "WBDiscoverViewController", "title" : "发现", "imageName" : "tabbar_discover", "selectedImageName" : "tabbar_discover_selected"], ["className" : "WBProfileViewController", "title" : "我", "imageName" : "tabbar_profile", "selectedImageName" : "tabbar_profile_selected"] ] var vcs = [UIViewController]() for dictionary in dictionaryArray { vcs.append(viewController(dictionary: dictionary)) } viewControllers = vcs } /// 根据信息字典得到对应视图控制器 /// /// - Parameter dictionary: 信息字典 /// - Returns: 视图控制器 private func viewController(dictionary: [String : String]) -> UIViewController { guard let className = dictionary["className"], let title = dictionary["title"], let imageName = dictionary["imageName"], let selectedImageName = dictionary["selectedImageName"], let classType = NSClassFromString(Bundle.main.namespace + "." + className) as? WBBaseViewController.Type else { return WBBaseViewController() } let viewController = classType.init() // viewController.navigationItem.title = title viewController.navItem.title = title let nc = WBNavigationController(rootViewController: viewController) nc.tabBarItem.title = title nc.tabBarItem.image = UIImage(named: imageName)?.withRenderingMode(.alwaysOriginal) nc.tabBarItem.selectedImage = UIImage(named: selectedImageName)?.withRenderingMode(.alwaysOriginal) nc.tabBarItem.setTitleTextAttributes([NSForegroundColorAttributeName : TabBarTintColor], for: .selected) nc.tabBarItem.setTitleTextAttributes([NSFontAttributeName : UIFont.systemFont(ofSize: 12)], for: .normal) return nc } fileprivate func setMiddleButton() { tabBar.addSubview(middleButton) let count = CGFloat(childViewControllers.count) let width = tabBar.bounds.width / count - errorTolerantRate // - 1.0是为了盖住容错点 middleButton.frame = tabBar.bounds.insetBy(dx: 2 * width, dy: 0) // 向内为正,向外为负 middleButton.addTarget(self, action: #selector(middleButtonClicked), for: .touchUpInside) } } // MARK: - Rotation extension WBTabBarController { override var shouldAutorotate: Bool { if let selectedViewController = selectedViewController { return selectedViewController.shouldAutorotate } return true } override var supportedInterfaceOrientations: UIInterfaceOrientationMask { if let selectedViewController = selectedViewController { return selectedViewController.supportedInterfaceOrientations } return .portrait } override var preferredInterfaceOrientationForPresentation: UIInterfaceOrientation { if let selectedViewController = selectedViewController { return selectedViewController.preferredInterfaceOrientationForPresentation } return .portrait } }
mit
b71ae9b64f9b5174f4242fa4595c06dd
40.942149
297
0.650246
5.456989
false
false
false
false
imace/open-muvr
ios/Lift/LiftServer/LiftServerURLs.swift
2
9164
import Foundation /// /// The request to the Lift server-side code /// struct LiftServerRequest { var path: String var method: Method init(path: String, method: Method) { self.path = path self.method = method } } /// /// Defines mechanism to convert a request to LiftServerRequest /// protocol LiftServerRequestConvertible { var Request: LiftServerRequest { get } } /// /// The Lift server URLs and request data mappers /// enum LiftServerURLs : LiftServerRequestConvertible { /// /// Register the user /// case UserRegister() /// /// Login the user /// case UserLogin() /// /// Adds an iOS device for the user identified by ``userId`` /// case UserRegisterDevice(/*userId: */NSUUID) /// /// Retrieves the user's profile for the ``userId`` /// case UserGetPublicProfile(/*userId: */NSUUID) /// /// Sets the user's profile for the ``userId`` /// case UserSetPublicProfile(/*userId: */NSUUID) /// /// Gets the user's profile image /// case UserGetProfileImage(/*userId: */NSUUID) /// /// Sets the user's profile image /// case UserSetProfileImage(/*userId: */NSUUID) /// /// Checks that the account is still there /// case UserCheckAccount(/*userId: */NSUUID) /// /// Get supported muscle groups /// case ExerciseGetMuscleGroups() /// /// Retrieves all the exercises for the given ``userId`` and ``date`` /// case ExerciseGetExerciseSessionsSummary(/*userId: */NSUUID, /*date: */NSDate) /// /// Retrieves all the session dates for the given ``userId`` /// case ExerciseGetExerciseSessionsDates(/*userId: */NSUUID) /// /// Retrieves all the exercises for the given ``userId`` and ``sessionId`` /// case ExerciseGetExerciseSession(/*userId: */NSUUID, /*sessionId: */NSUUID) /// /// Retrieves future exercise session suggestions for give ``userId`` /// case ExerciseGetExerciseSuggestions(/*userId: */NSUUID) /// /// Deletes all the exercises for the given ``userId`` and ``sessionId`` /// case ExerciseDeleteExerciseSession(/*userId: */NSUUID, /*sessionId: */NSUUID) /// /// Starts an exercise session for the given ``userId`` /// case ExerciseSessionStart(/*userId: */NSUUID) /// /// Abandons the exercise session for the given ``userId`` and ``sessionId``. /// case ExerciseSessionAbandon(/*userId: */NSUUID, /*sessionId: */NSUUID) /// /// Starts the replay of an existing session for the given user /// case ExerciseSessionReplayStart(/*userId: */NSUUID, /* sessionId */ NSUUID) /// /// Replays the exercise session for the given ``userId`` and ``sessionId``. /// case ExerciseSessionReplayData(/*userId: */NSUUID, /*sessionId: */NSUUID) /// /// Submits the data (received from the smartwatch) for the given ``userId``, ``sessionId`` /// case ExerciseSessionSubmitData(/*userId: */NSUUID, /*sessionId: */NSUUID) /// /// Submits the feedback for the given ``userId``, ``sessionId`` /// case ExerciseSessionSubmitFeedback(/*userId: */NSUUID, /*sessionId: */NSUUID) /// /// Gets exercise classification examples for the given ``userId`` and ``sessionId`` /// case ExerciseSessionGetClassificationExamples(/*userId: */NSUUID, /*sessionId: */NSUUID) /// /// Gets exercise classification examples for the given ``userId`` /// case ExerciseGetClassificationExamples(/*userId: */NSUUID) /// /// Ends the session for the given ``userId`` and ``sessionId`` /// case ExerciseSessionEnd(/*userId: */NSUUID, /*sessionId: */NSUUID) /// /// Starts the explicit exercise classification for ``userId`` and ``sessionId`` /// case ExplicitExerciseClassificationStart(/*userId: */NSUUID, /*sessionId: */NSUUID) /// /// Stops the explicit exercise classification for ``userId`` and ``sessionId`` /// case ExplicitExerciseClassificationStop(/*userId: */NSUUID, /*sessionId: */NSUUID) private struct Format { private static let simpleDateFormatter: NSDateFormatter = { let dateFormatter = NSDateFormatter() dateFormatter.dateFormat = "yyyy-MM-dd" return dateFormatter }() static func simpleDate(date: NSDate) -> String { return simpleDateFormatter.stringFromDate(date) } } // MARK: URLStringConvertible var Request: LiftServerRequest { get { let r: LiftServerRequest = { switch self { case let .UserRegister: return LiftServerRequest(path: "/user", method: Method.POST) case let .UserLogin: return LiftServerRequest(path: "/user", method: Method.PUT) case .UserRegisterDevice(let userId): return LiftServerRequest(path: "/user/\(userId.UUIDString)/device/ios", method: Method.POST) case .UserGetPublicProfile(let userId): return LiftServerRequest(path: "/user/\(userId.UUIDString)", method: Method.GET) case .UserSetPublicProfile(let userId): return LiftServerRequest(path: "/user/\(userId.UUIDString)", method: Method.POST) case .UserCheckAccount(let userId): return LiftServerRequest(path: "/user/\(userId.UUIDString)/check", method: Method.GET) case .UserGetProfileImage(let userId): return LiftServerRequest(path: "/user/\(userId.UUIDString)/image", method: Method.GET) case .UserSetProfileImage(let userId): return LiftServerRequest(path: "/user/\(userId.UUIDString)/image", method: Method.POST) case .ExerciseGetMuscleGroups(): return LiftServerRequest(path: "/exercise/musclegroups", method: Method.GET) case .ExerciseGetExerciseSessionsSummary(let userId, let date): return LiftServerRequest(path: "/exercise/\(userId.UUIDString)?date=\(Format.simpleDate(date))", method: Method.GET) case .ExerciseGetExerciseSessionsDates(let userId): return LiftServerRequest(path: "/exercise/\(userId.UUIDString)", method: Method.GET) case .ExerciseGetExerciseSession(let userId, let sessionId): return LiftServerRequest(path: "/exercise/\(userId.UUIDString)/\(sessionId.UUIDString)", method: Method.GET) case .ExerciseDeleteExerciseSession(let userId, let sessionId): return LiftServerRequest(path: "/exercise/\(userId.UUIDString)/\(sessionId.UUIDString)", method: Method.DELETE) case .ExerciseSessionStart(let userId): return LiftServerRequest(path: "/exercise/\(userId.UUIDString)/start", method: Method.POST) case .ExerciseSessionSubmitData(let userId, let sessionId): return LiftServerRequest(path: "/exercise/\(userId.UUIDString)/\(sessionId.UUIDString)", method: Method.PUT) case .ExerciseSessionSubmitFeedback(let userId, let sessionId): return LiftServerRequest(path: "/exercise/\(userId.UUIDString)/\(sessionId.UUIDString)/feedback", method: Method.POST) case .ExerciseSessionEnd(let userId, let sessionId): return LiftServerRequest(path: "/exercise/\(userId.UUIDString)/\(sessionId.UUIDString)/end", method: Method.POST) case .ExerciseSessionAbandon(let userId, let sessionId): return LiftServerRequest(path: "/exercise/\(userId.UUIDString)/\(sessionId.UUIDString)/abandon", method: Method.POST) case .ExerciseSessionReplayStart(let userId, let sessionId): return LiftServerRequest(path: "/exercise/\(userId.UUIDString)/\(sessionId.UUIDString)/replay", method: Method.POST) case .ExerciseSessionReplayData(let userId, let sessionId): return LiftServerRequest(path: "/exercise/\(userId.UUIDString)/\(sessionId.UUIDString)/replay", method: Method.PUT) case .ExerciseSessionGetClassificationExamples(let userId, let sessionId): return LiftServerRequest(path: "/exercise/\(userId.UUIDString)/\(sessionId.UUIDString)/classification", method: Method.GET) case .ExerciseGetClassificationExamples(let userId): return LiftServerRequest(path: "/exercise/\(userId.UUIDString)/classification", method: Method.GET) case .ExplicitExerciseClassificationStart(let userId, let sessionId): return LiftServerRequest(path: "/exercise/\(userId.UUIDString)/\(sessionId.UUIDString)/classification", method: Method.POST) case .ExplicitExerciseClassificationStop(let userId, let sessionId): return LiftServerRequest(path: "/exercise/\(userId.UUIDString)/\(sessionId.UUIDString)/classification", method: Method.DELETE) case .ExerciseGetExerciseSuggestions(let userId): return LiftServerRequest(path: "/exercise/\(userId.UUIDString)/suggestions", method: Method.GET) } }() return r } } }
apache-2.0
13ae17c0df93671ffd368e8571cb3f12
42.638095
214
0.645788
4.890075
false
false
false
false
adrfer/swift
test/Interpreter/SDK/objc_inner_pointer.swift
14
1428
// RUN: %target-run-simple-swift | FileCheck %s // REQUIRES: executable_test // REQUIRES: objc_interop import Foundation class Canary: NSObject { deinit { print("died") } } var CanaryAssocObjectHandle: UInt8 = 0 // Attach an associated object with a loud deinit so we can see that the // object died. func hangCanary(o: AnyObject) { objc_setAssociatedObject(o, &CanaryAssocObjectHandle, Canary(), .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } // CHECK-LABEL: NSData: print("NSData:") autoreleasepool { var bytes: UnsafeMutablePointer<UInt8> repeat { let data = NSData(bytes: [2, 3, 5, 7] as [UInt8], length: 4) hangCanary(data) bytes = UnsafeMutablePointer<UInt8>(data.bytes) } while false // CHECK-NOT: died print(bytes[0]) // CHECK: 2 print(bytes[1]) // CHECK-NEXT: 3 print(bytes[2]) // CHECK-NEXT: 5 print(bytes[3]) // CHECK-NEXT: 7 } // CHECK-NEXT: died // CHECK-LABEL: AnyObject: print("AnyObject:") autoreleasepool { var bytes: UnsafeMutablePointer<UInt8> repeat { let data = NSData(bytes: [11, 13, 17, 19] as [UInt8], length: 4) hangCanary(data) let dataAsAny: AnyObject = data bytes = UnsafeMutablePointer<UInt8>(dataAsAny.bytes!) } while false // CHECK-NOT: died print(bytes[0]) // CHECK: 11 print(bytes[1]) // CHECK-NEXT: 13 print(bytes[2]) // CHECK-NEXT: 17 print(bytes[3]) // CHECK-NEXT: 19 } // CHECK-NEXT: died
apache-2.0
ca3107abe7c9e06fd5cc9600416454b1
25.943396
72
0.660364
3.408115
false
false
false
false
Octadero/TensorFlow
Sources/TensorFlowKit/Summary.swift
1
7532
/* Copyright 2017 The Octadero Authors. All Rights Reserved. Created by Volodymyr Pavliukevych on 2017. Licensed under the GPL License, Version 3.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.gnu.org/licenses/gpl-3.0.txt Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ import Foundation import CTensorFlow import Proto import CAPI public enum SummaryError: Error { case notReady case incorrectImageSize } ///Summaries provide a way to export condensed information about a model, which is then accessible in tools such as [TensorBoard](https://www.tensorflow.org/get_started/summaries_and_tensorboard). /// TensorBoard operates by reading TensorFlow events files, /// which contain summary data that you can generate when running TensorFlow. /// Here's the general lifecycle for summary data within TensorBoard. public class Summary { /// Storage for outputs added to summary. var values = [Output]() let scope: Scope /// Associated scope public init(scope: Scope) { self.scope = scope } /// Add scalar value output to `Summary`. public func scalar(output: Output, key: String) throws { let tensor = try Tensor(dimensions: [Int64](), values: [key]) let const = try scope.addConst(tensor: tensor, as: key + "TagConst").defaultOutput let operation = try scope.scalarSummary(operationName: key, tags: const, values: output) self.values.append(operation) } /// Add histogram value output to `Summary`. public func histogram(output: Output, key: String) throws { let tensor = try Tensor(dimensions: [Int64](), values: [key]) let const = try scope.addConst(tensor: tensor, as: key + "TagConst").defaultOutput let operation = try scope.histogramSummary(operationName: key, tag: const, values: output) self.values.append(operation) } public enum Channel: Int { case grayscale = 1 case rgb = 3 case rgba = 4 var value: Int { return rawValue } } /// Represents BadColor options for `Summary` image `Tensor`. public struct BadColor { public let channel: Channel public let colorComponents: [UInt8] public init(channel: Channel, colorComponents: [UInt8]) { self.channel = channel self.colorComponents = colorComponents } public static let `default` = BadColor(channel: .grayscale, colorComponents: [UInt8(255)]) } /// Represents Image size for `Summary` image `Tensor`. public struct ImageSize { public let width: Int public let height: Int public var points: Int { return width * height } public init(width: Int, height: Int) { self.height = height self.width = width } } /// Add image to `Summary` public func images(name: String, batchSize: Int, size: ImageSize, values: [Float], maxImages: UInt8 = 255, badColor: BadColor = BadColor.default) throws { guard batchSize * size.points * badColor.channel.value == values.count else { throw SummaryError.incorrectImageSize } let imageTensor = try Tensor(dimensions: [batchSize, size.width, size.height, badColor.channel.value], values: values) let const = try scope.addConst(tensor: imageTensor, as: "Image-\(name)-\(UUID().uuidString)-Const") try images(name: name, output: const.defaultOutput, maxImages: maxImages, badColor: badColor) } ///Add images to `Summary`. /// Outputs a `Summary` protocol buffer with images. /// The summary has up to `max_images` summary values containing images. The /// images are built from `tensor` which must be 4-D with shape `[batch_size, /// height, width, channels]` and where `channels` can be: /// /// * 1: `tensor` is interpreted as Grayscale. /// * 3: `tensor` is interpreted as RGB. /// * 4: `tensor` is interpreted as RGBA. /// /// The images have the same number of channels as the input tensor. For float /// input, the values are normalized one image at a time to fit in the range /// `[0, 255]`. `uint8` values are unchanged. The op uses two different /// normalization algorithms: /// /// * If the input values are all positive, they are rescaled so the largest one /// is 255. /// /// * If any input value is negative, the values are shifted so input value 0.0 /// is at 127. They are then rescaled so that either the smallest value is 0, /// or the largest one is 255. /// /// The `tag` argument is a scalar `Tensor` of type `string`. It is used to /// build the `tag` of the summary values: /// /// * If `max_images` is 1, the summary value tag is ' * tag * /image'. /// * If `max_images` is greater than 1, the summary value tags are /// generated sequentially as ' * tag * /image/0', ' * tag * /image/1', etc. /// /// The `bad_color` argument is the color to use in the generated images for /// non-finite input values. It is a `unit8` 1-D tensor of length `channels`. /// Each element must be in the range `[0, 255]` (It represents the value of a /// pixel in the output image). Non-finite values in the input tensor are /// replaced by this tensor in the output image. The default value is the color /// red. /// - Parameter tag: Scalar. Used to build the `tag` attribute of the summary values. /// - Parameter tensor: 4-D of shape `[batch_size, height, width, channels]` where /// `channels` is 1, 3, or 4. /// - Parameter maxImages: Max number of batch elements to generate images for. /// - Parameter badColor: Color to use for pixels with non-finite values. /// - Returns: /// summary: Scalar. Serialized `Summary` protocol buffer. public func images(name: String, output: Output, maxImages: UInt8 = 255, badColor: BadColor = BadColor.default) throws { let tensor = try Tensor(dimensions: [Int64](), values: [name]) let const = try scope.addConst(tensor: tensor, as: "Tag-\(name)-\(UUID().uuidString)-Const").defaultOutput let badColorTensor = try Tensor(dimensions: [Int64(badColor.channel.value)], values: badColor.colorComponents) let operation = try scope.imageSummary(operationName: name + UUID().uuidString, tag: const, tensor: output, maxImages: maxImages, badColor: badColorTensor) self.values.append(operation) } /// It merge all outputs and provide them as one output. /// This op creates a [`Summary`](https://www.tensorflow.org/code/tensorflow/core/framework/summary.proto) /// protocol buffer that contains the union of all the values in the input /// summaries. public func merged(identifier: String = UUID().uuidString) throws -> Output { let output = try scope.mergeSummary(operationName: "MergeSummary-\(identifier)", inputs: self.values, n: UInt8(self.values.count)) self.values.removeAll() return output } }
gpl-3.0
e0b4567f53671646d05b0f7d3c78d59b
42.537572
196
0.654408
4.205472
false
false
false
false
slavapestov/swift
stdlib/public/core/Unicode.swift
1
31087
//===----------------------------------------------------------------------===// // // 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 // //===----------------------------------------------------------------------===// // Conversions between different Unicode encodings. Note that UTF-16 and // UTF-32 decoding are *not* currently resilient to erroneous data. /// The result of one Unicode decoding step. /// /// A unicode scalar value, an indication that no more unicode scalars /// are available, or an indication of a decoding error. public enum UnicodeDecodingResult { case Result(UnicodeScalar) case EmptyInput case Error /// Return true if `self` indicates no more unicode scalars are /// available. @warn_unused_result public func isEmptyInput() -> Bool { switch self { case .EmptyInput: return true default: return false } } } /// A Unicode [encoding scheme](http://www.unicode.org/glossary/#character_encoding_scheme). /// /// Consists of an underlying [code unit](http://www.unicode.org/glossary/#code_unit) and functions to /// translate between sequences of these code units and [unicode scalar values](http://www.unicode.org/glossary/#unicode_scalar_value). public protocol UnicodeCodecType { /// A type that can hold [code unit](http://www.unicode.org/glossary/#code_unit) values for this /// encoding. associatedtype CodeUnit init() /// Start or continue decoding a UTF sequence. /// /// In order to decode a code unit sequence completely, this function should /// be called repeatedly until it returns `UnicodeDecodingResult.EmptyInput`. /// Checking that the generator was exhausted is not sufficient. The decoder /// can have an internal buffer that is pre-filled with data from the input /// generator. /// /// Because of buffering, it is impossible to find the corresponding position /// in the generator for a given returned `UnicodeScalar` or an error. /// /// - parameter next: A *generator* of code units to be decoded. mutating func decode< G : GeneratorType where G.Element == CodeUnit >(inout next: G) -> UnicodeDecodingResult /// Encode a `UnicodeScalar` as a series of `CodeUnit`s by /// calling `output` on each `CodeUnit`. static func encode(input: UnicodeScalar, output: (CodeUnit) -> Void) } /// A codec for [UTF-8](http://www.unicode.org/glossary/#UTF_8). public struct UTF8 : UnicodeCodecType { /// A type that can hold [code unit](http://www.unicode.org/glossary/#code_unit) values for this /// encoding. public typealias CodeUnit = UInt8 public init() {} /// Returns the number of expected trailing bytes for a given first byte: 0, /// 1, 2 or 3. If the first byte cannot start a valid UTF-8 code unit /// sequence, returns 4. @warn_unused_result public static func _numTrailingBytes(cu0: CodeUnit) -> UInt8 { if _fastPath(cu0 & 0x80 == 0) { // 0x00 -- 0x7f: 1-byte sequences. return 0 } // 0xc0 -- 0xc1: invalid first byte. // 0xc2 -- 0xdf: 2-byte sequences. // 0xe0 -- 0xef: 3-byte sequences. // 0xf0 -- 0xf4: 4-byte sequences. // 0xf5 -- 0xff: invalid first byte. // The rules above are represented as a lookup table. The lookup table // consists of two words, where `high` contains the high bit of the result, // `low` contains the low bit. // // Bit patterns: // high | low | meaning // -----+-----+---------------- // 0 | 0 | 2-byte sequence // 0 | 1 | 3-byte sequence // 1 | 0 | 4-byte sequence // 1 | 1 | invalid // // This implementation allows us to handle these cases without branches. // ---------0xf?------- ---------0xe?------- ---------0xd?------- ---------0xc?------- let low: UInt64 = 0b1111_1111__1110_0000__1111_1111__1111_1111__0000_0000__0000_0000__0000_0000__0000_0011 let high: UInt64 = 0b1111_1111__1111_1111__0000_0000__0000_0000__0000_0000__0000_0000__0000_0000__0000_0011 let index = UInt64(max(0, Int(cu0) - 0xc0)) let highBit = ((high >> index) & 1) << 1 let lowBit = (low >> index) & 1 return UInt8(1 + (highBit | lowBit)) } /// Lookahead buffer used for UTF-8 decoding. New bytes are inserted at LSB, /// and bytes are read at MSB. var _decodeLookahead: UInt32 = 0 /// Flags with layout: `0bxxxx_yyyy`. /// /// `xxxx` is the EOF flag. It means that the input generator has signaled /// end of sequence. Out of the four bits, only one bit can be set. The bit /// position specifies how many bytes have been consumed from the lookahead /// buffer already. A value of `1000` means that there are `yyyy` bytes in /// the buffer, `0100` means that there are `yyyy - 1` bytes, `0010` -- /// `yyyy - 2`, `0001` -- `yyyy - 3`. /// /// `yyyy` specifies how many bytes are valid in the lookahead buffer. Value /// is expressed in unary code. Valid values: `1111` (4), `0111` (3), /// `0011` (2), `0001` (1), `0000` (0). /// /// This representation is crafted to allow one to consume a byte from a /// buffer with a shift, and update flags with a single-bit right shift. var _lookaheadFlags: UInt8 = 0 /// Return `true` if the LSB bytes in `buffer` are well-formed UTF-8 code /// unit sequence. @warn_unused_result static func _isValidUTF8Impl(buffer: UInt32, length: UInt8) -> Bool { switch length { case 4: let cu3 = UInt8((buffer >> 24) & 0xff) if cu3 < 0x80 || cu3 > 0xbf { return false } fallthrough case 3: let cu2 = UInt8((buffer >> 16) & 0xff) if cu2 < 0x80 || cu2 > 0xbf { return false } fallthrough case 2: let cu0 = UInt8(buffer & 0xff) let cu1 = UInt8((buffer >> 8) & 0xff) switch cu0 { case 0xe0: if cu1 < 0xa0 || cu1 > 0xbf { return false } case 0xed: if cu1 < 0x80 || cu1 > 0x9f { return false } case 0xf0: if cu1 < 0x90 || cu1 > 0xbf { return false } case 0xf4: if cu1 < 0x80 || cu1 > 0x8f { return false } default: _sanityCheck(cu0 >= 0xc2 && cu0 <= 0xf4, "invalid first bytes should be handled in the caller") if cu1 < 0x80 || cu1 > 0xbf { return false } } return true default: _sanityCheckFailure("one-byte sequences should be handled in the caller") } } /// Return `true` if the LSB bytes in `buffer` are well-formed UTF-8 code /// unit sequence. @warn_unused_result static func _isValidUTF8(buffer: UInt32, validBytes: UInt8) -> Bool { _sanityCheck(validBytes & 0b0000_1111 != 0, "input buffer should not be empty") let cu0 = UInt8(buffer & 0xff) let trailingBytes = _numTrailingBytes(cu0) switch trailingBytes { case 0: return true case 1, 2, 3: // We *don't* need to check the if the buffer actually contains at least // `trailingBytes` bytes. Here's why. // // If the buffer is not full -- contains fewer than 4 bytes, we are at // EOF, and the buffer will be padded with 0x00. Thus, an incomplete // code unit sequence just before EOF would be seen by code below as // padded with nuls. This sequence will be rejected by the logic in // `_isValidUTF8Impl`, because the nul byte is not a valid continuation // byte for UTF-8. return _isValidUTF8Impl(buffer, length: trailingBytes + 1) default: return false } } /// Given an ill-formed sequence, find the length of its maximal subpart. @inline(never) @warn_unused_result static func _findMaximalSubpartOfIllFormedUTF8Sequence( buffer: UInt32, validBytes: UInt8) -> UInt8 { var buffer = buffer var validBytes = validBytes // This function is '@inline(never)' because it is used only in the error // handling path. // Clear EOF flag, we don't care about it. validBytes &= 0b0000_1111 _sanityCheck(validBytes != 0, "input buffer should not be empty") _sanityCheck(!UTF8._isValidUTF8(buffer, validBytes: validBytes), "input sequence should be ill-formed UTF-8") // Unicode 6.3.0, D93b: // // Maximal subpart of an ill-formed subsequence: The longest code unit // subsequence starting at an unconvertible offset that is either: // a. the initial subsequence of a well-formed code unit sequence, or // b. a subsequence of length one. // Perform case analysis. See Unicode 6.3.0, Table 3-7. Well-Formed UTF-8 // Byte Sequences. let cu0 = UInt8(buffer & 0xff) buffer >>= 8 validBytes >>= 1 if (cu0 >= 0xc2 && cu0 <= 0xdf) { // First byte is valid, but we know that this code unit sequence is // invalid, so the maximal subpart has to end after the first byte. return 1 } if validBytes == 0 { return 1 } let cu1 = UInt8(buffer & 0xff) buffer >>= 8 validBytes >>= 1 if (cu0 == 0xe0) { return (cu1 >= 0xa0 && cu1 <= 0xbf) ? 2 : 1 } if (cu0 >= 0xe1 && cu0 <= 0xec) { return (cu1 >= 0x80 && cu1 <= 0xbf) ? 2 : 1 } if (cu0 == 0xed) { return (cu1 >= 0x80 && cu1 <= 0x9f) ? 2 : 1 } if (cu0 >= 0xee && cu0 <= 0xef) { return (cu1 >= 0x80 && cu1 <= 0xbf) ? 2 : 1 } if (cu0 == 0xf0) { if (cu1 >= 0x90 && cu1 <= 0xbf) { if validBytes == 0 { return 2 } let cu2 = UInt8(buffer & 0xff) return (cu2 >= 0x80 && cu2 <= 0xbf) ? 3 : 2 } return 1 } if (cu0 >= 0xf1 && cu0 <= 0xf3) { if (cu1 >= 0x80 && cu1 <= 0xbf) { if validBytes == 0 { return 2 } let cu2 = UInt8(buffer & 0xff) return (cu2 >= 0x80 && cu2 <= 0xbf) ? 3 : 2 } return 1 } if (cu0 == 0xf4) { if (cu1 >= 0x80 && cu1 <= 0x8f) { if validBytes == 0 { return 2 } let cu2 = UInt8(buffer & 0xff) return (cu2 >= 0x80 && cu2 <= 0xbf) ? 3 : 2 } return 1 } _sanityCheck((cu0 >= 0x80 && cu0 <= 0xc1) || cu0 >= 0xf5, "case analysis above should have handled all valid first bytes") // There are no well-formed sequences that start with these bytes. Maximal // subpart is defined to have length 1 in these cases. return 1 } /// Start or continue decoding a UTF sequence. /// /// In order to decode a code unit sequence completely, this function should /// be called repeatedly until it returns `UnicodeDecodingResult.EmptyInput`. /// Checking that the generator was exhausted is not sufficient. The decoder /// can have an internal buffer that is pre-filled with data from the input /// generator. /// /// Because of buffering, it is impossible to find the corresponding position /// in the generator for a given returned `UnicodeScalar` or an error. /// /// - parameter next: A *generator* of code units to be decoded. public mutating func decode< G : GeneratorType where G.Element == CodeUnit >(inout next: G) -> UnicodeDecodingResult { // If the EOF flag is not set, fill the lookahead buffer from the input // generator. if _lookaheadFlags & 0b1111_0000 == 0 { // Add more bytes into the buffer until we have 4. while _lookaheadFlags != 0b0000_1111 { if let codeUnit = next.next() { _decodeLookahead = (_decodeLookahead << 8) | UInt32(codeUnit) _lookaheadFlags = (_lookaheadFlags << 1) | 1 } else { // Set the EOF flag. switch _lookaheadFlags & 0b0000_1111 { case 0b1111: _sanityCheckFailure("should have not entered buffer refill loop") case 0b0111: _lookaheadFlags |= 0b0100_0000 case 0b0011: _lookaheadFlags |= 0b0010_0000 case 0b0001: _lookaheadFlags |= 0b0001_0000 case 0b0000: _lookaheadFlags |= 0b1000_0000 return .EmptyInput default: _sanityCheckFailure("bad value in _lookaheadFlags") } break } } } if _slowPath(_lookaheadFlags & 0b0000_1111 == 0) { return .EmptyInput } if _slowPath(_lookaheadFlags & 0b1111_0000 != 0) { // Reached EOF. Restore the invariant: first unread byte is always at // MSB. switch _lookaheadFlags & 0b1111_0000 { case 0b1000_0000: break case 0b0100_0000: _decodeLookahead <<= 1 * 8 case 0b0010_0000: _decodeLookahead <<= 2 * 8 case 0b0001_0000: _decodeLookahead <<= 3 * 8 default: _sanityCheckFailure("bad value in _lookaheadFlags") } _lookaheadFlags = (_lookaheadFlags & 0b0000_1111) | 0b1000_0000 } // The first byte to read is located at MSB of `_decodeLookahead`. Get a // representation of the buffer where we can read bytes starting from LSB. var buffer = _decodeLookahead.byteSwapped if _slowPath(!UTF8._isValidUTF8(buffer, validBytes: _lookaheadFlags)) { // The code unit sequence is ill-formed. According to Unicode // recommendation, replace the maximal subpart of ill-formed sequence // with one replacement character. _lookaheadFlags >>= UTF8._findMaximalSubpartOfIllFormedUTF8Sequence(buffer, validBytes: _lookaheadFlags) return .Error } // At this point we know that `buffer` starts with a well-formed code unit // sequence. Decode it. // // When consuming bytes from the `buffer`, we just need to update // `_lookaheadFlags`. The stored buffer in `_decodeLookahead` will be // shifted at the beginning of the next decoding cycle. let cu0 = UInt8(buffer & 0xff) buffer >>= 8 _lookaheadFlags >>= 1 if cu0 < 0x80 { // 1-byte sequences. return .Result(UnicodeScalar(UInt32(cu0))) } // Start with octet 1 (we'll mask off high bits later). var result = UInt32(cu0) let cu1 = UInt8(buffer & 0xff) buffer >>= 8 _lookaheadFlags >>= 1 result = (result << 6) | UInt32(cu1 & 0x3f) if cu0 < 0xe0 { // 2-byte sequences. return .Result(UnicodeScalar(result & 0x000007ff)) // 11 bits } let cu2 = UInt8(buffer & 0xff) buffer >>= 8 _lookaheadFlags >>= 1 result = (result << 6) | UInt32(cu2 & 0x3f) if cu0 < 0xf0 { // 3-byte sequences. return .Result(UnicodeScalar(result & 0x0000ffff)) // 16 bits } // 4-byte sequences. let cu3 = UInt8(buffer & 0xff) _lookaheadFlags >>= 1 result = (result << 6) | UInt32(cu3 & 0x3f) return .Result(UnicodeScalar(result & 0x001fffff)) // 21 bits } /// Encode a `UnicodeScalar` as a series of `CodeUnit`s by /// calling `output` on each `CodeUnit`. public static func encode( input: UnicodeScalar, output put: (CodeUnit) -> Void ) { var c = UInt32(input) var buf3 = UInt8(c & 0xFF) if c >= UInt32(1<<7) { c >>= 6 buf3 = (buf3 & 0x3F) | 0x80 // 10xxxxxx var buf2 = UInt8(c & 0xFF) if c < UInt32(1<<5) { buf2 |= 0xC0 // 110xxxxx } else { c >>= 6 buf2 = (buf2 & 0x3F) | 0x80 // 10xxxxxx var buf1 = UInt8(c & 0xFF) if c < UInt32(1<<4) { buf1 |= 0xE0 // 1110xxxx } else { c >>= 6 buf1 = (buf1 & 0x3F) | 0x80 // 10xxxxxx put(UInt8(c | 0xF0)) // 11110xxx } put(buf1) } put(buf2) } put(buf3) } /// Return `true` if `byte` is a continuation byte of the form /// `0b10xxxxxx`. @warn_unused_result public static func isContinuation(byte: CodeUnit) -> Bool { return byte & 0b11_00__0000 == 0b10_00__0000 } var _value = UInt8() } /// A codec for [UTF-16](http://www.unicode.org/glossary/#UTF_16). public struct UTF16 : UnicodeCodecType { /// A type that can hold [code unit](http://www.unicode.org/glossary/#code_unit) values for this /// encoding. public typealias CodeUnit = UInt16 public init() {} /// A lookahead buffer for one UTF-16 code unit. var _decodeLookahead: UInt32 = 0 /// Flags with layout: `0b0000_00xy`. /// /// `y` is the EOF flag. /// /// `x` is set when `_decodeLookahead` contains a code unit. var _lookaheadFlags: UInt8 = 0 /// Start or continue decoding a UTF sequence. /// /// In order to decode a code unit sequence completely, this function should /// be called repeatedly until it returns `UnicodeDecodingResult.EmptyInput`. /// Checking that the generator was exhausted is not sufficient. The decoder /// can have an internal buffer that is pre-filled with data from the input /// generator. /// /// Because of buffering, it is impossible to find the corresponding position /// in the generator for a given returned `UnicodeScalar` or an error. /// /// - parameter next: A *generator* of code units to be decoded. public mutating func decode< G : GeneratorType where G.Element == CodeUnit >(inout input: G) -> UnicodeDecodingResult { if _lookaheadFlags & 0b01 != 0 { return .EmptyInput } // Note: maximal subpart of ill-formed sequence for UTF-16 can only have // length 1. Length 0 does not make sense. Neither does length 2 -- in // that case the sequence is valid. var unit0: UInt32 if _fastPath(_lookaheadFlags & 0b10 == 0) { if let first = input.next() { unit0 = UInt32(first) } else { // Set EOF flag. _lookaheadFlags |= 0b01 return .EmptyInput } } else { // Fetch code unit from the lookahead buffer and note this fact in flags. unit0 = _decodeLookahead _lookaheadFlags &= 0b01 } // A well-formed pair of surrogates looks like this: // [1101 10ww wwxx xxxx] [1101 11xx xxxx xxxx] if _fastPath((unit0 >> 11) != 0b1101_1) { // Neither high-surrogate, nor low-surrogate -- sequence of 1 code unit, // decoding is trivial. return .Result(UnicodeScalar(unit0)) } if _slowPath((unit0 >> 10) == 0b1101_11) { // `unit0` is a low-surrogate. We have an ill-formed sequence. return .Error } // At this point we know that `unit0` is a high-surrogate. var unit1: UInt32 if let second = input.next() { unit1 = UInt32(second) } else { // EOF reached. Set EOF flag. _lookaheadFlags |= 0b01 // We have seen a high-surrogate and EOF, so we have an ill-formed // sequence. return .Error } if _fastPath((unit1 >> 10) == 0b1101_11) { // `unit1` is a low-surrogate. We have a well-formed surrogate pair. let result = 0x10000 + (((unit0 & 0x03ff) << 10) | (unit1 & 0x03ff)) return .Result(UnicodeScalar(result)) } // Otherwise, we have an ill-formed sequence. These are the possible // cases: // // * `unit1` is a high-surrogate, so we have a pair of two high-surrogates. // // * `unit1` is not a surrogate. We have an ill-formed sequence: // high-surrogate followed by a non-surrogate. // Save the second code unit in the lookahead buffer. _decodeLookahead = unit1 _lookaheadFlags |= 0b10 return .Error } /// Try to decode one Unicode scalar, and return the actual number of code /// units it spanned in the input. This function may consume more code /// units than required for this scalar. mutating func _decodeOne< G : GeneratorType where G.Element == CodeUnit >(inout input: G) -> (UnicodeDecodingResult, Int) { let result = decode(&input) switch result { case .Result(let us): return (result, UTF16.width(us)) case .EmptyInput: return (result, 0) case .Error: return (result, 1) } } /// Encode a `UnicodeScalar` as a series of `CodeUnit`s by /// calling `output` on each `CodeUnit`. public static func encode( input: UnicodeScalar, output put: (CodeUnit) -> Void ) { let scalarValue: UInt32 = UInt32(input) if scalarValue <= UInt32(UInt16.max) { put(UInt16(scalarValue)) } else { let lead_offset = UInt32(0xd800) - UInt32(0x10000 >> 10) put(UInt16(lead_offset + (scalarValue >> 10))) put(UInt16(0xdc00 + (scalarValue & 0x3ff))) } } var _value = UInt16() } /// A codec for [UTF-32](http://www.unicode.org/glossary/#UTF_32). public struct UTF32 : UnicodeCodecType { /// A type that can hold [code unit](http://www.unicode.org/glossary/#code_unit) values for this /// encoding. public typealias CodeUnit = UInt32 public init() {} /// Start or continue decoding a UTF sequence. /// /// In order to decode a code unit sequence completely, this function should /// be called repeatedly until it returns `UnicodeDecodingResult.EmptyInput`. /// Checking that the generator was exhausted is not sufficient. The decoder /// can have an internal buffer that is pre-filled with data from the input /// generator. /// /// Because of buffering, it is impossible to find the corresponding position /// in the generator for a given returned `UnicodeScalar` or an error. /// /// - parameter next: A *generator* of code units to be decoded. public mutating func decode< G : GeneratorType where G.Element == CodeUnit >(inout input: G) -> UnicodeDecodingResult { return UTF32._decode(&input) } static func _decode< G : GeneratorType where G.Element == CodeUnit >(inout input: G) -> UnicodeDecodingResult { guard let x = input.next() else { return .EmptyInput } if _fastPath((x >> 11) != 0b1101_1 && x <= 0x10ffff) { return .Result(UnicodeScalar(x)) } else { return .Error } } /// Encode a `UnicodeScalar` as a series of `CodeUnit`s by /// calling `output` on each `CodeUnit`. public static func encode( input: UnicodeScalar, output put: (CodeUnit) -> Void ) { put(UInt32(input)) } } /// Translate `input`, in the given `InputEncoding`, into `output`, in /// the given `OutputEncoding`. /// /// - parameter stopOnError: Causes encoding to stop when an encoding /// error is detected in `input`, if `true`. Otherwise, U+FFFD /// replacement characters are inserted for each detected error. public func transcode< Input : GeneratorType, InputEncoding : UnicodeCodecType, OutputEncoding : UnicodeCodecType where InputEncoding.CodeUnit == Input.Element>( inputEncoding: InputEncoding.Type, _ outputEncoding: OutputEncoding.Type, _ input: Input, _ output: (OutputEncoding.CodeUnit) -> Void, stopOnError: Bool ) -> Bool { var input = input // NB. It is not possible to optimize this routine to a memcpy if // InputEncoding == OutputEncoding. The reason is that memcpy will not // substitute U+FFFD replacement characters for ill-formed sequences. var inputDecoder = inputEncoding.init() var hadError = false var scalar = inputDecoder.decode(&input) while !scalar.isEmptyInput() { switch scalar { case .Result(let us): OutputEncoding.encode(us, output: output) case .EmptyInput: _sanityCheckFailure("should not enter the loop when input becomes empty") case .Error: if stopOnError { return (hadError: true) } else { OutputEncoding.encode("\u{fffd}", output: output) hadError = true } } scalar = inputDecoder.decode(&input) } return hadError } /// Transcode UTF-16 to UTF-8, replacing ill-formed sequences with U+FFFD. /// /// Returns the index of the first unhandled code unit and the UTF-8 data /// that was encoded. @warn_unused_result internal func _transcodeSomeUTF16AsUTF8< Input : CollectionType where Input.Generator.Element == UInt16>( input: Input, _ startIndex: Input.Index ) -> (Input.Index, _StringCore.UTF8Chunk) { typealias UTF8Chunk = _StringCore.UTF8Chunk let endIndex = input.endIndex let utf8Max = sizeof(UTF8Chunk.self) var result: UTF8Chunk = 0 var utf8Count = 0 var nextIndex = startIndex while nextIndex != input.endIndex && utf8Count != utf8Max { let u = UInt(input[nextIndex]) let shift = UTF8Chunk(utf8Count * 8) var utf16Length: Input.Index.Distance = 1 if _fastPath(u <= 0x7f) { result |= UTF8Chunk(u) << shift utf8Count += 1 } else { var scalarUtf8Length: Int var r: UInt if _fastPath((u >> 11) != 0b1101_1) { // Neither high-surrogate, nor low-surrogate -- well-formed sequence // of 1 code unit, decoding is trivial. if u < 0x800 { r = 0b10__00_0000__110__0_0000 r |= u >> 6 r |= (u & 0b11_1111) << 8 scalarUtf8Length = 2 } else { r = 0b10__00_0000__10__00_0000__1110__0000 r |= u >> 12 r |= ((u >> 6) & 0b11_1111) << 8 r |= (u & 0b11_1111) << 16 scalarUtf8Length = 3 } } else { let unit0 = u if _slowPath((unit0 >> 10) == 0b1101_11) { // `unit0` is a low-surrogate. We have an ill-formed sequence. // Replace it with U+FFFD. r = 0xbdbfef scalarUtf8Length = 3 } else if _slowPath(nextIndex.advancedBy(1) == endIndex) { // We have seen a high-surrogate and EOF, so we have an ill-formed // sequence. Replace it with U+FFFD. r = 0xbdbfef scalarUtf8Length = 3 } else { let unit1 = UInt(input[nextIndex.advancedBy(1)]) if _fastPath((unit1 >> 10) == 0b1101_11) { // `unit1` is a low-surrogate. We have a well-formed surrogate // pair. let v = 0x10000 + (((unit0 & 0x03ff) << 10) | (unit1 & 0x03ff)) r = 0b10__00_0000__10__00_0000__10__00_0000__1111_0__000 r |= v >> 18 r |= ((v >> 12) & 0b11_1111) << 8 r |= ((v >> 6) & 0b11_1111) << 16 r |= (v & 0b11_1111) << 24 scalarUtf8Length = 4 utf16Length = 2 } else { // Otherwise, we have an ill-formed sequence. Replace it with // U+FFFD. r = 0xbdbfef scalarUtf8Length = 3 } } } // Don't overrun the buffer if utf8Count + scalarUtf8Length > utf8Max { break } result |= numericCast(r) << shift utf8Count += scalarUtf8Length } nextIndex = nextIndex.advancedBy(utf16Length) } // FIXME: Annoying check, courtesy of <rdar://problem/16740169> if utf8Count < sizeofValue(result) { result |= ~0 << numericCast(utf8Count * 8) } return (nextIndex, result) } /// Instances of conforming types are used in internal `String` /// representation. public // @testable protocol _StringElementType { @warn_unused_result static func _toUTF16CodeUnit(_: Self) -> UTF16.CodeUnit @warn_unused_result static func _fromUTF16CodeUnit(utf16: UTF16.CodeUnit) -> Self } extension UTF16.CodeUnit : _StringElementType { public // @testable static func _toUTF16CodeUnit(x: UTF16.CodeUnit) -> UTF16.CodeUnit { return x } public // @testable static func _fromUTF16CodeUnit( utf16: UTF16.CodeUnit ) -> UTF16.CodeUnit { return utf16 } } extension UTF8.CodeUnit : _StringElementType { public // @testable static func _toUTF16CodeUnit(x: UTF8.CodeUnit) -> UTF16.CodeUnit { _sanityCheck(x <= 0x7f, "should only be doing this with ASCII") return UTF16.CodeUnit(x) } public // @testable static func _fromUTF16CodeUnit( utf16: UTF16.CodeUnit ) -> UTF8.CodeUnit { _sanityCheck(utf16 <= 0x7f, "should only be doing this with ASCII") return UTF8.CodeUnit(utf16) } } extension UTF16 { /// Return the number of code units required to encode `x`. @warn_unused_result public static func width(x: UnicodeScalar) -> Int { return x.value <= 0xFFFF ? 1 : 2 } /// Return the high surrogate code unit of a [surrogate pair](http://www.unicode.org/glossary/#surrogate_pair) representing /// `x`. /// /// - Requires: `width(x) == 2`. @warn_unused_result public static func leadSurrogate(x: UnicodeScalar) -> UTF16.CodeUnit { _precondition(width(x) == 2) return UTF16.CodeUnit((x.value - 0x1_0000) >> (10 as UInt32)) + 0xD800 } /// Return the low surrogate code unit of a [surrogate pair](http://www.unicode.org/glossary/#surrogate_pair) representing /// `x`. /// /// - Requires: `width(x) == 2`. @warn_unused_result public static func trailSurrogate(x: UnicodeScalar) -> UTF16.CodeUnit { _precondition(width(x) == 2) return UTF16.CodeUnit( (x.value - 0x1_0000) & (((1 as UInt32) << 10) - 1) ) + 0xDC00 } @warn_unused_result public static func isLeadSurrogate(x: CodeUnit) -> Bool { return 0xD800...0xDBFF ~= x } @warn_unused_result public static func isTrailSurrogate(x: CodeUnit) -> Bool { return 0xDC00...0xDFFF ~= x } public // @testable static func _copy<T : _StringElementType, U : _StringElementType>( source: UnsafeMutablePointer<T>, destination: UnsafeMutablePointer<U>, count: Int ) { if strideof(T.self) == strideof(U.self) { _memcpy( dest: UnsafeMutablePointer(destination), src: UnsafeMutablePointer(source), size: UInt(count) * UInt(strideof(U.self))) } else { for i in 0..<count { let u16 = T._toUTF16CodeUnit((source + i).memory) (destination + i).memory = U._fromUTF16CodeUnit(u16) } } } /// Returns the number of UTF-16 code units required for the given code unit /// sequence when transcoded to UTF-16, and a bit describing if the sequence /// was found to contain only ASCII characters. /// /// If `repairIllFormedSequences` is `true`, the function always succeeds. /// If it is `false`, `nil` is returned if an ill-formed code unit sequence is /// found in `input`. @warn_unused_result public static func measure< Encoding : UnicodeCodecType, Input : GeneratorType where Encoding.CodeUnit == Input.Element >( _: Encoding.Type, input: Input, repairIllFormedSequences: Bool ) -> (Int, Bool)? { var input = input var count = 0 var isAscii = true var inputDecoder = Encoding() loop: while true { switch inputDecoder.decode(&input) { case .Result(let us): if us.value > 0x7f { isAscii = false } count += width(us) case .EmptyInput: break loop case .Error: if !repairIllFormedSequences { return nil } isAscii = false count += width(UnicodeScalar(0xfffd)) } } return (count, isAscii) } }
apache-2.0
60cb58bab6510d633c1d8c0d8e9cfea5
31.449896
135
0.611381
3.739565
false
false
false
false
yakaolife/TrackLocations
Example/Tests/TrackLocationsSpec.swift
1
3464
// // TrackLocationsSpec.swift // TrackLocations // // Created by Ya Kao on 7/17/17. // Copyright © 2017 CocoaPods. All rights reserved. // import Quick import Nimble import Alamofire import SwiftyJSON import TrackLocations class TrackLocationsSpec: QuickSpec { override func spec() { describe("trackLocation func") { it("can load data from firebase"){ waitUntil(action: { done in Tracker.load(requestURL: "https://mylocations-cc913.firebaseio.com/testing.json", callback: { (success, locations, error) in expect(success) == true expect(error) == TrackLocationsError.NoError expect(locations).toNot(beNil()) if let loc = locations{ expect(loc.count) == 3 for l in loc{ if l.name == "SF Ferry Building"{ expect(l.latitude) == 37.795545 expect(l.longitude) == -122.392967 }else if l.name == "Iterable"{ expect(l.latitude) == 37.782923 expect(l.longitude) == -122.398377 }else if l.name == "SF MOMA"{ expect(l.latitude) == 37.78595 expect(l.longitude) == -122.401081 }else{ print("This test case failed, data isn't loading correctly") expect(true) == false } } } done() }) }) } it("can return error from loading"){ waitUntil(action: { done in Tracker.load(requestURL: "https://mylocations-cc913.firebaseio.com/wrongURL", callback: { (success, locations, error) in expect(success) == false expect(locations).to(beNil()) expect(error) == TrackLocationsError.RequestError done() }) }) } it("can return error from JSON parsing"){ waitUntil(action: { done in Tracker.load(requestURL: "https:/mylocations-cc913.firebaseio.com/wrongJSON.json", callback: { (success, locations, error) in expect(success) == false expect(locations).to(beNil()) expect(error) == TrackLocationsError.JSONError done() }) }) } it("can return error from incompatible format"){ waitUntil(action: { done in Tracker.load(requestURL: "https:/mylocations-cc913.firebaseio.com/wrongFormat.json", callback: { (success, locations, error) in expect(success) == false expect(locations).to(beNil()) expect(error) == TrackLocationsError.FormatError done() }) }) } } } }
mit
09523870f5097cd2acd979bebad577e8
39.267442
147
0.428819
5.640065
false
false
false
false
wangela/wittier
wittier/Views/InfiniteScrollActivityView.swift
1
1217
// // InfiniteScrollActivityView.swift // wittier // // Created by Angela Yu on 10/1/17. // Copyright © 2017 Angela Yu. All rights reserved. // import UIKit class InfiniteScrollActivityView: UIView { var activityIndicatorView: UIActivityIndicatorView = UIActivityIndicatorView() static let defaultHeight:CGFloat = 60.0 required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setupActivityIndicator() } override init(frame aRect: CGRect) { super.init(frame: aRect) setupActivityIndicator() } override func layoutSubviews() { super.layoutSubviews() activityIndicatorView.center = CGPoint(x: self.bounds.size.width/2, y: self.bounds.size.height/2) } func setupActivityIndicator() { activityIndicatorView.activityIndicatorViewStyle = .gray activityIndicatorView.hidesWhenStopped = true self.addSubview(activityIndicatorView) } func stopAnimating() { self.activityIndicatorView.stopAnimating() self.isHidden = true } func startAnimating() { self.isHidden = false self.activityIndicatorView.startAnimating() } }
mit
528f83efa18bf1fec2bfa456979fe2b5
26.022222
105
0.67023
5.109244
false
false
false
false
hipposan/LemonDeer
Sources/SegmentDownloader.swift
1
2869
// // SegmentDownloader.swift // WindmillComic // // Created by Ziyi Zhang on 09/06/2017. // Copyright © 2017 Ziyideas. All rights reserved. // import Foundation protocol SegmentDownloaderDelegate { func segmentDownloadSucceeded(with downloader: SegmentDownloader) func segmentDownloadFailed(with downloader: SegmentDownloader) } class SegmentDownloader: NSObject { var fileName: String var filePath: String var downloadURL: String var duration: Float var index: Int lazy var downloadSession: URLSession = { let configuration = URLSessionConfiguration.default let session = URLSession(configuration: configuration, delegate: self, delegateQueue: nil) return session }() var downloadTask: URLSessionDownloadTask? var resumeData: Data? var isDownloading = false var delegate: SegmentDownloaderDelegate? init(with url: String, filePath: String, fileName: String, duration: Float, index: Int) { downloadURL = url self.filePath = filePath self.fileName = fileName self.duration = duration self.index = index } func startDownload() { if checkIfIsDownloaded() { delegate?.segmentDownloadSucceeded(with: self) return } else { downloadTask = downloadSession.downloadTask(with: URL(string: downloadURL)!) downloadTask?.resume() isDownloading = true } } func cancelDownload() { downloadTask?.cancel() isDownloading = false } func pauseDownload() { if isDownloading { downloadTask?.suspend() isDownloading = false } } func resumeDownload() { downloadTask?.resume() isDownloading = true } func checkIfIsDownloaded() -> Bool { let filePath = generateFilePath().path if FileManager.default.fileExists(atPath: filePath) { return true } else { return false } } func generateFilePath() -> URL { return getDocumentsDirectory().appendingPathComponent("Downloads").appendingPathComponent(filePath).appendingPathComponent(fileName) } } extension SegmentDownloader: URLSessionDownloadDelegate { func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) { let destinationURL = generateFilePath() if FileManager.default.fileExists(atPath: destinationURL.path) { delegate?.segmentDownloadSucceeded(with: self) return } else { do { try FileManager.default.moveItem(at: location, to: destinationURL) delegate?.segmentDownloadSucceeded(with: self) } catch let error as NSError { print(error.localizedDescription) } } } func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) { if error != nil { delegate?.segmentDownloadFailed(with: self) } } }
mit
1d84bb11f58efbf531eb82c05c1585fd
24.837838
136
0.696653
4.894198
false
false
false
false
nickplee/A-E-S-T-H-E-T-I-C-A-M
Aestheticam/Sources/Other Sources/Globals.swift
1
1536
// // Constants.swift // A E S T H E T I C A M // // Created by Nick Lee on 5/29/16. // Copyright © 2016 Nick Lee. All rights reserved. // import Foundation import FastttCamera struct Globals { static let apiURL = "http://api.nicholasleedesigns.com/aesthetic.php" static var persistedCaptureDevice: FastttCameraDevice { get { let defaults = UserDefaults.standard defaults.synchronize() guard let val = defaults.object(forKey: "persistedCaptureDevice") as? Int, let position = FastttCameraDevice(rawValue: val) else { return .rear } return position } set { let defaults = UserDefaults.standard defaults.set(newValue.rawValue, forKey: "persistedCaptureDevice") defaults.synchronize() } } static var lastDownloadDate: Date { get { let defaults = UserDefaults.standard defaults.synchronize() return (defaults.object(forKey: "lastDownloadDate") as? Date) ?? Date.distantPast } set { let defaults = UserDefaults.standard defaults.set(newValue, forKey: "lastDownloadDate") defaults.synchronize() } } static let downloadThreshold: TimeInterval = 60 * 60 * 24 * 3 // every three days static var needsDownload: Bool { get { return Date().timeIntervalSince(lastDownloadDate) >= downloadThreshold } } }
mit
9b01ab93cc2091de0a4330120508837c
27.962264
142
0.592834
4.737654
false
false
false
false
yanif/circator
MetabolicCompassWatchExtension/WeightMetric.swift
1
2344
// // WeightMetric.swift // MetabolicCompass // // Created by twoolf on 6/17/16. // Copyright © 2016 Yanif Ahmad, Tom Woolf. All rights reserved. // import Foundation final class WeightMetric: NSObject { private static let dateFormatter: NSDateFormatter = { let dateFormatter = NSDateFormatter() dateFormatter.dateFormat = "yyyy-MM-dd HH:mm" return dateFormatter }() let date: NSDate let pounds: Double // Calculated by HealthConditions var situation: HealthConditions.HealthSituation init(date: NSDate, pounds: Double) { self.date = date self.pounds = pounds self.situation = .Unknown super.init() } convenience init?(json: [String: AnyObject]) { guard let dateString = json["t"] as? String, poundsString = json["v"] as? String else { return nil } guard let date = WeightMetric.dateFormatter.dateFromString(dateString), let pounds = Double(poundsString) else { return nil } self.init(date: date, pounds: pounds) } override var description: String { return "WaterLevel: \(pounds)" } } // MARK: For Complication extension WeightMetric { var shortTextForComplication: String { return String(format: "%.1fm", self.pounds) } var longTextForComplication: String { return String(format: "%@, %.1fm",self.situation.rawValue, self.pounds) } } // MARK: NSCoding extension WeightMetric: NSCoding { private struct CodingKeys { static let date = "date" static let pounds = "pounds" static let situation = "situation" } convenience init(coder aDecoder: NSCoder) { let date = aDecoder.decodeObjectForKey(CodingKeys.date) as! NSDate let pounds = aDecoder.decodeDoubleForKey(CodingKeys.pounds) self.init(date: date, pounds: pounds) self.situation = HealthConditions.HealthSituation(rawValue: aDecoder.decodeObjectForKey(CodingKeys.situation) as! String)! } func encodeWithCoder(encoder: NSCoder) { encoder.encodeObject(date, forKey: CodingKeys.date) encoder.encodeDouble(pounds, forKey: CodingKeys.pounds) encoder.encodeObject(situation.rawValue, forKey: CodingKeys.situation) } }
apache-2.0
ff0942db86fddb9ed5361267e614988a
28.658228
130
0.647461
4.420755
false
false
false
false
jindulys/Leetcode_Solutions_Swift
Sources/Tree/124_BinaryTreeMaximumPathSum.swift
1
2491
// // 124_BinaryTreeMaximumPathSum.swift // LeetcodeSwift // // Created by yansong li on 2016-09-04. // Copyright © 2016 YANSONG LI. All rights reserved. // import Foundation /** Title:124 Binary Tree Maximum Path Sum URL: https://leetcode.com/problems/binary-tree-maximum-path-sum/ Space: O(n) Time: O(n^2) */ class BinaryTreeMaximumPathSum_Solution { func maxPathSum(_ root: TreeNode?) -> Int { let (_, anyMax) = maxPathSumHelper(root) return anyMax } fileprivate func maxPathSumHelper(_ root: TreeNode?) -> (Int, Int) { guard let root = root else { return (0, Int.min) } let (leftRootMax, leftAnyMax) = maxPathSumHelper(root.left) let (rightRootMax, rightAnyMax) = maxPathSumHelper(root.right) var currentRootMax = max(leftRootMax, rightRootMax) + root.val currentRootMax = max(currentRootMax, 0) var currentAnyMax = max(leftAnyMax, rightAnyMax) currentAnyMax = max(currentAnyMax, leftRootMax + rightRootMax + root.val) return (currentRootMax, currentAnyMax) } func maxPathSum_Memoized(_ root: TreeNode?) -> Int { let hashableTreeRoot = HashableTreeNode.buildHashableTreeWith(root) let (_, anyMax) = maxPathSumMemoized(hashableTreeRoot) return anyMax } fileprivate func maxPathSumMemoized(_ root: HashableTreeNode?) -> (Int, Int) { guard let root = root else { return (0, Int.min) } let ans:(HashableTreeNode) -> (Int, Int) = memoize { (ans: (HashableTreeNode) -> (Int, Int), currentNode: HashableTreeNode) -> (Int, Int) in var leftResult: (Int, Int) if let left = currentNode.left { leftResult = ans(left) } else { leftResult = (0, Int.min) } var rightResult: (Int, Int) if let right = currentNode.right { rightResult = ans(right) } else { rightResult = (0, Int.min) } var currentRootMax = max(leftResult.0, rightResult.0) + currentNode.val currentRootMax = max(currentRootMax, 0) var currentAnyMax = max(leftResult.1, rightResult.1) currentAnyMax = max(currentAnyMax, leftResult.0 + rightResult.0 + currentNode.val) return (currentRootMax, currentAnyMax) } return ans(root) } func test() { let node1 = TreeNode(1) let node2 = TreeNode(2) let node3 = TreeNode(3) node1.left = node2 node1.right = node3 let result = maxPathSum(node1) if result == 6 { print("Pass") } else { print("Fail") } } }
mit
3e0818eb6a8bde33aabd0a75c1ec0453
29
144
0.650602
3.448753
false
false
false
false
noppoMan/aws-sdk-swift
Sources/Soto/Services/FMS/FMS_Error.swift
1
3340
//===----------------------------------------------------------------------===// // // This source file is part of the Soto for AWS open source project // // Copyright (c) 2017-2020 the Soto project authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information // See CONTRIBUTORS.txt for the list of Soto project authors // // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// // THIS FILE IS AUTOMATICALLY GENERATED by https://github.com/soto-project/soto/tree/main/CodeGenerator. DO NOT EDIT. import SotoCore /// Error enum for FMS public struct FMSErrorType: AWSErrorType { enum Code: String { case internalErrorException = "InternalErrorException" case invalidInputException = "InvalidInputException" case invalidOperationException = "InvalidOperationException" case invalidTypeException = "InvalidTypeException" case limitExceededException = "LimitExceededException" case resourceNotFoundException = "ResourceNotFoundException" } private let error: Code public let context: AWSErrorContext? /// initialize FMS public init?(errorCode: String, context: AWSErrorContext) { guard let error = Code(rawValue: errorCode) else { return nil } self.error = error self.context = context } internal init(_ error: Code) { self.error = error self.context = nil } /// return error code string public var errorCode: String { self.error.rawValue } /// The operation failed because of a system problem, even though the request was valid. Retry your request. public static var internalErrorException: Self { .init(.internalErrorException) } /// The parameters of the request were invalid. public static var invalidInputException: Self { .init(.invalidInputException) } /// The operation failed because there was nothing to do or the operation wasn't possible. For example, you might have submitted an AssociateAdminAccount request for an account ID that was already set as the AWS Firewall Manager administrator. Or you might have tried to access a Region that's disabled by default, and that you need to enable for the Firewall Manager administrator account and for AWS Organizations before you can access it. public static var invalidOperationException: Self { .init(.invalidOperationException) } /// The value of the Type parameter is invalid. public static var invalidTypeException: Self { .init(.invalidTypeException) } /// The operation exceeds a resource limit, for example, the maximum number of policy objects that you can create for an AWS account. For more information, see Firewall Manager Limits in the AWS WAF Developer Guide. public static var limitExceededException: Self { .init(.limitExceededException) } /// The specified resource was not found. public static var resourceNotFoundException: Self { .init(.resourceNotFoundException) } } extension FMSErrorType: Equatable { public static func == (lhs: FMSErrorType, rhs: FMSErrorType) -> Bool { lhs.error == rhs.error } } extension FMSErrorType: CustomStringConvertible { public var description: String { return "\(self.error.rawValue): \(self.message ?? "")" } }
apache-2.0
ee3196fd0ac31c735e738948e2908f0a
45.388889
445
0.695808
5.138462
false
false
false
false
austinzheng/swift
test/IRGen/protocol_resilience_descriptors.swift
2
6273
// RUN: %empty-directory(%t) // Resilient protocol definition // RUN: %target-swift-frontend -emit-ir -enable-resilience -module-name=resilient_protocol %S/../Inputs/resilient_protocol.swift | %FileCheck -DINT=i%target-ptrsize -check-prefix=CHECK-DEFINITION %s // Resilient protocol usage // RUN: %target-swift-frontend -emit-module -enable-resilience -emit-module-path=%t/resilient_protocol.swiftmodule -module-name=resilient_protocol %S/../Inputs/resilient_protocol.swift // RUN: %target-swift-frontend -I %t -emit-ir -enable-resilience %s | %FileCheck %s -DINT=i%target-ptrsize -check-prefix=CHECK-USAGE // ---------------------------------------------------------------------------- // Resilient protocol definition // ---------------------------------------------------------------------------- // CHECK: @"default assoc type x" = linkonce_odr hidden constant // CHECK-SAME: i8 -1, [1 x i8] c"x", i8 0 // CHECK: @"default assoc type \01____y2T118resilient_protocol29ProtocolWithAssocTypeDefaultsPQzG 18resilient_protocol7WrapperV" = // Protocol descriptor // CHECK-DEFINITION-LABEL: @"$s18resilient_protocol29ProtocolWithAssocTypeDefaultsMp" ={{( protected)?}} constant // CHECK-DEFINITION-SAME: @"default associated conformance2T218resilient_protocol29ProtocolWithAssocTypeDefaultsP_AB014OtherResilientD0" // Associated type default + flags // CHECK-DEFINITION-SAME: [[INT]] add // CHECK-DEFINITION-SAME: @"default assoc type _____y2T1_____QzG 18resilient_protocol7WrapperV AA29ProtocolWithAssocTypeDefaultsP" // CHECK-DEFINITION-SAME: [[INT]] 1 // Protocol requirements base descriptor // CHECK-DEFINITION: @"$s18resilient_protocol21ResilientBaseProtocolTL" ={{( dllexport)?}}{{( protected)?}} alias %swift.protocol_requirement, getelementptr (%swift.protocol_requirement, %swift.protocol_requirement* getelementptr inbounds (<{ i32, i32, i32, i32, i32, i32, %swift.protocol_requirement }>, <{ i32, i32, i32, i32, i32, i32, %swift.protocol_requirement }>* @"$s18resilient_protocol21ResilientBaseProtocolMp", i32 0, i32 6), i32 -1) // Associated conformance descriptor for inherited protocol // CHECK-DEFINITION-LABEL: s18resilient_protocol24ResilientDerivedProtocolPAA0c4BaseE0Tb" ={{( dllexport)?}}{{( protected)?}} alias // Associated type and conformance // CHECK-DEFINITION: @"$s1T18resilient_protocol24ProtocolWithRequirementsPTl" ={{( dllexport)?}}{{( protected)?}} alias // CHECK-DEFINITION: @"$s18resilient_protocol29ProtocolWithAssocTypeDefaultsP2T2AC_AA014OtherResilientC0Tn" ={{( dllexport)?}}{{( protected)?}} alias // Default associated conformance witnesses // CHECK-DEFINITION-LABEL: define internal swiftcc i8** @"$s18resilient_protocol29ProtocolWithAssocTypeDefaultsP2T2AC_AA014OtherResilientC0TN" import resilient_protocol // ---------------------------------------------------------------------------- // Resilient witness tables // ---------------------------------------------------------------------------- // CHECK-USAGE-LABEL: $s31protocol_resilience_descriptors34ConformsToProtocolWithRequirementsVyxG010resilient_A00fgH0AAMc" = // CHECK-USAGE-SAME: {{got.|__imp_}}$s1T18resilient_protocol24ProtocolWithRequirementsPTl // CHECK-USAGE-SAME: @"symbolic x" public struct ConformsToProtocolWithRequirements<Element> : ProtocolWithRequirements { public typealias T = Element public func first() { } public func second() { } } public protocol P { } public struct ConditionallyConforms<Element> { } public struct Y { } // CHECK-USAGE-LABEL: @"$s31protocol_resilience_descriptors1YV010resilient_A022OtherResilientProtocolAAMc" = // CHECK-USAGE-SAME: i32 131072, // CHECK-USAGE-SAME: i16 0, // CHECK-USAGE-SAME: i16 0, // CHECK-USAGE-SAME: i32 0 extension Y: OtherResilientProtocol { } // CHECK-USAGE: @"$s31protocol_resilience_descriptors29ConformsWithAssocRequirementsV010resilient_A008ProtocoleF12TypeDefaultsAAMc" = // CHECK-USAGE-SAME: $s18resilient_protocol29ProtocolWithAssocTypeDefaultsP2T2AC_AA014OtherResilientC0Tn // CHECK-USAGE-SAME: @"associated conformance 31protocol_resilience_descriptors29ConformsWithAssocRequirementsV010resilient_A008ProtocoleF12TypeDefaultsAA2T2AdEP_AD014OtherResilientI0" public struct ConformsWithAssocRequirements : ProtocolWithAssocTypeDefaults { } // CHECK-USAGE: @"$s31protocol_resilience_descriptors21ConditionallyConformsVyxG010resilient_A024ProtocolWithRequirementsAaeFRzAA1YV1TRtzlMc" extension ConditionallyConforms: ProtocolWithRequirements where Element: ProtocolWithRequirements, Element.T == Y { public typealias T = Element.T public func first() { } public func second() { } } // CHECK-USAGE: @"$s31protocol_resilience_descriptors17ConformsToDerivedV010resilient_A009ResilientF8ProtocolAAMc" = // CHECK-SAME: @"associated conformance 31protocol_resilience_descriptors17ConformsToDerivedV010resilient_A009ResilientF8ProtocolAaD0h4BaseI0" public struct ConformsToDerived : ResilientDerivedProtocol { public func requirement() -> Int { return 0 } } // ---------------------------------------------------------------------------- // Resilient protocol usage // ---------------------------------------------------------------------------- // CHECK-USAGE: define{{( dllexport)?}}{{( protected)?}} swiftcc %swift.type* @"$s31protocol_resilience_descriptors17assocTypeMetadatay1TQzmxm010resilient_A024ProtocolWithRequirementsRzlF"(%swift.type*, %swift.type* [[PWD:%.*]], i8** [[WTABLE:%.*]]) public func assocTypeMetadata<PWR: ProtocolWithRequirements>(_: PWR.Type) -> PWR.T.Type { // CHECK-USAGE: call swiftcc %swift.metadata_response @swift_getAssociatedTypeWitness([[INT]] 0, i8** %PWR.ProtocolWithRequirements, %swift.type* %PWR, %swift.protocol_requirement* @"$s18resilient_protocol24ProtocolWithRequirementsTL", %swift.protocol_requirement* @"$s1T18resilient_protocol24ProtocolWithRequirementsPTl") return PWR.T.self } func useOtherResilientProtocol<T: OtherResilientProtocol>(_: T.Type) { } // CHECK-USAGE: define{{( dllexport)?}}{{( protected)?}} swiftcc void @"$s31protocol_resilience_descriptors23extractAssocConformanceyyx010resilient_A0012ProtocolWithE12TypeDefaultsRzlF" public func extractAssocConformance<T: ProtocolWithAssocTypeDefaults>(_: T) { // CHECK-USAGE: swift_getAssociatedConformanceWitness useOtherResilientProtocol(T.T2.self) }
apache-2.0
84cecc1418a08c2359433491706e80ae
58.742857
444
0.73091
4.116142
false
false
false
false
beepscore/WebKitty
WebKitty/ViewController.swift
1
7259
// // ViewController.swift // WebKitty // // Created by Steve Baker on 3/19/15. // Copyright (c) 2015 Beepscore LLC. All rights reserved. // import UIKit import WebKit class ViewController: UIViewController { // ! implies variable is optional, force unwrapped // app will crash if they aren't set before use var webView: WKWebView! // MARK: - view lifecycle override func viewDidLoad() { print("viewDidLoad") super.viewDidLoad() configureWebView() constrainWebView() //loadRequest() loadLocalFile(fileName: "index", fileType: "html") } // viewDidLayoutSubviews gets called upon rotation override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() print("viewDidLayoutSubviews") } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - layout func constrainWebView() { // http://code.tutsplus.com/tutorials/introduction-to-the-visual-format-language--cms-22715 let viewDict: [String: UIView] = Dictionary(dictionaryLiteral:("view", view), ("webView", webView)) let horizontalConstraints = NSLayoutConstraint.constraints(withVisualFormat: "H:|[webView]|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: viewDict) NSLayoutConstraint.activate(horizontalConstraints) let verticalConstraints = NSLayoutConstraint.constraints(withVisualFormat: "V:|[webView]|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: viewDict) NSLayoutConstraint.activate(verticalConstraints) printConstraints() } func printConstraints() { print("view.constraints().count \(view.constraints.count)") for constraint in view.constraints { print("\(constraint.debugDescription)") } print("") print("webView.constraints().count \(webView.constraints.count)") print("") } // MARK: - communicate between app and WKWebView /// adds user script to communicate from app to web page /// adds user script to communicate from web page to app func configureWebView() { let userContentController = WKUserContentController() // MARK: Communicate from app to web page // addUserScript() dynamically injects javascript from native Swift app into web page in the WKWebView. // App can use addUserScript() to customize any web page! // http://nshipster.com/wkwebkit/ userContentController.addUserScript(ViewController.userScriptBackgroundColor()) // MARK: Communicate from web page to app // To send a message, web page must contain javascript with one or more calls to postMessage(). // Original web page author can write the javascript, or // Swift app can use addUserScript to inject javascript into any web page. userContentController.addUserScript(ViewController.userScriptPostMessage()) // Register handler to get messages from WKWebView javascript into native Swift app. let webScriptMessageHandler = WebScriptMessageHandler() userContentController.add(webScriptMessageHandler, name: "notification") let configuration = WKWebViewConfiguration() configuration.userContentController = userContentController webView = WKWebView(frame: self.view.bounds, configuration: configuration) webView.translatesAutoresizingMaskIntoConstraints = false // on device to see webView background pinch view to zoom out webView.backgroundColor = UIColor.yellow webView.scrollView.backgroundColor = UIColor.red view.addSubview(webView); } /** Typically app calls userContentController.addUserScript(userScriptBackgroundColor()) - returns: script to set web page background color. This overrides setting in style.css */ class func userScriptBackgroundColor() -> WKUserScript { let paleBlueColor = "\"#CCF\"" let userScriptSource = "document.body.style.background = \(paleBlueColor);" let userScript = WKUserScript(source: userScriptSource, injectionTime: .atDocumentEnd, forMainFrameOnly: true) return userScript } /** Typically app calls userContentController.addUserScript(userScriptPostMessage()) - returns: script to call postMessage so web page will send message to app */ class func userScriptPostMessage() -> WKUserScript { let userScriptSource = "window.webkit.messageHandlers.notification.postMessage({body: \"Hi from javascript\"});" let userScript = WKUserScript(source: userScriptSource, injectionTime: .atDocumentEnd, forMainFrameOnly: true) return userScript } // MARK: - load urls into web page /// creates a request for a remote url and loads it func loadRequest() { // http://stackoverflow.com/questions/24410473/how-to-convert-this-var-string-to-nsurl-in-swift?rq=1 guard let url = URL(string: "http://www.beepscore.com") else { return } let request = URLRequest(url:url) webView.load(request) } /// Loads local file from main bundle using loadFileURL /// Note: In iOS 8 WKWebView loadRequest couldn't load a local file directly, /// had to use webView.loadHTMLString. /// /// - Parameters: /// - fileName: file name to load, e.g. "index" /// - fileType: may start with a period or not e.g. ".html" or "html" func loadLocalFile (fileName: String, fileType: String) { guard let url = Bundle.main.url(forResource: fileName, withExtension: fileType) else { return } // guard let cssUrl = Bundle.main.url(forResource: "style", // withExtension: "css") else { return } // guard let cssUrl2 = Bundle.main.url(forResource: "style", // withExtension: "css", // subdirectory: nil) else { return } // get url for directory instead of for just one file // http://stackoverflow.com/questions/40692737/how-to-get-path-to-a-subfolder-in-main-bundle guard let resourcePath = Bundle.main.resourcePath else { return } let webResourcesDirUrl = URL(fileURLWithPath:resourcePath) .appendingPathComponent("webResources") // http://stackoverflow.com/questions/24882834/wkwebview-not-loading-local-files-under-ios-8?rq=1 webView.loadFileURL(url, allowingReadAccessTo: webResourcesDirUrl) } }
mit
b5b5cb8845bec04b6ec38331049e7f1f
39.780899
120
0.620058
5.470234
false
false
false
false
moonrailgun/OpenCode
OpenCode/Classes/News/View/Hot/HotRepoView.swift
1
4860
// // HotRepoView.swift // OpenCode // // Created by 陈亮 on 16/5/31. // Copyright © 2016年 moonrailgun. All rights reserved. // import UIKit import SwiftyJSON import MJRefresh class HotRepoView: UIView, UITableViewDataSource, UITableViewDelegate { let HOT_CELL_ID = "hot" lazy var tableView:UITableView = UITableView(frame: self.bounds, style: .Plain) var hotRepoData:JSON? var controller:UIViewController? var currentMaxPage = 1 init(frame: CGRect, controller:UIViewController?) { super.init(frame: frame) self.controller = controller initView() initData() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func initData(){ Github.getGithubHotSearch(nil) { (data:AnyObject?) in if let d = data{ let json = JSON(d) //print(json) print("共\(json["total_count"].int!)个热门项目") let items = json["items"] self.hotRepoData = items OperationQueueHelper.operateInMainQueue({ let header = UILabel(frame: CGRectMake(0,0,self.bounds.width,24)) header.text = "共\(json["total_count"].int!)个热门项目" header.textColor = UIColor.whiteColor() header.backgroundColor = UIColor.alizarinFlatColor() header.textAlignment = .Center header.font = UIFont.systemFontOfSize(14) self.tableView.tableHeaderView = header self.tableView.reloadData() }) } } } func addonData(page:Int){ Github.getGithubHotSearch(page) { (data:AnyObject?) in if let d = data{ let json = JSON(d) print("加载新数据完毕,加载页码\(page)") let items = json["items"] if(self.hotRepoData != nil) { var tmp = self.hotRepoData?.array for i in 0 ... items.count - 1{ tmp!.append(items[i]) } self.hotRepoData = JSON(tmp!) } OperationQueueHelper.operateInMainQueue({ self.tableView.reloadData() self.endRefresh() }) } } } func initView(){ tableView.registerNib(UINib(nibName: "SearchRepoCell", bundle: nil), forCellReuseIdentifier: HOT_CELL_ID) tableView.rowHeight = 130 tableView.dataSource = self tableView.delegate = self tableView.mj_footer = MJRefreshAutoNormalFooter(refreshingBlock: { self.currentMaxPage += 1 self.addonData(self.currentMaxPage) }) self.addSubview(tableView) } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if(self.hotRepoData != nil) { return self.hotRepoData!.count }else{ return 0 } } func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { var cell = tableView.dequeueReusableCellWithIdentifier(HOT_CELL_ID) if(cell == nil){ cell = SearchRepoCell(style: .Default, reuseIdentifier: HOT_CELL_ID) } if(hotRepoData != nil){ let item = hotRepoData![indexPath.row] (cell as! SearchRepoCell).setData(item) } return cell! } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { print(indexPath) let item = self.hotRepoData![indexPath.row] if let repoFullName = item["full_name"].string{ ProgressHUD.show() Github.getRepoInfo(repoFullName, completionHandler: { (data:AnyObject?) in let controller = RepoDetailController() controller.repoDetailData = data OperationQueueHelper.operateInMainQueue({ ProgressHUD.dismiss() self.controller?.navigationController?.pushViewController(controller, animated: true) }) }) } } private func endRefresh(){ self.tableView.mj_footer.endRefreshing() } /* // Only override drawRect: if you perform custom drawing. // An empty implementation adversely affects performance during animation. override func drawRect(rect: CGRect) { // Drawing code } */ }
gpl-2.0
4706c1d450c2b1ff5160b7eb46c51852
31.47973
113
0.55544
5.033508
false
false
false
false
kstaring/swift
test/Misc/misc_diagnostics.swift
1
6232
// RUN: %target-parse-verify-swift // REQUIRES: objc_interop import Foundation import CoreGraphics var roomName : String? if let realRoomName = roomName as! NSString { // expected-error {{initializer for conditional binding must have Optional type, not 'NSString'}} expected-warning {{cast from 'String?' to unrelated type 'NSString' always fails}} } var pi = 3.14159265358979 var d: CGFloat = 2.0 var dpi:CGFloat = d*pi // expected-error{{binary operator '*' cannot be applied to operands of type 'CGFloat' and 'Double'}} // expected-note{{expected an argument list of type '(CGFloat, CGFloat)'}} let ff: CGFloat = floorf(20.0) // expected-error{{cannot convert value of type 'Float' to specified type 'CGFloat'}} let total = 15.0 let count = 7 let median = total / count // expected-error {{binary operator '/' cannot be applied to operands of type 'Double' and 'Int'}} expected-note {{overloads for '/' exist with these partially matching parameter lists: (Int, Int), (Double, Double)}} if (1) {} // expected-error{{'Int' is not convertible to 'Bool'}} if 1 {} // expected-error {{'Int' is not convertible to 'Bool'}} var a: [String] = [1] // expected-error{{cannot convert value of type 'Int' to expected element type 'String'}} var b: Int = [1, 2, 3] // expected-error{{contextual type 'Int' cannot be used with array literal}} var f1: Float = 2.0 var f2: Float = 3.0 var dd: Double = f1 - f2 // expected-error{{cannot convert value of type 'Float' to specified type 'Double'}} func f() -> Bool { return 1 + 1 // expected-error{{cannot convert return expression of type 'Int' to return type 'Bool'}} } // Test that nested diagnostics are properly surfaced. func takesInt(_ i: Int) {} func noParams() -> Int { return 0 } func takesAndReturnsInt(_ i: Int) -> Int { return 0 } takesInt(noParams(1)) // expected-error{{argument passed to call that takes no arguments}} takesInt(takesAndReturnsInt("")) // expected-error{{cannot convert value of type 'String' to expected argument type 'Int'}} // Test error recovery for type expressions. struct MyArray<Element> {} class A { var a: MyArray<Int> init() { a = MyArray<Int // expected-error{{binary operator '<' cannot be applied to operands of type 'MyArray<_>.Type' and 'Int.Type'}} // expected-note @-1 {{overloads for '<' exist with these partially matching parameter lists:}} } } func retV() { return true } // expected-error {{unexpected non-void return value in void function}} func retAI() -> Int { let a = [""] let b = [""] return (a + b) // expected-error{{cannot convert return expression of type '[String]' to return type 'Int'}} } func bad_return1() { return 42 // expected-error {{unexpected non-void return value in void function}} } func bad_return2() -> (Int, Int) { return 42 // expected-error {{cannot convert return expression of type 'Int' to return type '(Int, Int)'}} } // <rdar://problem/14096697> QoI: Diagnostics for trying to return values from void functions func bad_return3(lhs: Int, rhs: Int) { return lhs != 0 // expected-error {{unexpected non-void return value in void function}} } class MyBadReturnClass { static var intProperty = 42 } func ==(lhs:MyBadReturnClass, rhs:MyBadReturnClass) { return MyBadReturnClass.intProperty == MyBadReturnClass.intProperty // expected-error{{unexpected non-void return value in void function}} } func testIS1() -> Int { return 0 } let _: String = testIS1() // expected-error {{cannot convert value of type 'Int' to specified type 'String'}} func insertA<T>(array : inout [T], elt : T) { array.append(T); // expected-error {{cannot invoke 'append' with an argument list of type '((T).Type)'}} expected-note {{expected an argument list of type '(T)'}} } // <rdar://problem/17875634> can't append to array of tuples func test17875634() { var match: [(Int, Int)] = [] var row = 1 var col = 2 var coord = (row, col) match += (1, 2) // expected-error{{binary operator '+=' cannot be applied to operands of type '[(Int, Int)]' and '(Int, Int)'}} expected-note {{overloads for '+=' exist}} match += (row, col) // expected-error{{binary operator '+=' cannot be applied to operands of type '[(Int, Int)]' and '(Int, Int)'}} expected-note {{overloads for '+=' exist}} match += coord // expected-error{{binary operator '+=' cannot be applied to operands of type '[(Int, Int)]' and '(Int, Int)'}} expected-note {{overloads for '+=' exist}} match.append(row, col) // expected-error{{extra argument in call}} match.append(1, 2) // expected-error{{extra argument in call}} match.append(coord) match.append((1, 2)) // Make sure the behavior matches the non-generic case. struct FakeNonGenericArray { func append(_ p: (Int, Int)) {} } let a2 = FakeNonGenericArray() a2.append(row, col) // expected-error{{extra argument in call}} a2.append(1, 2) // expected-error{{extra argument in call}} a2.append(coord) a2.append((1, 2)) } // <rdar://problem/20770032> Pattern matching ranges against tuples crashes the compiler func test20770032() { if case let 1...10 = (1, 1) { // expected-warning{{'let' pattern has no effect; sub-pattern didn't bind any variables}} {{11-15=}} expected-error{{expression pattern of type 'CountableClosedRange<Int>' cannot match values of type '(Int, Int)'}} } } func tuple_splat1(_ a : Int, _ b : Int) { // expected-note {{'tuple_splat1' declared here}} let x = (1,2) tuple_splat1(x) // expected-error {{passing 2 arguments to a callee as a single tuple value has been removed in Swift 3}} tuple_splat1(1, 2) // Ok. tuple_splat1((1, 2)) // expected-error {{missing argument for parameter #2 in call}} } // This take a tuple as a value, so it isn't a tuple splat. func tuple_splat2(_ q : (a : Int, b : Int)) { let x = (1,2) tuple_splat2(x) // Ok let y = (1, b: 2) tuple_splat2(y) // Ok tuple_splat2((1, b: 2)) // Ok. tuple_splat2(1, b: 2) // expected-error {{extra argument 'b' in call}} } // SR-1612: Type comparison of foreign types is always true. func is_foreign(a: AnyObject) -> Bool { return a is CGColor // expected-warning {{'is' test is always true because 'CGColor' is a Core Foundation type}} }
apache-2.0
f0c459bf0df377ef8b365f7886696dda
39.206452
246
0.674583
3.557078
false
false
false
false
brentsimmons/Evergreen
Account/Sources/Account/ReaderAPI/ReaderAPIEntry.swift
1
3122
// // ReaderAPIArticle.swift // Account // // Created by Jeremy Beker on 5/28/19. // Copyright © 2017 Ranchero Software, LLC. All rights reserved. // import Foundation import RSParser import RSCore struct ReaderAPIEntryWrapper: Codable { let id: String let updated: Int let entries: [ReaderAPIEntry] enum CodingKeys: String, CodingKey { case id = "id" case updated = "updated" case entries = "items" } } /* { "id": "tag:google.com,2005:reader/item/00058a3b5197197b", "crawlTimeMsec": "1559362260113", "timestampUsec": "1559362260113787", "published": 1554845280, "title": "", "summary": { "content": "\n<p>Found an old screenshot of NetNewsWire 1.0 for iPhone!</p>\n\n<p><img src=\"https://nnw.ranchero.com/uploads/2019/c07c0574b1.jpg\" alt=\"Netnewswire 1.0 for iPhone screenshot showing the list of feeds.\" title=\"NewsGator got renamed to Sitrion, years later, and then renamed again as Limeade.\" border=\"0\" width=\"260\" height=\"320\"></p>\n" }, "alternate": [ { "href": "https://nnw.ranchero.com/2019/04/09/found-an-old.html" } ], "categories": [ "user/-/state/com.google/reading-list", "user/-/label/Uncategorized" ], "origin": { "streamId": "feed/130", "title": "NetNewsWire" } } */ struct ReaderAPIEntry: Codable { let articleID: String let title: String? let author: String? let publishedTimestamp: Double? let crawledTimestamp: String? let timestampUsec: String? let summary: ReaderAPIArticleSummary let alternates: [ReaderAPIAlternateLocation] let categories: [String] let origin: ReaderAPIEntryOrigin enum CodingKeys: String, CodingKey { case articleID = "id" case title = "title" case author = "author" case summary = "summary" case alternates = "alternate" case categories = "categories" case publishedTimestamp = "published" case crawledTimestamp = "crawlTimeMsec" case origin = "origin" case timestampUsec = "timestampUsec" } func parseDatePublished() -> Date? { guard let unixTime = publishedTimestamp else { return nil } return Date(timeIntervalSince1970: unixTime) } func uniqueID(variant: ReaderAPIVariant) -> String { // Should look something like "tag:google.com,2005:reader/item/00058b10ce338909" // REGEX feels heavy, I should be able to just split on / and take the last element guard let idPart = articleID.components(separatedBy: "/").last else { return articleID } guard variant != .theOldReader else { return idPart } // Convert hex representation back to integer and then a string representation guard let idNumber = Int(idPart, radix: 16) else { return articleID } return String(idNumber, radix: 10, uppercase: false) } } struct ReaderAPIArticleSummary: Codable { let content: String? enum CodingKeys: String, CodingKey { case content = "content" } } struct ReaderAPIAlternateLocation: Codable { let url: String? enum CodingKeys: String, CodingKey { case url = "href" } } struct ReaderAPIEntryOrigin: Codable { let streamId: String? let title: String? enum CodingKeys: String, CodingKey { case streamId = "streamId" case title = "title" } }
mit
068842f93c1b56352482e472f646c717
22.824427
362
0.71067
3.278361
false
false
false
false
overtake/TelegramSwift
Telegram-Mac/EBlockRowView.swift
1
6001
// // EBlockRowView.swift // Telegram-Mac // // Created by keepcoder on 08/10/2016. // Copyright © 2016 Telegram. All rights reserved. // import Cocoa import TGUIKit import SwiftSignalKit import InAppSettings private let xAdd:CGFloat = 41 private let yAdd:CGFloat = 34 private final class LineLayer : SimpleLayer { struct Key: Hashable { let value: Int let index: Int } private let content = SimpleLayer() init(emoji: NSAttributedString) { self.emoji = emoji super.init() addSublayer(content) let signal = generateEmoji(emoji) |> deliverOnMainQueue let value = cachedEmoji(emoji: emoji.string, scale: System.backingScale) content.frame = NSMakeSize(xAdd, yAdd).bounds.focus(NSMakeSize(30, 33)) content.contents = value if self.contents == nil { self.disposable = signal.start(next: { [weak self] image in self?.content.contents = image cacheEmoji(image, emoji: emoji.string, scale: System.backingScale) }) } } deinit { disposable?.dispose() } private var disposable: Disposable? let emoji: NSAttributedString required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } } class EBlockRowView: TableRowView { private var popover: NSPopover? var selectedEmoji:String = "" private let longHandle = MetaDisposable() private var useEmoji: Bool = true private let content = Control() private var lines:[LineLayer.Key : LineLayer] = [:] required init(frame frameRect: NSRect) { super.init(frame: frameRect) addSubview(content) content.set(handler: { [weak self] _ in self?.updateDown() }, for: .Down) content.set(handler: { [weak self] _ in self?.updateDragging() }, for: .MouseDragging) content.set(handler: { [weak self] _ in self?.updateUp() }, for: .Up) } private var currentDownItem: (LineLayer, NSAttributedString, Bool)? private func updateDown() { if let item = itemUnderMouse { self.currentDownItem = (item.0, item.1, true) } if let itemUnderMouse = self.currentDownItem { itemUnderMouse.0.animateScale(from: 1, to: 0.85, duration: 0.2, removeOnCompletion: false) } } private func updateDragging() { if let current = self.currentDownItem { if self.itemUnderMouse?.1 != current.1, current.2 { current.0.animateScale(from: 0.85, to: 1, duration: 0.2, removeOnCompletion: true) self.currentDownItem?.2 = false } else if !current.2, self.itemUnderMouse?.1 == current.1 { current.0.animateScale(from: 1, to: 0.85, duration: 0.2, removeOnCompletion: false) self.currentDownItem?.2 = true } } } private func updateUp() { if let itemUnderMouse = self.currentDownItem { itemUnderMouse.0.animateScale(from: 0.85, to: 1, duration: 0.2, removeOnCompletion: true) if itemUnderMouse.1 == self.itemUnderMouse?.1 { self.click() } } self.currentDownItem = nil } private var itemUnderMouse: (LineLayer, NSAttributedString)? { guard let window = self.window else { return nil } let point = self.content.convert(window.mouseLocationOutsideOfEventStream, from: nil) let firstLayer = self.lines.first(where: { layer in return NSPointInRect(point, layer.1.frame) })?.value if let firstLayer = firstLayer { return (firstLayer, firstLayer.emoji) } return nil } private func click() { if let currentDownItem = currentDownItem, let item = item as? EBlockItem { let wrect = self.content.convert(currentDownItem.0.frame, to: nil) item.selectHandler(currentDownItem.1.string, wrect) } } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func layout() { super.layout() content.frame = bounds } override func set(item:TableRowItem, animated:Bool = false) { super.set(item: item, animated: animated) guard let item = item as? EBlockItem else { return } updateLines(item: item) } func updateLines(item: EBlockItem) { var validIds: [LineLayer.Key] = [] var point: NSPoint = NSMakePoint(10, 0) var index: Int = 0 for line in item.lineAttr { for symbol in line { let id = LineLayer.Key(value: symbol.string.hashValue, index: index) let view: LineLayer if let current = self.lines[id] { view = current } else { view = LineLayer(emoji: symbol) self.lines[id] = view self.content.layer?.addSublayer(view) } let size = NSMakeSize(xAdd, yAdd) view.frame = CGRect(origin: point, size: size) point.x += xAdd validIds.append(id) index += 1 } point.y += yAdd point.x = 10 } var removeKeys: [LineLayer.Key] = [] for (key, itemLayer) in self.lines { if !validIds.contains(key) { removeKeys.append(key) itemLayer.removeFromSuperlayer() } } for key in removeKeys { self.lines.removeValue(forKey: key) } } }
gpl-2.0
53793c4fc0fd647a0419eacb35b6489f
28.126214
102
0.550833
4.494382
false
false
false
false
shaps80/Peek
Pod/Classes/Peekable/UIDevice+Peekable.swift
1
4017
/* Copyright © 23/04/2016 Shaps Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ import UIKit extension UIDevice { open override func preparePeek(with coordinator: Coordinator) { coordinator.appendDynamic(keyPaths: [ "batteryMonitoringEnabled", "proximityMonitoringEnabled" ], forModel: self, in: .states) (coordinator as? SwiftCoordinator)? .appendEnum(keyPath: "batteryState", into: UIDevice.BatteryState.self, forModel: self, group: .general) coordinator.appendDynamic(keyPaths: [ "batteryLevel", ], forModel: self, in: .general) coordinator.appendTransformed(keyPaths: ["peek_totalMemory"], valueTransformer: { value in guard let value = value as? Int64 else { return nil } let formatter = ByteCountFormatter() formatter.countStyle = .memory return formatter.string(fromByteCount: value) }, forModel: self, in: .general) coordinator.appendTransformed(keyPaths: ["peek_totalStorage"], valueTransformer: { value in guard let value = value as? Int64 else { return nil } let formatter = ByteCountFormatter() formatter.countStyle = .file return formatter.string(fromByteCount: value) }, forModel: self, in: .general) coordinator.appendTransformed(keyPaths: ["peek_usedStorage"], valueTransformer: { value in guard let value = value as? Int64 else { return nil } let formatter = ByteCountFormatter() formatter.countStyle = .file return formatter.string(fromByteCount: value) }, forModel: self, in: .general) coordinator.appendTransformed(keyPaths: ["peek_availableStorage"], valueTransformer: { value in guard let value = value as? Int64 else { return nil } let formatter = ByteCountFormatter() formatter.countStyle = .file return formatter.string(fromByteCount: value) }, forModel: self, in: .general) coordinator.appendDynamic(keyPaths: [ "name", "model", "systemVersion" ], forModel: self, in: .general) super.preparePeek(with: coordinator) } @objc private var peek_usedStorage: Int64 { return peek_totalStorage - peek_availableStorage } @objc private var peek_totalStorage: Int64 { let attributes = try? FileManager.default.attributesOfFileSystem(forPath: NSHomeDirectory()) return attributes?[.systemSize] as? Int64 ?? 0 } @objc private var peek_availableStorage: Int64 { let attributes = try? FileManager.default.attributesOfFileSystem(forPath: NSHomeDirectory()) return attributes?[.systemFreeSize] as? Int64 ?? 0 } @objc private var peek_totalMemory: Int64 { return Int64(ProcessInfo.processInfo.physicalMemory) } }
mit
7eccf86c7d55508006770d85bd66aaed
41.273684
115
0.667082
4.995025
false
false
false
false
vector-im/vector-ios
RiotSwiftUI/Modules/AnalyticsPrompt/MockAnalyticsPromptStrings.swift
1
1669
// // Copyright 2021 New Vector Ltd // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // import UIKit struct MockAnalyticsPromptStrings: AnalyticsPromptStringsProtocol { let point1: NSAttributedString let point2: NSAttributedString let shortString = NSAttributedString(string: "This is a short string.") let longString = NSAttributedString(string: "This is a very long string that will be used to test the layout over multiple lines of text to ensure everything is correct.") init() { let point1 = NSMutableAttributedString(string: "We ") point1.append(NSAttributedString(string: "don't", attributes: [.font: UIFont.boldSystemFont(ofSize: UIFont.systemFontSize)])) point1.append(NSAttributedString(string: " record or profile any account data")) self.point1 = point1 let point2 = NSMutableAttributedString(string: "We ") point2.append(NSAttributedString(string: "don't", attributes: [.font: UIFont.boldSystemFont(ofSize: UIFont.systemFontSize)])) point2.append(NSAttributedString(string: " share information with third parties")) self.point2 = point2 } }
apache-2.0
f659429ca6cdf25fec22b56446087340
44.108108
175
0.727382
4.610497
false
false
false
false
sivaganeshsg/Virtual-Tourist-iOS-App
VirtualTorist/ImageCache.swift
1
1971
// // File.swift // FavoriteActors // // Created by Jason on 1/31/15. // Copyright (c) 2015 Udacity. All rights reserved. // import UIKit class ImageCache { private var inMemoryCache = NSCache() // MARK: - Retreiving images func imageWithIdentifier(identifier: String?) -> UIImage? { // If the identifier is nil, or empty, return nil if identifier == nil || identifier! == "" { return nil } let path = pathForIdentifier(identifier!) // First try the memory cache if let image = inMemoryCache.objectForKey(path) as? UIImage { return image } // Next Try the hard drive if let data = NSData(contentsOfFile: path) { return UIImage(data: data) } return nil } // MARK: - Saving images func storeImage(image: UIImage?, withIdentifier identifier: String) { let path = pathForIdentifier(identifier) // If the image is nil, remove images from the cache if image == nil { inMemoryCache.removeObjectForKey(path) do { try NSFileManager.defaultManager().removeItemAtPath(path) } catch _ {} return } // Otherwise, keep the image in memory inMemoryCache.setObject(image!, forKey: path) // And in documents directory let data = UIImagePNGRepresentation(image!)! data.writeToFile(path, atomically: true) } // MARK: - Helper func pathForIdentifier(identifier: String) -> String { let documentsDirectoryURL: NSURL = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask).first! let fullURL = documentsDirectoryURL.URLByAppendingPathComponent(identifier) return fullURL.path! } }
apache-2.0
3897635c3af97b4fc8857214b5461f09
26.774648
145
0.576865
5.312668
false
false
false
false
Iiiggs/AsthmaBuddy
AsthmaBuddy/HealthKitAdapter.swift
1
3167
// // HealthKitAdapter.swift // AsthmaBuddy // // Created by Igor Kantor on 7/17/17. // Copyright © 2017 Igorware. All rights reserved. // import UIKit import HealthKit import MapKit // Wrap HealthKit in HealthKitAdapter class HealthKitAdapter: NSObject { static let sharedInstance = HealthKitAdapter() private let healthKitStore = HKHealthStore() override init() { // I. Authorization // let typesToShare : Set = [inhalerUsageQuantitityType] // let typesToRead : Set = [inhalerUsageQuantitityType, dobCharacteristicType, genderCharacteristicType] // // if(HKHealthStore.isHealthDataAvailable()){ // self.healthKitStore.requestAuthorization(toShare: typesToShare, read: typesToRead) {success, error in // let hkReadyNotif = Notification(name: .healthKitReady, object: nil) // NotificationCenter.default.post(hkReadyNotif) // } // } } func getDemograhics(completion: @escaping DemographicsCompletionBlock) { // II. Get Characteristics // do { // let dob = try healthKitStore.dateOfBirthComponents().date! // let gender = try healthKitStore.biologicalSex() // completion(dob, gender.biologicalSex) // } catch { // print("Error") // } } func recordUsage(withLocation location:CLLocation?){ // III. Save samples // let date = Date() // // if let location = location { // let lat = location.coordinate.latitude // let lon = location.coordinate.longitude // // // III. Save samples with location // // let coordinateString = "\(lat),\(lon)" // // let sample = HKQuantitySample( // type: inhalerUsageQuantitityType, // quantity: quantityOne, // start: date, // end: date, // metadata: [usageLocationKey:coordinateString] // ) // // healthKitStore.save(sample) { (success, error) in // print("saved one use to health kit, with location") // } // } // else { // // // III. Save samples // // let sample = HKQuantitySample( // type: inhalerUsageQuantitityType, // quantity: quantityOne, // start: date, // end: date // ) // // healthKitStore.save(sample) { (success, error) in // print("saved one use to health kit") // } // } } func getInhalerUsage(completion: @escaping InhalerUsageCompletionBlock){ // IV: Get data for chart and map // let query = HKSampleQuery( // sampleType: inhalerUsageQuantitityType, // predicate: nil, // limit: 100, // sortDescriptors: nil) { (query, samples, error) in // completion(samples as? [HKQuantitySample]) // } // // self.healthKitStore.execute(query) } }
mit
62551fdf62c16311e4ae5980dd9f33fd
29.442308
115
0.542325
4.238286
false
false
false
false
PANDA-Guide/PandaGuideApp
Carthage/Checkouts/SwiftTweaks/SwiftTweaks/TweakCollectionViewController.swift
1
8257
// // TweakCollectionViewController.swift // SwiftTweaks // // Created by Bryan Clark on 11/10/15. // Copyright © 2015 Khan Academy. All rights reserved. // import UIKit internal protocol TweakCollectionViewControllerDelegate { func tweakCollectionViewControllerDidPressDismissButton(_ tweakCollectionViewController: TweakCollectionViewController) func tweakCollectionViewController(_ tweakCollectionViewController: TweakCollectionViewController, didTapFloatingTweakGroupButtonForTweakGroup tweakGroup: TweakGroup) } /// Displays the contents of a TweakCollection in a table - each child TweakGroup gets a section, each Tweak<T> gets a cell. internal final class TweakCollectionViewController: UIViewController { fileprivate let tweakCollection: TweakCollection fileprivate let tweakStore: TweakStore fileprivate let delegate: TweakCollectionViewControllerDelegate fileprivate let tableView: UITableView = { let tableView = UITableView(frame: CGRect.zero, style: .grouped) tableView.keyboardDismissMode = .onDrag return tableView }() init(tweakCollection: TweakCollection, tweakStore: TweakStore, delegate: TweakCollectionViewControllerDelegate) { self.tweakCollection = tweakCollection self.tweakStore = tweakStore self.delegate = delegate super.init(nibName: nil, bundle: nil) title = tweakCollection.title toolbarItems = [ UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil), UIBarButtonItem(title: TweaksViewController.dismissButtonTitle, style: .done, target: self, action: #selector(self.dismissButtonTapped)) ] } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() tableView.frame = view.bounds tableView.autoresizingMask = [.flexibleWidth, .flexibleHeight] tableView.delegate = self tableView.dataSource = self tableView.register(TweakTableCell.self, forCellReuseIdentifier: TweakCollectionViewController.TweakTableViewCellIdentifer) tableView.register(TweakGroupSectionHeader.self, forHeaderFooterViewReuseIdentifier: TweakGroupSectionHeader.identifier) view.addSubview(tableView) } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) // Reload data (in case colors were changed on a divedown) tableView.reloadData() } // MARK: Events @objc private func dismissButtonTapped() { delegate.tweakCollectionViewControllerDidPressDismissButton(self) } // MARK: Table Cells fileprivate static let TweakTableViewCellIdentifer = "TweakTableViewCellIdentifer" } extension TweakCollectionViewController: UITableViewDelegate { func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let tweak = tweakAtIndexPath(indexPath) switch tweak.tweakViewDataType { case .uiColor: let colorEditVC = TweakColorEditViewController(anyTweak: tweak, tweakStore: tweakStore, delegate: self) navigationController?.pushViewController(colorEditVC, animated: true) case .boolean, .integer, .cgFloat, .double: break } } } extension TweakCollectionViewController: UITableViewDataSource { func numberOfSections(in tableView: UITableView) -> Int { return tweakCollection.tweakGroups.count } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return tweakCollection.sortedTweakGroups[section].tweaks.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let tweak = tweakAtIndexPath(indexPath) let cell = tableView.dequeueReusableCell(withIdentifier: TweakCollectionViewController.TweakTableViewCellIdentifer, for: indexPath) as! TweakTableCell cell.textLabel?.text = tweak.tweakName cell.viewData = tweakStore.currentViewDataForTweak(tweak) cell.delegate = self return cell } private static let sectionFooterHeight: CGFloat = 27 private func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat { return TweakCollectionViewController.sectionFooterHeight } private func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return TweakGroupSectionHeader.height } private func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { let headerView = tableView.dequeueReusableHeaderFooterView(withIdentifier: TweakGroupSectionHeader.identifier) as! TweakGroupSectionHeader headerView.tweakGroup = tweakCollection.sortedTweakGroups[section] headerView.delegate = self return headerView } fileprivate func tweakAtIndexPath(_ indexPath: IndexPath) -> AnyTweak { return tweakCollection.sortedTweakGroups[indexPath.section].sortedTweaks[indexPath.row] } } extension TweakCollectionViewController: TweakTableCellDelegate { func tweakCellDidChangeCurrentValue(_ tweakCell: TweakTableCell) { if let indexPath = tableView.indexPath(for: tweakCell), let viewData = tweakCell.viewData { let tweak = tweakAtIndexPath(indexPath) tweakStore.setValue(viewData, forTweak: tweak) } } } extension TweakCollectionViewController: TweakColorEditViewControllerDelegate { func tweakColorEditViewControllerDidPressDismissButton(_ tweakColorEditViewController: TweakColorEditViewController) { self.delegate.tweakCollectionViewControllerDidPressDismissButton(self) } } extension TweakCollectionViewController: TweakGroupSectionHeaderDelegate { fileprivate func tweakGroupSectionHeaderDidPressFloatingButton(_ sectionHeader: TweakGroupSectionHeader) { guard let tweakGroup = sectionHeader.tweakGroup else { return } delegate.tweakCollectionViewController(self, didTapFloatingTweakGroupButtonForTweakGroup: tweakGroup) } } private protocol TweakGroupSectionHeaderDelegate: class { func tweakGroupSectionHeaderDidPressFloatingButton(_ sectionHeader: TweakGroupSectionHeader) } /// Displays the name of a tweak group, and includes a (+) button to present the floating TweakGroup UI when tapped. fileprivate final class TweakGroupSectionHeader: UITableViewHeaderFooterView { static let identifier = "TweakGroupSectionHeader" private let floatingButton: UIButton = { let button = UIButton(type: .custom) let buttonImage = UIImage(swiftTweaksImage: .floatingPlusButton).withRenderingMode(.alwaysTemplate) button.setImage(buttonImage.imageTintedWithColor(AppTheme.Colors.controlTinted), for: UIControlState()) button.setImage(buttonImage.imageTintedWithColor(AppTheme.Colors.controlTintedPressed), for: .highlighted) return button }() private let titleLabel: UILabel = { let label = UILabel() label.textColor = AppTheme.Colors.sectionHeaderTitleColor label.font = AppTheme.Fonts.sectionHeaderTitleFont return label }() fileprivate weak var delegate: TweakGroupSectionHeaderDelegate? var tweakGroup: TweakGroup? { didSet { titleLabel.text = tweakGroup?.title } } override init(reuseIdentifier: String?) { super.init(reuseIdentifier: reuseIdentifier) floatingButton.addTarget(self, action: #selector(self.floatingButtonTapped), for: .touchUpInside) contentView.addSubview(floatingButton) contentView.addSubview(titleLabel) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } static let height: CGFloat = 38 private static let horizontalMargin: CGFloat = 12 private static let floatingButtonSize = CGSize(width: 46, height: TweakGroupSectionHeader.height) override fileprivate func layoutSubviews() { super.layoutSubviews() let floatingButtonFrame = CGRect( origin: CGPoint( x: self.contentView.bounds.maxX - TweakGroupSectionHeader.floatingButtonSize.width, y: 0 ), size: TweakGroupSectionHeader.floatingButtonSize ) floatingButton.frame = floatingButtonFrame let titleLabelFrame = CGRect( origin: CGPoint( x: TweakGroupSectionHeader.horizontalMargin, y: 0 ), size: CGSize( width: self.contentView.bounds.width - floatingButtonFrame.width - TweakGroupSectionHeader.horizontalMargin, height: TweakGroupSectionHeader.height ) ) titleLabel.frame = titleLabelFrame } @objc private func floatingButtonTapped() { delegate!.tweakGroupSectionHeaderDidPressFloatingButton(self) } }
gpl-3.0
fcea5080c165a35fd3bff6cdaf11ae86
33.689076
167
0.800145
4.581576
false
false
false
false
CalQL8ed-K-OS/SwiftProceduralLevelGeneration
Procedural/Code/Scene.swift
1
8412
// // Scene.swift // Procedural // // Created by Xavi on 3/19/15. // Copyright (c) 2015 Xavi. All rights reserved. // import SpriteKit class Scene:SKScene { private let world = SKNode() private let hud = SKNode() private let dPad = Scene.createDpad() private let map = Map() private var player = Scene.createPlayer() private let playerShadow = Scene.createShadow() private let exit = Scene.createExit() private var isExistingLevel = false private static let playerSpeed:CGFloat = 100.0 private var lastUpdateTime = NSTimeInterval(0) override init(size:CGSize) { super.init(size: size) backgroundColor = SKColor(hue: 0.5, saturation: 0.5, brightness: 0.5, alpha: 1.0) setupNodes() setupPhysics() } override func update(currentTime: NSTimeInterval) { let timeDelta:NSTimeInterval = { let time = currentTime - lastUpdateTime return time > 1 ? time : 1.0 / 60.0 }() lastUpdateTime = currentTime updatePlayer(timeDelta) updateCamera() } override func didSimulatePhysics() { player.zRotation = 0.0 playerShadow.position = CGPoint(x: player.position.x, y: player.position.y - 7.0) } // Shoutout to Nate Cook for his // [NS_OPTIONS Bitmasker Generator for Swift](http://natecook.com/blog/2014/07/swift-options-bitmask-generator/) struct CollisionType : RawOptionSetType { typealias RawValue = UInt32 private var value: RawValue = 0 init(_ value: RawValue) { self.value = value } init(rawValue value: RawValue) { self.value = value } init(nilLiteral: ()) { self.value = 0 } static var allZeros: CollisionType { return self(0) } static func fromMask(raw: RawValue) -> CollisionType { return self(raw) } var rawValue: RawValue { return self.value } static var Player: CollisionType { return CollisionType(1 << 0) } static var Wall: CollisionType { return CollisionType(1 << 1) } static var Exit: CollisionType { return CollisionType(1 << 2) } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } // MARK: SKPhysicsContactDelegate extension Scene:SKPhysicsContactDelegate { func didBeginContact(contact: SKPhysicsContact) { let firstBody:SKPhysicsBody let secondBody:SKPhysicsBody if contact.bodyA.categoryBitMask < contact.bodyB.categoryBitMask { firstBody = contact.bodyA secondBody = contact.bodyB } else { firstBody = contact.bodyB secondBody = contact.bodyA } if CollisionType.fromMask( firstBody.categoryBitMask) == CollisionType.Player && CollisionType.fromMask(secondBody.categoryBitMask) == CollisionType.Exit { resolveExit() } } } // MARK: Private private extension Scene { // MARK: Setup func setupNodes() { player.position = map.spawnPosition exit.position = map.exitPosition world.addChild(map) world.addChild(exit) world.addChild(playerShadow) world.addChild(player) hud.addChild(dPad) self.addChild(world) self.addChild(hud) } func setupPhysics() { physicsWorld.gravity = CGVector(dx: 0, dy: 0) physicsWorld.contactDelegate = self } // MARK: Update cycle func updatePlayer(timeDelta:NSTimeInterval) { let playerVelocity = isExistingLevel ? CGPoint.zeroPoint : dPad.velocity // Position player.position = CGPoint(x: player.position.x + playerVelocity.x * CGFloat(timeDelta) * Scene.playerSpeed, y: player.position.y + playerVelocity.y * CGFloat(timeDelta) * Scene.playerSpeed) if playerVelocity.x != 0.0 { player.xScale = playerVelocity.x > 0.0 ? -1.0 : 1.0 } // Animation let anim:PlayerAnimation = playerVelocity.x != 0.0 ? .Walk : .Idle let key = anim.key let action = player.actionForKey(key) if let action = action { return } else { var action = SKAction.animateWithTextures(anim.frames, timePerFrame: 5.0/60.0, resize: true, restore: false) if anim == .Walk { let stepSound = SKAction.playSoundFileNamed("step.wav", waitForCompletion: false) action = SKAction.group([action, stepSound]) } player.runAction(action, withKey: key) } } func updateCamera() { world.position = CGPoint(x: -player.position.x + frame.midX, y: -player.position.y + frame.midY) } func resolveExit() { isExistingLevel = true playerShadow.removeFromParent() let move = SKAction.moveTo(map.exitPosition, duration: 0.5) let rotate = SKAction.rotateByAngle(CGFloat(M_PI * 2), duration: 0.5) let fade = SKAction.fadeAlphaTo(0.0, duration: 0.5) let scale = SKAction.scaleXTo(0.0, y: 0.0, duration: 0.5) let sound = SKAction.playSoundFileNamed("win.wav", waitForCompletion: false) let presentNextScene = SKAction.runBlock { self.view!.presentScene(Scene(size: self.size), transition: SKTransition.doorsCloseVerticalWithDuration(0.5)) } player.runAction(SKAction.sequence([SKAction.group([move, rotate, fade, scale, sound]), presentNextScene])) } // MARK: Inner types enum PlayerAnimation { case Idle, Walk var key:String { switch self { case Idle: return "anim_idle" case Walk: return "anim_walk" } } var frames:[SKTexture] { switch self { case Idle: return Scene.idleTextures case Walk: return Scene.walkTextures } } } // MARK: Sprite creation static var spriteAtlas:SKTextureAtlas = SKTextureAtlas(named: "sprites") class func createExit() -> SKSpriteNode { let exit = SKSpriteNode(texture: self.spriteAtlas.textureNamed("exit")) exit.physicsBody = { let size = CGSize(width: exit.texture!.size().width / 2.0, height: exit.texture!.size().height / 2.0) var body = SKPhysicsBody(rectangleOfSize: size) body.categoryBitMask = CollisionType.Exit.rawValue body.collisionBitMask = 0 return body }() return exit } class func createPlayer() -> SKSpriteNode { let player = SKSpriteNode(texture: self.spriteAtlas.textureNamed("idle_0")) player.physicsBody = { let body = SKPhysicsBody(rectangleOfSize: player.texture!.size()) body.categoryBitMask = CollisionType.Player.rawValue body.contactTestBitMask = CollisionType.Exit.rawValue body.collisionBitMask = CollisionType.Wall.rawValue body.allowsRotation = false return body }() return player } class func createDpad() -> DPad { let dpad = DPad(rect: CGRect(x: 0, y: 0, width: 64, height: 64)) dpad.position = CGPoint(x: 16, y: 16) dpad.numberOfDirections = 24 dpad.deadRadius = 8 return dpad } class func createShadow() -> SKSpriteNode { let shadow = SKSpriteNode(texture: self.spriteAtlas.textureNamed("shadow")) shadow.xScale = 0.6 shadow.yScale = 0.5 shadow.alpha = 0.4 return shadow } // MARK: Animation texture array creation static let idleTextures = Scene.createIdleAnimation() static let walkTextures = Scene.createWalkAnimation() class func createIdleAnimation() -> [SKTexture] { return [self.spriteAtlas.textureNamed("idle_0")] } class func createWalkAnimation() -> [SKTexture] { return [0, 1, 2].map { self.spriteAtlas.textureNamed("walk_\($0)") } } }
mit
9e1777a98440407a5eb6946c5e5d2276
33.05668
120
0.588564
4.601751
false
false
false
false
richy486/printer-server-io
Sources/App/Models/Post.swift
1
1008
import Vapor import Fluent import Foundation final class Post: Model { var exists: Bool = false var id: Node? var content: String init(content: String) { self.id = UUID().uuidString.makeNode() self.content = content } init(node: Node, in context: Context) throws { id = try node.extract("id") content = try node.extract("content") } func makeNode(context: Context) throws -> Node { return try Node(node: [ "id": id, "content": content ]) } } extension Post { /** This will automatically fetch from database, using example here to load automatically for example. Remove on real models. */ public convenience init?(from string: String) throws { self.init(content: string) } } extension Post: Preparation { static func prepare(_ database: Database) throws { // } static func revert(_ database: Database) throws { // } }
mit
017d5c0e0b9157cabcdb920ff9ff21c2
20.913043
79
0.589286
4.363636
false
false
false
false
achimk/Cars
CarsApp/Features/Cars/List/CarsListFlow.swift
1
2511
// // CarsListFlow.swift // CarsApp // // Created by Joachim Kret on 29/07/2017. // Copyright © 2017 Joachim Kret. All rights reserved. // import Foundation import UIKit struct CarsListFlow: FlowPresentable { private let navigationService: NavigationServiceType private let listService: CarsListServiceType private let errorPresenter: ErrorPresenterType? init(navigationService: NavigationServiceType, listService: CarsListServiceType, errorPresenter: ErrorPresenterType?) { self.navigationService = navigationService self.listService = listService self.errorPresenter = errorPresenter } func present(using presenter: ViewControllerNavigationType) { let navigation = navigationService let errorPresenter = ProxyErrorPresenter(self.errorPresenter) let onAddCallback: ((@escaping (Bool) -> Void) -> Void) = { completion in let modal = ModalPresenter(parent: presenter) let stack = NavigationPresenter( parent: modal, navigationController: UINavigationController() ) let sequence = ConditionPresenter( parent: stack, onPresent: { vc in modal.present(stack.navigationController); stack.present(vc) }, onDismiss: { modal.dismiss(); stack.dismiss() } ) let payload = CarAddRoutePayload { isSuccess in sequence.dismiss() completion(isSuccess) } let location = Navigation.Route.carAdd(payload).asLocation() navigation.navigate(to: location, using: sequence) } let onSelectCallback: ((CarType) -> Void) = { car in let payload = CarDetailsRoutePayload(identity: car.asIdentityModel()) let location = Navigation.Route.carDetails(payload).asLocation() navigation.navigate(to: location, using: presenter) } let viewController = CarsListViewController( service: listService, errorPresenter: errorPresenter, onAddCallback: onAddCallback, onSelectCallback: onSelectCallback ) if errorPresenter.proxy == nil { errorPresenter.proxy = RetryErrorPresenter.create(using: viewController) } viewController.title = NSLocalizedString("List", comment: "List of cars title") presenter.present(viewController) } }
mit
d5f9cd0d9b0b2e4708c670ab2b32821d
33.383562
98
0.636255
5.409483
false
false
false
false
pixlwave/Stingtk-iOS
Source/Models/Engine.swift
1
8128
import Foundation import AVFoundation import os.log class Engine { static let shared = Engine() private let engine = AVAudioEngine() private let player = AVAudioPlayerNode() private let session = AVAudioSession.sharedInstance() var outputConfig: ChannelPair = (try? JSONDecoder().decode(ChannelPair.self, from: UserDefaults.standard.data(forKey: "outputConfig") ?? Data())) ?? .default { didSet { updateChannelMap() if let data = try? JSONEncoder().encode(outputConfig) { UserDefaults.standard.set(data, forKey: "outputConfig") } } } var playingSting: Sting? var totalTime: TimeInterval { guard let sting = playingSting else { return 0 } return sting.totalTime } var elapsedTime: TimeInterval { guard let audioFile = playingSting?.audioFile, let lastRenderTime = player.lastRenderTime, let elapsedSamples = player.playerTime(forNodeTime: lastRenderTime)?.sampleTime else { return 0 } return Double(elapsedSamples) / audioFile.processingFormat.sampleRate } var isInBackground = false { didSet { switch isInBackground { case true: if playingSting == nil { engine.stop() } case false: configureAudioSession() updateChannelMap() } } } var playbackDelegate: PlaybackDelegate? init() { configureAudioSession() configureEngine() NotificationCenter.default.addObserver(self, selector: #selector(updateChannelMap), name: AVAudioSession.routeChangeNotification, object: nil) } func configureAudioSession() { // allow music to play whilst muted with playback category // prevent app launch from killing iPod by allowing mixing do { try session.setCategory(.playback, options: .mixWithOthers) try session.setActive(true) } catch { #warning("Implement error handling") os_log("Error configuring audio session: %@", String(describing: error)) } } func configureEngine() { // get output hardware format let output = engine.outputNode let outputHWFormat = output.outputFormat(forBus: 0) // connect mixer to output let mixer = engine.mainMixerNode #warning("Only needed if using non-default output") engine.connect(mixer, to: output, format: outputHWFormat) // attach the player to the engine engine.attach(player) engine.connect(player, to: mixer, fromBus: 0, toBus: 0, format: outputHWFormat) updateChannelMap() } func ensureEngineIsRunning() -> Bool { guard !engine.isRunning else { return true } do { try engine.start() } catch { os_log("Error starting audio engine: %@", String(describing: error)) return false } return true } func audioInterfaceName() -> String { return session.currentRoute.outputs.first?.portName ?? "Audio Interface" } func outputChannelCount() -> Int { Int(engine.outputNode.outputFormat(forBus: 0).channelCount) } @objc func updateChannelMap() { guard let audioUnit = engine.outputNode.audioUnit else { return } let channelCount = outputChannelCount() // with 6 channels [-1, -1, 0, 1, -1, -1] would use channels 3 & 4 var channelMap = [Int32](repeating: -1, count: channelCount) if outputConfig.highestChannel < channelCount { channelMap[outputConfig.left] = 0 // send left channel, the left stream channelMap[outputConfig.right] = 1 // send right channel, the right stream let propSize = UInt32(channelMap.count) * UInt32(MemoryLayout<UInt32>.size) _ = AudioUnitSetProperty(audioUnit, kAudioOutputUnitProperty_ChannelMap, kAudioUnitScope_Global, 1, channelMap, propSize) } else { _ = AudioUnitSetProperty(audioUnit, kAudioOutputUnitProperty_ChannelMap, kAudioUnitScope_Global, 1, nil, 0) } if playingSting != nil { _ = ensureEngineIsRunning() } } private func prepareToPlay(_ sting: Sting) -> Bool { guard let audioFile = sting.audioFile else { return false } if player.isPlaying { player.stop() } if audioFile.processingFormat != engine.mainMixerNode.inputFormat(forBus: 0) { engine.connect(player, to: engine.mainMixerNode, fromBus: 0, toBus: 0, format: audioFile.processingFormat) } return ensureEngineIsRunning() } private func scheduleSegment(of sting: Sting, from startSample: AVAudioFramePosition, for sampleCount: AVAudioFrameCount) { guard let audioFile = sting.audioFile else { return } player.scheduleSegment(audioFile, startingFrame: startSample, frameCount: sampleCount, at: nil, completionCallbackType: .dataPlayedBack, completionHandler: stopCompletionHandler(for: sting)) } private func schedule(_ buffer: AVAudioPCMBuffer, for sting: Sting, options: AVAudioPlayerNodeBufferOptions = []) { player.scheduleBuffer(buffer, at: nil, options: options, completionCallbackType: .dataPlayedBack, completionHandler: stopCompletionHandler(for: sting)) } private func stopCompletionHandler(for sting: Sting) -> (AVAudioPlayerNodeCompletionCallbackType) -> Void { { callbackType in self.playingSting = nil self.playbackDelegate?.stingDidStopPlaying(sting) if self.isInBackground { self.engine.stop() } } } private func startPlayback(of sting: Sting) { player.play() playingSting = sting playbackDelegate?.stingDidStartPlaying(sting) } func play(_ sting: Sting) { guard prepareToPlay(sting) else { return } if sting.loops { guard let buffer = sting.buffer else { return } schedule(buffer, for: sting, options: .loops) } else { scheduleSegment(of: sting, from: sting.startSample, for: sting.sampleCount) } startPlayback(of: sting) } func stopSting() { player.stop() // delegate method is called by the player } func previewStart(of sting: Sting, for length: TimeInterval = 3) { guard let audioFile = sting.audioFile, length > 0 else { return } guard prepareToPlay(sting) else { return } let sampleCount = AVAudioFrameCount(audioFile.processingFormat.sampleRate * length) scheduleSegment(of: sting, from: sting.startSample, for: sampleCount) startPlayback(of: sting) } func previewEnd(of sting: Sting, for length: TimeInterval = 3) { guard let audioFile = sting.audioFile, length > 0 else { return } guard prepareToPlay(sting) else { return } let endSample = AVAudioFrameCount(sting.startSample) + sting.sampleCount if sting.loops { let sampleCount = AVAudioFrameCount(audioFile.processingFormat.sampleRate * length) / 2 let previewStartSample = AVAudioFramePosition(endSample - sampleCount) scheduleSegment(of: sting, from: previewStartSample, for: sampleCount) scheduleSegment(of: sting, from: sting.startSample, for: sampleCount) startPlayback(of: sting) } else { let sampleCount = AVAudioFrameCount(audioFile.processingFormat.sampleRate * length) let previewStartSample = AVAudioFramePosition(endSample - sampleCount) scheduleSegment(of: sting, from: previewStartSample, for: sampleCount) startPlayback(of: sting) } } } protocol PlaybackDelegate: AnyObject { func stingDidStartPlaying(_ sting: Sting) func stingDidStopPlaying(_ sting: Sting) }
mpl-2.0
982e97eed16a302b0a552c275441f81b
37.339623
198
0.630782
4.84675
false
true
false
false
yaslab/Harekaze-iOS
Harekaze/ViewControllers/Search/ProgramSearchResultTableViewController.swift
1
6504
/** * * ProgramSearchResultTableViewController.swift * Harekaze * Created by Yuki MIZUNO on 2016/07/23. * * Copyright (c) 2016-2017, Yuki MIZUNO * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. Neither the name of the copyright holder nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. */ import UIKit import StatefulViewController import Material import RealmSwift class ProgramSearchResultTableViewController: CommonProgramTableViewController, UITableViewDelegate, UITableViewDataSource, TextFieldDelegate { // MARK: - Private instance fileds private var dataSource: Results<Program>! // MARK: - View initialization override func viewDidLoad() { // Table self.tableView.register(UINib(nibName: "ProgramItemMaterialTableViewCell", bundle: nil), forCellReuseIdentifier: "ProgramItemCell") super.viewDidLoad() // Set empty loading view loadingView = UIView() loadingView?.backgroundColor = Material.Color.white // Set empty view message if let emptyView = emptyView as? EmptyDataView { emptyView.messageLabel.text = "Nothing matched" } // Setup initial view state setupInitialViewState() // Disable refresh control refresh.removeTarget(self, action: #selector(refreshDataSource), for: .valueChanged) refresh.removeFromSuperview() refresh = nil // Refresh data stored list startLoading() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) // Setup search bar let backButton = IconButton(image: UIImage(named: "ic_arrow_back"), tintColor: Material.Color.darkText.secondary) backButton.pulseColor = Material.Color.darkText.secondary backButton.addTarget(self, action: #selector(handleBackButton), for: .touchUpInside) let moreButton = IconButton(image: UIImage(named: "ic_more_vert"), tintColor: Material.Color.darkText.secondary) moreButton.pulseColor = Material.Color.darkText.secondary searchBarController?.statusBarStyle = .default searchBarController?.searchBar.textField.delegate = self searchBarController?.searchBar.leftViews = [backButton] searchBarController?.searchBar.rightViews = [moreButton] searchBarController?.searchBar.textField.returnKeyType = .search } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) // Close navigation drawer navigationDrawerController?.closeLeftView() navigationDrawerController?.isEnabled = false // Show keyboard when search text is empty if searchBarController?.searchBar.textField.text == "" { searchBarController?.searchBar.textField.becomeFirstResponder() } } // MARK: - View deinitialization override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) // Change status bar style searchBarController?.statusBarStyle = .lightContent // Enable navigation drawer navigationDrawerController?.isEnabled = false } // MARK: - Event handler internal func handleBackButton() { searchBarController?.searchBar.textField.resignFirstResponder() dismiss(animated: true, completion: nil) } // MARK: - Memory/resource management override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } // MARK: - Layout methods override func viewWillLayoutSubviews() { super.viewWillLayoutSubviews() // FIXME: Bad way to remove unknown 20px top margin tableView.contentInset = UIEdgeInsets.zero } // MARK: - Resource searcher internal func searchDataSource(_ text: String) { let predicate = NSPredicate(format: "title CONTAINS[c] %@", text) let realm = try! Realm() dataSource = realm.objects(Program.self).filter(predicate).sorted(byProperty: "startTime", ascending: false) notificationToken?.stop() notificationToken = dataSource.addNotificationBlock(updateNotificationBlock()) tableView.reloadData() endLoading() } // MARK: - Table view data source func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if let dataSource = dataSource { return dataSource.count } return 0 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { guard let cell = tableView.dequeueReusableCell(withIdentifier: "ProgramItemCell", for: indexPath) as? ProgramItemMaterialTableViewCell else { return UITableViewCell() } let item = dataSource[indexPath.row] cell.setCellEntities(item, navigationController: self.navigationController) return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { guard let programDetailViewController = self.storyboard!.instantiateViewController(withIdentifier: "ProgramDetailTableViewController") as? ProgramDetailTableViewController else { return } programDetailViewController.program = dataSource[indexPath.row] self.navigationController?.pushViewController(programDetailViewController, animated: true) } // MARK: - Text field func textFieldShouldReturn(_ textField: UITextField) -> Bool { if textField.text == "" { return false } searchDataSource(textField.text!) textField.resignFirstResponder() return true } }
bsd-3-clause
3fe1ada5b820b31828c27330348cdb7c
32.525773
143
0.767066
4.554622
false
false
false
false
Stealth2012/InfoBipSmsSwift
InfoBip/LoginViewController.swift
1
1818
// // LoginViewController.swift // InfoBip // // Created by Artem Shuba on 12/11/15. // Copyright © 2015 Artem Shuba. All rights reserved. // import UIKit class LoginViewController: UIViewController, UITextFieldDelegate { //MARK: fields @IBOutlet weak var loginField: UITextField! @IBOutlet weak var passwordField: UITextField! @IBOutlet weak var loginButton: UIButton! //MARK: methods override func viewDidLoad() { super.viewDidLoad() loginField.delegate = self passwordField.delegate = self } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) navigationController?.navigationBar.hidden = true } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == "mainScreenSegue" { if let viewController = segue.destinationViewController as? MainViewController { viewController.login = loginField.text viewController.password = passwordField.text } } } @IBAction func loginTextChanged(sender: UITextField) { if canLogin() { loginButton.enabled = true } else { loginButton.enabled = false } } func textFieldShouldReturn(textField: UITextField) -> Bool { //if it's a loginField then switch to password if textField == loginField { passwordField.becomeFirstResponder() } return true } private func canLogin() -> Bool { return (loginField.text != nil && !loginField.text!.isEmpty) && (passwordField.text != nil && !passwordField.text!.isEmpty) } }
mit
7bbc0b921fccfa4f447e888c81147ef7
25.333333
90
0.601541
5.297376
false
false
false
false
vmanot/swift-package-manager
Tests/BasicTests/RegExTests.swift
1
1028
/* 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 XCTest import Basic class RegExTests: XCTestCase { func testErrors() { // https://bugs.swift.org/browse/SR-5557 #if os(macOS) XCTAssertThrowsError(try RegEx(pattern: "(")) #endif } func testMatchGroups() throws { try XCTAssert(RegEx(pattern: "([a-z]+)([0-9]+)").matchGroups(in: "foo1 bar2 baz3") == [["foo", "1"], ["bar", "2"], ["baz", "3"]]) try XCTAssert(RegEx(pattern: "[0-9]+").matchGroups(in: "foo bar baz") == []) try XCTAssert(RegEx(pattern: "[0-9]+").matchGroups(in: "1") == [[]]) } static var allTests = [ ("testErrors", testErrors), ("testMatchGroups", testMatchGroups), ] }
apache-2.0
b871de526e539bc0144ffab5316c1ef3
30.151515
137
0.622568
3.765568
false
true
false
false
andykkt/BFWControls
BFWControls/Modules/Transition/View/TranslationNavigationDelegate.swift
1
3266
// // TranslationNavigationDelegate.swift // // Created by Tom Brodhurst-Hill on 7/04/2016. // Copyright © 2016 BareFeetWare. // Free to use at your own risk, with acknowledgement to BareFeetWare. // import UIKit open class TranslationNavigationDelegate: NSObject, UINavigationControllerDelegate { // MARK: - Variables @IBInspectable open var duration: TimeInterval = 0.3 @IBInspectable open var leftInset: CGFloat = 0.0 @IBInspectable open var rightInset: CGFloat = 0.0 @IBInspectable open var topInset: CGFloat = 0.0 @IBInspectable open var bottomInset: CGFloat = 0.0 @IBInspectable open var belowTopGuide: Bool = false open var direction: Direction = .left @IBInspectable open var direction_: Int { get { return direction.rawValue } set { direction = Direction(rawValue: newValue) ?? .left } } open var firstDirection: Direction? @IBInspectable open var firstDirection_: Int { get { return firstDirection?.rawValue ?? direction.rawValue } set { firstDirection = Direction(rawValue: newValue) ?? .left } } /// Fade out/in the first view controller, instead of moving. @IBInspectable open var fadeFirst: Bool = false /// Clears background of view controllers so navigation background shows through. @IBInspectable open var clearBackgrounds: Bool = false // MARK: - UINavigationControllerDelegate open func navigationController( _ navigationController: UINavigationController, animationControllerFor operation: UINavigationControllerOperation, from fromViewController: UIViewController, to toViewController: UIViewController ) -> UIViewControllerAnimatedTransitioning? { let animationController = TranslationAnimationController() animationController.leftInset = leftInset animationController.rightInset = rightInset animationController.topInset = topInset animationController.belowTopGuide = belowTopGuide animationController.bottomInset = bottomInset animationController.animatePresenter = true animationController.isPresenting = operation != .pop animationController.fadeFirst = fadeFirst let viewControllerAfterTransitionCount = navigationController.viewControllers.count - (operation == .pop ? 0 : 1) animationController.direction = viewControllerAfterTransitionCount == 1 ? (firstDirection ?? direction) : direction return animationController } open func navigationController(_ navigationController: UINavigationController, willShow viewController: UIViewController, animated: Bool) { viewController.automaticallyAdjustsScrollViewInsets = !belowTopGuide if clearBackgrounds { viewController.view.backgroundColor = .clear // TODO: Attribute if let tableViewController = viewController as? UITableViewController { tableViewController.tableView.backgroundView = nil tableViewController.tableView.backgroundColor = .clear } } } }
mit
3b365628ca16710028fe9885a2037b5b
36.528736
123
0.683308
6.057514
false
false
false
false
clwm01/RTKitDemo
RCToolsDemo/RTAnimation.swift
2
3932
// // RTAnimation.swift // RTKit // // Created by Rex Tsao on 9/4/2016. // Copyright © 2016 rexcao.net. All rights reserved. // import Foundation import UIKit class RTAnimation { class Transition { } } enum TransitionAction { case Immediately case Left case Right case Up case Down case FadeIn case FadeOut } extension UIViewController { /// Show one view controller immediately. func show(toVC: UIViewController?, fromVC: UIViewController?, completion: ((Bool) -> Void)? ) { let finalToFrame: CGRect = UIScreen.mainScreen().bounds self.transitionFromViewController(fromVC!, toViewController: toVC!, duration: 0, options: [], animations: { toVC!.view.frame = finalToFrame }, completion: completion) } /// Swipe a vc according to TransitionAction. func swipe(toVC: UIViewController, fromVC: UIViewController, direction: TransitionAction, duration: NSTimeInterval, options: UIViewAnimationOptions, completion: ((Bool) -> Void)?) { let screenBounds = UIScreen.mainScreen().bounds let finalToFrame = screenBounds var beginToFrame = CGRectOffset(finalToFrame, screenBounds.size.width, 0) var finalFromFrame = CGRectOffset(screenBounds, -screenBounds.size.width / 6, 0) switch direction { case .Right: beginToFrame = CGRectOffset(finalToFrame, -screenBounds.size.width, 0) finalFromFrame = CGRectOffset(screenBounds, screenBounds.size.width / 6, 0) break case .Up: beginToFrame = CGRectOffset(finalToFrame, 0, screenBounds.size.height) finalFromFrame = CGRectOffset(screenBounds, 0, -screenBounds.size.height / 6) break case .Down: beginToFrame = CGRectOffset(finalToFrame, 0, -screenBounds.size.height) finalFromFrame = CGRectOffset(screenBounds, 0, screenBounds.size.height / 6) break default: break } self.swiping(toVC, fromVC: fromVC, duration: duration, options: options, completion: completion, beginToFrame: beginToFrame, finalToFrame: finalToFrame, finalFromFrame: finalFromFrame) } /// Swipe a vc according to TransitionAction. /// Apple: This method adds the second view controller'€™s view to the view hierarchy and then performs the animations defined in your animations block. After the animation completes, it removes the first view controller'€™s view from the view hierarchy. /// IMPORTANT: transitionFromViewController only can be used in the solution which contains a container view controller. private func swiping(toVC: UIViewController, fromVC: UIViewController, duration: NSTimeInterval, options: UIViewAnimationOptions, completion: ((Bool) -> Void)?, beginToFrame: CGRect, finalToFrame: CGRect, finalFromFrame: CGRect ) { toVC.view.frame = beginToFrame self.transitionFromViewController(fromVC, toViewController: toVC, duration: duration, options: options, animations: { toVC.view.frame = finalToFrame fromVC.view.frame = finalFromFrame }, completion: completion) } /// Show a popView in current view controller /// /// - parameter message: Message to show. /// - parameter ticked: Auto removeself or not, set true will remove self automatically, default is true func showPop(message: String?, ticked: Bool = true) -> RTView.Pop { let popWidth = UIScreen.mainScreen().bounds.width / 2 let popHeight: CGFloat = 100 let popOrigin = RTMath.centerOrigin(UIScreen.mainScreen().bounds.size, childSize: CGSizeMake(popWidth, popHeight)) let popFrame = CGRectMake(popOrigin.x, popOrigin.y, popWidth, popHeight) let rcpop = RTView.Pop(frame: popFrame, message: message, ticked: ticked) self.view.addSubview(rcpop) return rcpop } }
mit
00c88449aea4f6ae58c183d756e83079
44.149425
258
0.686275
4.669441
false
false
false
false
KBryan/SwiftFoundation
Source/DateFormatter.swift
1
4336
// // DateFormatter.swift // SwiftFoundation // // Created by Alsey Coleman Miller on 7/4/15. // Copyright © 2015 PureSwift. All rights reserved. // /// Formats a date. public struct DateFormatter: Formatter { // MARK: - Properties public var locale: Locale? { mutating didSet { self = DateFormatter(format: format, properties: properties, locale: locale) } } public var format: String { mutating didSet { if !isUniquelyReferencedNonObjC(&self.internalFormatter) { // make copy self = DateFormatter(format: format, properties: properties, locale: locale) } // set format CFDateFormatterSetFormat(self.internalFormatter.value, format) } } public var properties: [DateFormatterProperty] { mutating didSet { if !isUniquelyReferencedNonObjC(&self.internalFormatter) { // make copy self = DateFormatter(format: format, properties: properties, locale: locale) } // set properties self.internalFormatter.value.setProperties(properties) } } // MARK: - Private Properties private var internalFormatter: InternalDateFormatter private let internalQueue = dispatch_queue_create("DateFormatter Thread Safety Internal Queue", nil) // MARK: - Initialization public init(format: String, properties: [DateFormatterProperty] = [], locale: Locale? = nil) { let formatter = CFDateFormatterRef.withStyle(.NoStyle, timeStyle: .NoStyle, locale: locale) CFDateFormatterSetFormat(formatter, format) self.properties = properties self.format = format self.locale = locale self.internalFormatter = InternalDateFormatter(value: formatter) } // MARK: - Format public func stringFromValue(value: Date) -> String { return self.internalFormatter.stringFromDate(value) } public func valueFromString(string: String) -> Date? { return self.internalFormatter.dateFromString(string) } } public enum DateFormatterProperty { //case Calendar(Calendar) // CFCalendar //case TimeZone(TimeZone) // CFTimeZone case IsLenient(Bool) case CalendarName(String) case DefaultFormat(String) case TwoDigitStartDate(Date) case DefaultDate(Date) case EraSymbols([String]) case MonthSymbols([String]) case ShortMonthSymbols([String]) case WeekdaySymbols([String]) case ShortWeekdaySymbols([String]) case AMSymbol(StringValue) case PMSymbol(StringValue) case LongEraSymbols([String]) case VeryShortMonthSymbols([String]) case StandaloneMonthSymbols([String]) case ShortStandaloneMonthSymbols([String]) case VeryShortStandaloneMonthSymbols([String]) case VeryShortWeekdaySymbols([String]) case StandaloneWeekdaySymbols([String]) case ShortStandaloneWeekdaySymbols([String]) case VeryShortStandaloneWeekdaySymbols([String]) case QuarterSymbols([String]) case ShortQuarterSymbols([String]) case StandaloneQuarterSymbols([String]) case ShortStandaloneQuarterSymbols([String]) case GregorianStartDate(Date) case DoesRelativeDateFormattingKey(Bool) } // MARK: - Internal internal final class InternalDateFormatter { let value: CFDateFormatterRef init(value: CFDateFormatterRef) { self.value = value } let internalQueue = dispatch_queue_create("DateFormatter Thread Safety Queue", nil) func stringFromDate(value: Date) -> String { var stringValue: String! dispatch_sync(self.internalQueue) { () -> Void in stringValue = self.value.stringFromDate(value) } return stringValue } func dateFromString(string: String) -> Date? { var date: Date? dispatch_sync(self.internalQueue) { () -> Void in date = self.value.dateFromString(string) } return date } }
mit
895f07375b8a52b6ca8c48d70d64f1c6
26.967742
104
0.618916
5.41875
false
false
false
false
PJayRushton/TeacherTools
TeacherTools/GroupTableViewCell.swift
1
1475
// // GroupTableViewCell.swift // TeacherTools // // Created by Parker Rushton on 10/30/16. // Copyright © 2016 AppsByPJ. All rights reserved. // import UIKit class GroupTableViewCell: UITableViewCell, AutoReuseIdentifiable { @IBOutlet weak var titleLabel: UILabel! @IBOutlet weak var subtitleLabel: UILabel! private let checkImageView = UIImageView(image: UIImage(named: "check")) private let selectedColor = App.core.state.theme.textColor.withAlphaComponent(0.2) override func awakeFromNib() { super.awakeFromNib() backgroundColor = .clear } override func setHighlighted(_ highlighted: Bool, animated: Bool) { backgroundColor = highlighted ? selectedColor : .clear } override func setSelected(_ selected: Bool, animated: Bool) { backgroundColor = selected ? selectedColor : .clear } func update(with group: Group, theme: Theme, isSelected: Bool) { titleLabel.text = group.name subtitleLabel.text = String(format: "%d students", group.studentIds.count) accessoryView = isSelected ? checkImageView : nil accessoryView?.tintColor = theme.tintColor update(with: theme) } func update(with theme: Theme) { titleLabel.font = theme.font(withSize: 24) titleLabel.textColor = theme.textColor subtitleLabel.font = theme.font(withSize: 15) subtitleLabel.textColor = theme.textColor } }
mit
da21b9be60b3dbdc80a77e0578f67ce0
30.361702
86
0.674355
4.709265
false
false
false
false
cafielo/iOS_BigNerdRanch_5th
Chap13_Homepwner_bronze_silver_gold/Homepwner/AppDelegate.swift
2
2486
// // AppDelegate.swift // Homepwner // // Created by Joonwon Lee on 7/31/16. // Copyright © 2016 Joonwon Lee. 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. let itemStore = ItemStore() // let itemsController = window!.rootViewController as! ItemsViewController let navController = window!.rootViewController as! UINavigationController let itemsController = navController.topViewController as! ItemsViewController itemsController.itemStore = itemStore return true } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
mit
476c723336175c48b0c487194c6cb73e
46.788462
285
0.750503
5.647727
false
false
false
false
eisber/tasty-imitation-keyboard
Keyboard/Catboard.swift
3
5076
// // Catboard.swift // TransliteratingKeyboard // // Created by Alexei Baboulevitch on 9/24/14. // Copyright (c) 2014 Apple. All rights reserved. // import UIKit /* This is the demo keyboard. If you're implementing your own keyboard, simply follow the example here and then set the name of your KeyboardViewController subclass in the Info.plist file. */ let kCatTypeEnabled = "kCatTypeEnabled" class Catboard: KeyboardViewController { let takeDebugScreenshot: Bool = false override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) { NSUserDefaults.standardUserDefaults().registerDefaults([kCatTypeEnabled: true]) super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) } required init(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func keyPressed(key: Key) { if let textDocumentProxy = self.textDocumentProxy as? UITextDocumentProxy { let keyOutput = key.outputForCase(self.shiftState.uppercase()) if !NSUserDefaults.standardUserDefaults().boolForKey(kCatTypeEnabled) { textDocumentProxy.insertText(keyOutput) return } if key.type == .Character || key.type == .SpecialCharacter { let context = textDocumentProxy.documentContextBeforeInput if context != nil { if count(context) < 2 { textDocumentProxy.insertText(keyOutput) return } var index = context!.endIndex index = index.predecessor() if context[index] != " " { textDocumentProxy.insertText(keyOutput) return } index = index.predecessor() if context[index] == " " { textDocumentProxy.insertText(keyOutput) return } textDocumentProxy.insertText("\(randomCat())") textDocumentProxy.insertText(" ") textDocumentProxy.insertText(keyOutput) return } else { textDocumentProxy.insertText(keyOutput) return } } else { textDocumentProxy.insertText(keyOutput) return } } } override func setupKeys() { super.setupKeys() if takeDebugScreenshot { if self.layout == nil { return } for page in keyboard.pages { for rowKeys in page.rows { for key in rowKeys { if let keyView = self.layout!.viewForKey(key) { keyView.addTarget(self, action: "takeScreenshotDelay", forControlEvents: .TouchDown) } } } } } } override func createBanner() -> ExtraView? { return CatboardBanner(globalColors: self.dynamicType.globalColors, darkMode: false, solidColorMode: self.solidColorMode()) } func takeScreenshotDelay() { var timer = NSTimer.scheduledTimerWithTimeInterval(0.1, target: self, selector: Selector("takeScreenshot"), userInfo: nil, repeats: false) } func takeScreenshot() { if !CGRectIsEmpty(self.view.bounds) { UIDevice.currentDevice().beginGeneratingDeviceOrientationNotifications() let oldViewColor = self.view.backgroundColor self.view.backgroundColor = UIColor(hue: (216/360.0), saturation: 0.05, brightness: 0.86, alpha: 1) var rect = self.view.bounds UIGraphicsBeginImageContextWithOptions(rect.size, true, 0) var context = UIGraphicsGetCurrentContext() self.view.drawViewHierarchyInRect(self.view.bounds, afterScreenUpdates: true) var capturedImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() let name = (self.interfaceOrientation.isPortrait ? "Screenshot-Portrait" : "Screenshot-Landscape") var imagePath = "/Users/archagon/Documents/Programming/OSX/RussianPhoneticKeyboard/External/tasty-imitation-keyboard/\(name).png" UIImagePNGRepresentation(capturedImage).writeToFile(imagePath, atomically: true) self.view.backgroundColor = oldViewColor } } } func randomCat() -> String { let cats = "🐱😺😸😹😽😻😿😾😼🙀" let numCats = count(cats) let randomCat = arc4random() % UInt32(numCats) let index = advance(cats.startIndex, Int(randomCat)) let character = cats[index] return String(character) }
bsd-3-clause
b1895f78a2f3b7e1f0dc5a32e50d6c01
35.302158
146
0.563218
5.619154
false
false
false
false
cmyers78/TIY-Assignments
FoodPin/FoodPin/RestaurantTableViewController.swift
1
5832
// // RestaurantTableViewController.swift // FoodPin // // Created by Simon Ng on 14/8/15. // Copyright © 2015 AppCoda. All rights reserved. // import UIKit class RestaurantTableViewController: UITableViewController { var restaurantNames = ["Cafe Deadend", "Homei", "Teakha", "Cafe Loisl", "Petite Oyster", "For Kee Restaurant", "Po's Atelier", "Bourke Street Bakery", "Haigh's Chocolate", "Palomino Espresso", "Upstate", "Traif", "Graham Avenue Meats", "Waffle & Wolf", "Five Leaves", "Cafe Lore", "Confessional", "Barrafina", "Donostia", "Royal Oak", "Thai Cafe"] var restaurantImages = ["cafedeadend.jpg", "homei.jpg", "teakha.jpg", "cafeloisl.jpg", "petiteoyster.jpg", "forkeerestaurant.jpg", "posatelier.jpg", "bourkestreetbakery.jpg", "haighschocolate.jpg", "palominoespresso.jpg", "upstate.jpg", "traif.jpg", "grahamavenuemeats.jpg", "wafflewolf.jpg", "fiveleaves.jpg", "cafelore.jpg", "confessional.jpg", "barrafina.jpg", "donostia.jpg", "royaloak.jpg", "thaicafe.jpg"] var restaurantLocations = ["Hong Kong", "Hong Kong", "Hong Kong", "Hong Kong", "Hong Kong", "Hong Kong", "Hong Kong", "Sydney", "Sydney", "Sydney", "New York", "New York", "New York", "New York", "New York", "New York", "New York", "London", "London", "London", "London"] var restaurantTypes = ["Coffee & Tea Shop", "Cafe", "Tea House", "Austrian / Causual Drink", "French", "Bakery", "Bakery", "Chocolate", "Cafe", "American / Seafood", "American", "American", "Breakfast & Brunch", "Coffee & Tea", "Coffee & Tea", "Latin American", "Spanish", "Spanish", "Spanish", "British", "Thai"] var restaurantIsVisted = [Bool](count: 21, repeatedValue: false) override func viewDidLoad() { super.viewDidLoad() // Uncomment the following line to preserve selection between presentations // self.clearsSelectionOnViewWillAppear = false // Uncomment the following line to display an Edit button in the navigation bar for this view controller. // self.navigationItem.rightBarButtonItem = self.editButtonItem() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return restaurantNames.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cellIdentifier = "Cell" let cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier, forIndexPath: indexPath) as! RestaurantTableViewCell // Configure the cell... cell.nameLabel.text = restaurantNames[indexPath.row] cell.thumbnailImageView.image = UIImage(named: restaurantImages[indexPath.row]) cell.locationLabel.text = restaurantLocations[indexPath.row] cell.typeLabel.text = restaurantTypes[indexPath.row] if restaurantIsVisted[indexPath.row] { cell.accessoryType = .Checkmark } else { cell.accessoryType = .None } return cell } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { let optionMenu = UIAlertController(title: nil, message: "What do you want to do", preferredStyle: .ActionSheet) let cancelAction = UIAlertAction(title: "Cancel", style: .Cancel, handler: nil) optionMenu.addAction(cancelAction) let callActionHandler = {(action: UIAlertAction) -> Void in let alertMessage = UIAlertController(title: "Service Unavailable", message: "Sorry. The call feature is not available yet. Please try again", preferredStyle: .Alert) alertMessage.addAction(UIAlertAction(title: "OK", style: .Default, handler: nil)) self.presentViewController(alertMessage, animated: true, completion: nil) } let callAction = UIAlertAction(title: "Call " + "123-000-\(indexPath.row)", style: UIAlertActionStyle.Default, handler: callActionHandler) optionMenu.addAction(callAction) let isVisitedAction = UIAlertAction(title: "I've been here", style: .Default, handler: { (action: UIAlertAction) -> Void in let cell = tableView.cellForRowAtIndexPath(indexPath) cell?.accessoryType = .Checkmark self.restaurantIsVisted[indexPath.row] = true }) optionMenu.addAction(isVisitedAction) let didNotVisitAction = UIAlertAction(title: "I haven't been here", style: .Default, handler: { (action: UIAlertAction) -> Void in let cell = tableView.cellForRowAtIndexPath(indexPath) cell?.accessoryType = .None self.restaurantIsVisted[indexPath.row] = false }) optionMenu.addAction(didNotVisitAction) self.presentViewController(optionMenu, animated: true, completion: nil) tableView.deselectRowAtIndexPath(indexPath, animated: false) } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
mit
400adfcee3e7f89f21c952d058a1051c
44.554688
415
0.651175
4.587726
false
false
false
false
Pluto-tv/RxSwift
RxCocoa/Common/CocoaUnits/Driver/Driver+Operators.swift
1
13369
// // Driver+Operators.swift // Rx // // Created by Krunoslav Zaher on 9/19/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // import Foundation #if !RX_NO_MODULE import RxSwift #endif extension DriverConvertibleType { /** Projects each element of an observable sequence into a new form. - parameter selector: A transform function to apply to each source element. - returns: An observable sequence whose elements are the result of invoking the transform function on each element of source. */ @warn_unused_result(message="http://git.io/rxs.uo") public func map<R>(selector: E -> R) -> Driver<R> { let source = self .asObservable() .map(selector) return Driver<R>(source) } /** Filters the elements of an observable sequence based on a predicate. - parameter predicate: A function to test each source element for a condition. - returns: An observable sequence that contains elements from the input sequence that satisfy the condition. */ @warn_unused_result(message="http://git.io/rxs.uo") public func filter(predicate: (E) -> Bool) -> Driver<E> { let source = self .asObservable() .filter(predicate) return Driver(source) } } extension DriverConvertibleType where E : DriverConvertibleType { /** Transforms an observable sequence of observable sequences into an observable sequence producing values only from the most recent observable sequence. Each time a new inner observable sequence is received, unsubscribe from the previous inner observable sequence. - returns: The observable sequence that at any point in time produces the elements of the most recent inner observable sequence that has been received. */ @warn_unused_result(message="http://git.io/rxs.uo") public func switchLatest() -> Driver<E.E> { let source: Observable<E.E> = self .asObservable() .map { $0.asDriver() } .switchLatest() return Driver<E.E>(source) } } extension DriverConvertibleType { /** Invokes an action for each event in the observable sequence, and propagates all observer messages through the result sequence. - parameter eventHandler: Action to invoke for each event in the observable sequence. - returns: The source sequence with the side-effecting behavior applied. */ @warn_unused_result(message="http://git.io/rxs.uo") public func doOn(eventHandler: (Event<E>) -> Void) -> Driver<E> { let source = self.asObservable() .doOn(eventHandler) return Driver(source) } /** Invokes an action for each event in the observable sequence, and propagates all observer messages through the result sequence. - parameter onNext: Action to invoke for each element in the observable sequence. - parameter onError: Action to invoke upon errored termination of the observable sequence. - parameter onCompleted: Action to invoke upon graceful termination of the observable sequence. - returns: The source sequence with the side-effecting behavior applied. */ @warn_unused_result(message="http://git.io/rxs.uo") public func doOn(onNext onNext: (E -> Void)? = nil, onError: (ErrorType -> Void)? = nil, onCompleted: (() -> Void)? = nil) -> Driver<E> { let source = self.asObservable() .doOn(onNext: onNext, onError: onError, onCompleted: onCompleted) return Driver(source) } } extension DriverConvertibleType { /** Prints received events for all observers on standard output. - parameter identifier: Identifier that is printed together with event description to standard output. - returns: An observable sequence whose events are printed to standard output. */ @warn_unused_result(message="http://git.io/rxs.uo") public func debug(identifier: String = "\(__FILE__):\(__LINE__)") -> Driver<E> { let source = self.asObservable() .debug(identifier) return Driver(source) } } extension DriverConvertibleType where E: Equatable { /** Returns an observable sequence that contains only distinct contiguous elements according to equality operator. - returns: An observable sequence only containing the distinct contiguous elements, based on equality operator, from the source sequence. */ @warn_unused_result(message="http://git.io/rxs.uo") public func distinctUntilChanged() -> Driver<E> { let source = self.asObservable() .distinctUntilChanged({ $0 }, comparer: { ($0 == $1) }) return Driver(source) } } extension DriverConvertibleType { /** Returns an observable sequence that contains only distinct contiguous elements according to the `keySelector`. - parameter keySelector: A function to compute the comparison key for each element. - returns: An observable sequence only containing the distinct contiguous elements, based on a computed key value, from the source sequence. */ @warn_unused_result(message="http://git.io/rxs.uo") public func distinctUntilChanged<K: Equatable>(keySelector: (E) -> K) -> Driver<E> { let source = self.asObservable() .distinctUntilChanged(keySelector, comparer: { $0 == $1 }) return Driver(source) } /** Returns an observable sequence that contains only distinct contiguous elements according to the `comparer`. - parameter comparer: Equality comparer for computed key values. - returns: An observable sequence only containing the distinct contiguous elements, based on `comparer`, from the source sequence. */ @warn_unused_result(message="http://git.io/rxs.uo") public func distinctUntilChanged(comparer: (lhs: E, rhs: E) -> Bool) -> Driver<E> { let source = self.asObservable() .distinctUntilChanged({ $0 }, comparer: comparer) return Driver(source) } /** Returns an observable sequence that contains only distinct contiguous elements according to the keySelector and the comparer. - parameter keySelector: A function to compute the comparison key for each element. - parameter comparer: Equality comparer for computed key values. - returns: An observable sequence only containing the distinct contiguous elements, based on a computed key value and the comparer, from the source sequence. */ @warn_unused_result(message="http://git.io/rxs.uo") public func distinctUntilChanged<K>(keySelector: (E) -> K, comparer: (lhs: K, rhs: K) -> Bool) -> Driver<E> { let source = self.asObservable() .distinctUntilChanged(keySelector, comparer: comparer) return Driver(source) } } extension DriverConvertibleType { /** Projects each element of an observable sequence to an observable sequence and merges the resulting observable sequences into one observable sequence. - parameter selector: A transform function to apply to each element. - returns: An observable sequence whose elements are the result of invoking the one-to-many transform function on each element of the input sequence. */ @warn_unused_result(message="http://git.io/rxs.uo") public func flatMap<R>(selector: (E) -> Driver<R>) -> Driver<R> { let source = self.asObservable() .flatMap(selector) return Driver<R>(source) } } // merge extension DriverConvertibleType where E : DriverConvertibleType { /** Merges elements from all observable sequences in the given enumerable sequence into a single observable sequence. - parameter maxConcurrent: Maximum number of inner observable sequences being subscribed to concurrently. - returns: The observable sequence that merges the elements of the observable sequences. */ @warn_unused_result(message="http://git.io/rxs.uo") public func merge() -> Driver<E.E> { let source = self.asObservable() .map { $0.asDriver() } .merge() return Driver<E.E>(source) } /** Merges elements from all inner observable sequences into a single observable sequence, limiting the number of concurrent subscriptions to inner sequences. - returns: The observable sequence that merges the elements of the inner sequences. */ @warn_unused_result(message="http://git.io/rxs.uo") public func merge(maxConcurrent maxConcurrent: Int) -> Driver<E.E> { let source = self.asObservable() .map { $0.asDriver() } .merge(maxConcurrent: maxConcurrent) return Driver<E.E>(source) } } // throttle extension DriverConvertibleType { /** Ignores elements from an observable sequence which are followed by another element within a specified relative time duration, using the specified scheduler to run throttling timers. `throttle` and `debounce` are synonyms. - parameter dueTime: Throttling duration for each element. - parameter scheduler: Scheduler to run the throttle timers and send events on. - returns: The throttled sequence. */ @warn_unused_result(message="http://git.io/rxs.uo") public func throttle<S: SchedulerType>(dueTime: S.TimeInterval, _ scheduler: S) -> Driver<E> { let source = self.asObservable() .throttle(dueTime, scheduler) return Driver(source) } /** Ignores elements from an observable sequence which are followed by another element within a specified relative time duration, using the specified scheduler to run throttling timers. `throttle` and `debounce` are synonyms. - parameter dueTime: Throttling duration for each element. - parameter scheduler: Scheduler to run the throttle timers and send events on. - returns: The throttled sequence. */ @warn_unused_result(message="http://git.io/rxs.uo") public func debounce<S: SchedulerType>(dueTime: S.TimeInterval, _ scheduler: S) -> Driver<E> { let source = self.asObservable() .debounce(dueTime, scheduler) return Driver(source) } } // scan extension DriverConvertibleType { /** Applies an accumulator function over an observable sequence and returns each intermediate result. The specified seed value is used as the initial accumulator value. For aggregation behavior with no intermediate results, see `reduce`. - parameter seed: The initial accumulator value. - parameter accumulator: An accumulator function to be invoked on each element. - returns: An observable sequence containing the accumulated values. */ @warn_unused_result(message="http://git.io/rxs.uo") public func scan<A>(seed: A, accumulator: (A, E) -> A) -> Driver<A> { let source = self.asObservable() .scan(seed, accumulator: accumulator) return Driver<A>(source) } } extension SequenceType where Generator.Element : DriverConvertibleType { /** Concatenates all observable sequences in the given sequence, as long as the previous observable sequence terminated successfully. - returns: An observable sequence that contains the elements of each given sequence, in sequential order. */ @warn_unused_result(message="http://git.io/rxs.uo") public func concat() -> Driver<Generator.Element.E> { let source: Observable<Generator.Element.E> = self.lazy.map { $0.asDriver() }.concat() return Driver<Generator.Element.E>(source) } } extension CollectionType where Generator.Element : DriverConvertibleType { /** Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences have produced an element at a corresponding index. - parameter resultSelector: Function to invoke for each series of elements at corresponding indexes in the sources. - returns: An observable sequence containing the result of combining elements of the sources using the specified result selector function. */ @warn_unused_result(message="http://git.io/rxs.uo") public func zip<R>(resultSelector: [Generator.Element.E] throws -> R) -> Driver<R> { let source: Observable<R> = self.map { $0.asDriver() }.zip(resultSelector) return Driver<R>(source) } } extension CollectionType where Generator.Element : DriverConvertibleType { /** Merges the specified observable sequences into one observable sequence by using the selector function whenever any of the observable sequences produces an element. - parameter resultSelector: Function to invoke whenever any of the sources produces an element. - returns: An observable sequence containing the result of combining elements of the sources using the specified result selector function. */ @warn_unused_result(message="http://git.io/rxs.uo") public func combineLatest<R>(resultSelector: [Generator.Element.E] throws -> R) -> Driver<R> { let source : Observable<R> = self.map { $0.asDriver() }.combineLatest(resultSelector) return Driver<R>(source) } }
mit
2838315561928b0cec10c0ec7107fb02
39.512121
197
0.684396
4.765775
false
false
false
false
Nikita2k/MDRotatingPieChart
MDRotatingPieChart/MDRotatingPieChart.swift
2
20173
// // MDRotatingPieChart.swift // MDRotatingPieChart // // Created by Maxime DAVID on 2015-04-03. // Copyright (c) 2015 Maxime DAVID. All rights reserved. // import UIKit import QuartzCore /** * DataSource : all methods are mandatory to build the pie chart */ protocol MDRotatingPieChartDataSource { /** Gets slice color :param: index slice index in your data array :returns: the color of the slice at the given index */ func colorForSliceAtIndex(index:Int) -> UIColor /** Gets slice value :param: index slice index in your data array :returns: the value of the slice at the given index */ func valueForSliceAtIndex(index:Int) -> CGFloat /** Gets slice label :param: index slice index in your data array :returns: the label of the slice at the given index */ func labelForSliceAtIndex(index:Int) -> String /** Gets number of slices :param: index slice index in your data array :returns: the number of slices */ func numberOfSlices() -> Int } /** * Delegate : all methods are optional */ @objc protocol MDRotatingPieChartDelegate { /** Triggered when a slice is going to be opened :param: index slice index in your data array */ optional func willOpenSliceAtIndex(index:Int) /** Triggered when a slice is going to be closed :param: index slice index in your data array */ optional func willCloseSliceAtIndex(index:Int) /** Triggered when a slice has just finished opening :param: index slice index in your data array */ optional func didOpenSliceAtIndex(index:Int) /** Triggered when a slice has just finished closing :param: index slice index in your data array */ optional func didCloseSliceAtIndex(index:Int) } /** * Properties, to customize your pie chart (actually this is not mandatory to use this structure since all values have a default behaviour) */ struct Properties { //smallest of both radius var smallRadius:CGFloat = 50 //biggest of both radius var bigRadius:CGFloat = 120 //value of the translation when a slice is openned var expand:CGFloat = 25 //label format in slices var displayValueTypeInSlices:DisplayValueType = .Percent //label format in center var displayValueTypeCenter:DisplayValueType = .Label //font to use in slices var fontTextInSlices:UIFont = UIFont(name: "Arial", size: 12)! //font to use in the center var fontTextCenter:UIFont = UIFont(name: "Arial", size: 10)! //tells whether or not the pie should be animated var enableAnimation = true //if so, this describes the duration of the animation var animationDuration:CFTimeInterval = 0.5 //number formatter to use var nf = NSNumberFormatter() init() { nf.groupingSize = 3 nf.maximumSignificantDigits = 3 nf.minimumSignificantDigits = 3 } } class MDRotatingPieChart: UIControl { //stores the slices var slicesArray:Array<Slice> = Array<Slice>() var delta:CGFloat = 0 //properties configuration var properties = Properties() //datasource and delegate var datasource:MDRotatingPieChartDataSource! var delegate:MDRotatingPieChartDelegate! //tells whether or not a drag action has been done, is so, do not open or close a slice var hasBeenDraged:Bool = false //saves the previous transfomation var oldTransform:CATransform3D? //saves the selected slice index var currentSelected:Int = -1 //label var labelCenter:UILabel = UILabel() //saves the center of the pie chart var pieChartCenter:CGPoint = CGPointZero //current slice translation var currentTr:CGPoint = CGPointZero override init(frame: CGRect) { super.init(frame: frame) setup() } required init(coder: NSCoder) { super.init(coder: coder) setup() } private func setup() { //saves the center (since the frame will change after some rotations) pieChartCenter.x = frame.width/2 pieChartCenter.y = frame.height/2 //builds and adds the centered label labelCenter.frame = CGRectZero labelCenter.center = CGPointMake(pieChartCenter.x, pieChartCenter.y) labelCenter.textColor = UIColor.blackColor() labelCenter.textAlignment = NSTextAlignment.Center addSubview(labelCenter) } /** Resets the pie chart */ func reset() { self.transform = CGAffineTransformMake(1, 0, 0, 1, 0, 0) labelCenter.transform = self.transform labelCenter.text = "" for currentShape in slicesArray { currentShape.shapeLayer.removeFromSuperlayer() } slicesArray.removeAll(keepCapacity: false) } /** Contructs the pie chart */ func build() { if(datasource == nil) { println("Did you forget to set your datasource ?") return } reset() var total = computeTotal() var currentStartAngle:CGFloat = 0 var angleSum:CGFloat = 0 for (var index = 0; index < datasource?.numberOfSlices(); ++index) { prepareSlice(&angleSum, currentStartAngle: &currentStartAngle, total: total, index: index) } } /** Prepares the slice and adds it to the pie chart :param: angleSum sum of already prepared slices :param: currentStartAngle start angle :param: total total value of the pie chart :param: index slice index */ func prepareSlice(inout angleSum:CGFloat, inout currentStartAngle:CGFloat, total:CGFloat, index:Int) { let currentValue = datasource.valueForSliceAtIndex(index) let currentAngle = currentValue * 2 * CGFloat(M_PI) / total let currentColor = datasource.colorForSliceAtIndex(index) let currentLabel = datasource.labelForSliceAtIndex(index) //create slice let slice = createSlice(currentStartAngle, end: CGFloat(currentStartAngle - currentAngle), color:currentColor, label:currentLabel, value:currentValue, percent:100 * currentValue/total) slicesArray.append(slice) //create label let label = createLabel(angleSum + slice.angle/2, slice: slice) //populate slicesArray slicesArray[index].labelObj = label slicesArray[index].shapeLayer.addSublayer(label.layer) angleSum += slice.angle self.layer.insertSublayer(slice.shapeLayer, atIndex:0) currentStartAngle -= currentAngle if(properties.enableAnimation) { addAnimation(slice) } } /** Retrieves the middle point of a slice (to set the label) :param: angleSum sum of already prepared slices :returns: the middle point */ func getMiddlePoint(angleSum:CGFloat) -> CGPoint { let middleRadiusX = properties.smallRadius + (properties.bigRadius-properties.smallRadius)/2 let middleRadiusY = properties.smallRadius + (properties.bigRadius-properties.smallRadius)/2 return CGPointMake( cos(angleSum) * middleRadiusX + pieChartCenter.x, sin(angleSum) * middleRadiusY + pieChartCenter.y ) } /** Creates the label :param: angleSum sum of already prepared slices :param: slice the slice :returns: a new label */ func createLabel(angleSum:CGFloat, slice:Slice) -> UILabel { let label = UILabel(frame: CGRectZero) label.center = getMiddlePoint(angleSum) label.textAlignment = NSTextAlignment.Center label.textColor = UIColor.blackColor() label.font = properties.fontTextInSlices label.text = formatFromDisplayValueType(slice, displayType: properties.displayValueTypeInSlices) let tmpCenter = label.center label.sizeToFit() label.center = tmpCenter label.hidden = !frameFitInPath(label.frame, path: slice.paths.bezierPath, inside:true) return label; } /** Adds an animation to a slice :param: slice the slice to be animated */ func addAnimation(slice:Slice) { let animateStrokeEnd = CABasicAnimation(keyPath: "strokeEnd") animateStrokeEnd.duration = properties.animationDuration animateStrokeEnd.fromValue = 0.0 animateStrokeEnd.toValue = 1.0 slice.shapeLayer.addAnimation(animateStrokeEnd, forKey: "animate stroke end animation") CATransaction.commit() } /** Computes the total value of slices :returns: the total value */ func computeTotal() -> CGFloat { var total:CGFloat = 0 for (var index=0; index < datasource.numberOfSlices(); ++index) { total = total + datasource.valueForSliceAtIndex(index) } return total; } /** Closes a slice */ func closeSlice() { delegate?.willCloseSliceAtIndex!(currentSelected) slicesArray[currentSelected].shapeLayer.transform = oldTransform! delegate?.didCloseSliceAtIndex!(currentSelected) labelCenter.text = "" } /** Opens a slice :param: index the slice index in the data array */ func openSlice(index:Int) { //save the transformation oldTransform = slicesArray[index].shapeLayer.transform //update the label labelCenter.text = formatFromDisplayValueType(slicesArray[index], displayType: properties.displayValueTypeCenter) let centerTmp = labelCenter.center labelCenter.sizeToFit() labelCenter.center = centerTmp labelCenter.hidden = false var cpt = 0; for (; cpt < datasource?.numberOfSlices(); ++cpt) { if(!frameFitInPath(labelCenter.frame, path: slicesArray[cpt].paths.bezierPath, inside:false)) { labelCenter.hidden = true break; } } //move var i=0 var angleSum:CGFloat = 0 for(i=0; i<index; ++i) { angleSum += slicesArray[i].angle } angleSum += slicesArray[index].angle/2.0 let transX:CGFloat = properties.expand*cos(angleSum) let transY:CGFloat = properties.expand*sin(angleSum) let translate = CATransform3DMakeTranslation(transX, transY, 0); currentTr = CGPointMake(-transX, -transY) delegate?.willOpenSliceAtIndex!(index) slicesArray[index].shapeLayer.transform = translate delegate?.didOpenSliceAtIndex!(index) currentSelected = index } /** Computes the logic of opening/closing slices :param: index the slice index */ func openCloseSlice(index:Int) { // nothing is opened, let's opened one slice if(currentSelected == -1) { openSlice(index) } // here a slice is opened, so let's close it before else { closeSlice() //if the same slice is chosen, no need to open if(currentSelected == index) { currentSelected = -1 } else { openSlice(index) } } } //UIControl implementation override func beginTrackingWithTouch(touch: UITouch, withEvent event: UIEvent) -> Bool { //makes sure to reset the drag event hasBeenDraged = false let currentPoint = touch.locationInView(self) if ignoreThisTap(currentPoint) { return false; } let deltaX = currentPoint.x - pieChartCenter.x let deltaY = currentPoint.y - pieChartCenter.y delta = atan2(deltaY,deltaX) return true } //UIControl implementation override func continueTrackingWithTouch(touch: UITouch, withEvent event: UIEvent) -> Bool { //drag event detected, we won't open/close any slices hasBeenDraged = true let currentPoint = touch.locationInView(self) let deltaX = currentPoint.x - pieChartCenter.x let deltaY = currentPoint.y - pieChartCenter.y let ang = atan2(deltaY,deltaX); let angleDifference = delta - ang //rotate ! self.transform = CGAffineTransformRotate(self.transform, -angleDifference) //reset labels let savedTransform = slicesArray[0].labelObj?.transform let savedTransformCenter = labelCenter.transform for slice in slicesArray { if(slice.labelObj != nil) { slice.labelObj?.transform = CGAffineTransformRotate(savedTransform!, angleDifference) } } labelCenter.transform = CGAffineTransformRotate(savedTransformCenter, angleDifference) return true; } //UIControl implementation override func endTrackingWithTouch(touch: UITouch, withEvent event: UIEvent) { //don't open/close slice if a drag event has been detected if(hasBeenDraged) { return } let currentPoint = touch.locationInView(self) var cpt = 0 for currentPath in slicesArray { //click on a slice if currentPath.paths.bezierPath.containsPoint(currentPoint) { openCloseSlice(cpt) return } //click on the current opened slice if currentPath.paths.bezierPath.containsPoint(CGPointMake(currentPoint.x+currentTr.x, currentPoint.y+currentTr.y)) && cpt == currentSelected { openCloseSlice(cpt) return } cpt++ } } /** Checks whether or not a tap shoud be dismissed (too close from the center or too far) :param: currentPoint current tapped point :returns: true if it should be ignored, false otherwise */ func ignoreThisTap(currentPoint:CGPoint) -> Bool { let dx = currentPoint.x - pieChartCenter.x let dy = currentPoint.y - pieChartCenter.y let sqroot = sqrt(dx*dx + dy*dy) return sqroot < properties.smallRadius || sqroot > (properties.bigRadius + properties.expand + (properties.bigRadius-properties.smallRadius)/2) } /** Creates a slice :param: start start angle :param: end end angle :param: color color :param: label label :param: value value :param: percent percent value :returns: a new slice */ func createSlice(start:CGFloat, end:CGFloat, color:UIColor, label:String, value:CGFloat, percent:CGFloat) -> Slice { var mask = CAShapeLayer() mask.frame = bounds let path = computeDualPath(start, end: end) mask.path = path.animationBezierPath.CGPath mask.lineWidth = properties.bigRadius - properties.smallRadius mask.strokeColor = color.CGColor mask.fillColor = color.CGColor var slice = Slice(myPaths: path, myShapeLayer: mask, myAngle: end-start, myLabel:label, myValue:value, myPercent:percent) return slice; } /** Formats the text :param: slice a slice :param: displayType an enum representing a display value type :returns: a formated text ready to be displayed */ func formatFromDisplayValueType(slice:Slice, displayType:DisplayValueType) -> String { var toRet = "" switch(displayType) { case .Value : toRet = properties.nf.stringFromNumber(slice.value)! break case .Percent : toRet = (properties.nf.stringFromNumber(slice.percent)?.stringByAppendingString("%"))! break case .Label : toRet = slice.label break default : toRet = slice.label break } return toRet; } /** Computes and returns a path representing a slice :param: start start angle :param: end end angle :returns: the UIBezierPath build */ func computeAnimationPath(start:CGFloat, end:CGFloat) -> UIBezierPath { var animationPath = UIBezierPath() animationPath.moveToPoint(getMiddlePoint(start)) animationPath.addArcWithCenter(pieChartCenter, radius: (properties.smallRadius + (properties.bigRadius-properties.smallRadius)/2), startAngle: start, endAngle: end, clockwise: false) animationPath.addArcWithCenter(pieChartCenter, radius: (properties.smallRadius + (properties.bigRadius-properties.smallRadius)/2), startAngle: end, endAngle: start, clockwise: true) return animationPath; } /** Computes and returns a pair of UIBezierPaths :param: start start angle :param: end end angle :returns: the pair */ func computeDualPath(start:CGFloat, end:CGFloat) -> DualPath { let pathRef = computeAnimationPath(start, end: end) let other = CGPathCreateCopyByStrokingPath(pathRef.CGPath, nil, properties.bigRadius-properties.smallRadius, kCGLineCapButt, kCGLineJoinMiter, 1) let ok = UIBezierPath(CGPath: other) return DualPath(myBezierPath: ok, myAnimationBezierPath: pathRef) } /** Tells whether or not the given frame is overlapping with a shape (delimited by an UIBeizerPath) :param: frame the frame :param: path the path :param: inside tells whether or not the path should be inside the path :returns: true if it fits, false otherwise */ func frameFitInPath(frame:CGRect, path:UIBezierPath, inside:Bool) -> Bool { let topLeftPoint = frame.origin let topRightPoint = CGPointMake(frame.origin.x + frame.width, frame.origin.y) let bottomLeftPoint = CGPointMake(frame.origin.x, frame.origin.y + frame.height) let bottomRightPoint = CGPointMake(frame.origin.x + frame.width, frame.origin.y + frame.height) if(inside) { if(!path.containsPoint(topLeftPoint) || !path.containsPoint(topRightPoint) || !path.containsPoint(bottomLeftPoint) || !path.containsPoint(bottomRightPoint)) { return false } } if(!inside) { if(path.containsPoint(topLeftPoint) || path.containsPoint(topRightPoint) || path.containsPoint(bottomLeftPoint) || path.containsPoint(bottomRightPoint)) { return false } } return true } } /** * Stores both BezierPaths, one for the animation and the "real one" */ struct DualPath { var bezierPath:UIBezierPath var animationBezierPath:UIBezierPath init(myBezierPath:UIBezierPath, myAnimationBezierPath:UIBezierPath) { self.bezierPath = myBezierPath self.animationBezierPath = myAnimationBezierPath } } /** * Stores a slice */ struct Slice { var paths:DualPath var shapeLayer:CAShapeLayer var angle:CGFloat var label:String var value:CGFloat var labelObj:UILabel? var percent:CGFloat init(myPaths:DualPath, myShapeLayer:CAShapeLayer, myAngle:CGFloat, myLabel:String, myValue:CGFloat, myPercent:CGFloat) { self.paths = myPaths self.shapeLayer = myShapeLayer self.angle = myAngle self.label = myLabel self.value = myValue self.percent = myPercent } } /** Helper enum to format the labels - Percent: the percent value - Value: the raw value - Label: the description */ enum DisplayValueType { case Percent case Value case Label }
mit
93f1db20f7c5853b604befa76b0826dd
29.611533
192
0.622912
4.765651
false
false
false
false
tbajis/Bop
Bop/BopMapViewController.swift
1
11928
// // BopMapViewController.swift // Bop // // Created by Thomas Manos Bajis on 4/17/17. // Copyright © 2017 Thomas Manos Bajis. All rights reserved. // import Foundation import UIKit import CoreData import MapKit import CoreLocation import Crashlytics import TwitterKit import DigitsKit // MARK: BopMapViewController: UIViewController, FoursquareRequestType, CLLocationManagerDelegate, SegueHandlerType, BopAlertViewControllerDelegate class BopMapViewController: UIViewController, FoursquareRequestType, CLLocationManagerDelegate, SegueHandlerType, BopAlertViewControllerDelegate { // MARK: Properties enum SegueIdentifier: String { case MapPinPressed } var interest = UserDefaults.standard.object(forKey: "Interest") as? String // Create an instance of CLLocationManager to track user's location let locationManager = CLLocationManager() // Create objects for user's current region and a preset New York City option var userRegion: MKCoordinateRegion? let newYorkCity = CLLocationCoordinate2D(latitude: 40.7, longitude: -74) // MARK: Outlets @IBOutlet weak var mapView: MKMapView! // MARK: Life Cycle override func viewDidLoad() { super.viewDidLoad() locationManager.delegate = self locationManager.desiredAccuracy = kCLLocationAccuracyBest locationManager.requestWhenInUseAuthorization() locationManager.startUpdatingLocation() configureUI() loadMapRegion() CoreDataObject.sharedInstance().executePinSearch() guard let pins = CoreDataObject.sharedInstance().fetchedPinResultsController.fetchedObjects as? [Pin], pins.count > 0 else { self.searchForPins(with: self.newYorkCity, searchCompletionStatus: { (success) in if success { self.setRegionFromSearch(using: self.newYorkCity) self.placePinsOnMap() } else { self.displayError(from: self, with: BopError.PinPlacement) } }) return } placePinsOnMap() } // MARK: Actions @IBAction func searchWithLocation(_ sender: UIButton) { guard let coordinate = userRegion?.center else { self.displayError(from: self, with: BopError.UserLocation) return } removePinsFromMap() { (success) in if success { self.searchForPins(with: coordinate) { (success) in if success { self.setRegionFromSearch(using: coordinate) self.placePinsOnMap() } else { self.displayError(from: self, with: BopError.PinPlacement) } } } } } @IBAction func bigAppleButtonPressed(_ sender: UIButton) { removePinsFromMap() { (success) in if success { self.searchForPins(with: self.newYorkCity) { (success) in if success { self.setRegionFromSearch(using: self.newYorkCity) self.placePinsOnMap() } else { self.displayError(from: self, with: BopError.PinPlacement) } } } } } @IBAction func refresh() { removePinsFromMap() { (success) in if success { let mapCenter = self.mapView.centerCoordinate self.searchForPins(with: mapCenter) { (success) in if success { self.setRegionFromSearch(using: mapCenter) self.placePinsOnMap() } else { self.displayError(from: self, with: BopError.PinPlacement) } } } } } @IBAction func logout(_ sender: UIBarButtonItem) { // Remove Pins from CoreData removePinsFromMap() { (success) in if success { // Remove any Twitter or Digits local session for this app. let sessionStore = Twitter.sharedInstance().sessionStore if let userId = sessionStore.session()?.userID { sessionStore.logOutUserID(userId) } Digits.sharedInstance().logOut() // Remove user information for any upcoming crashes in Crashlytics. Crashlytics.sharedInstance().setUserIdentifier(nil) Crashlytics.sharedInstance().setUserName(nil) // Log Answers Custom Event. Answers.logCustomEvent(withName: "Signed Out", customAttributes: nil) // Set Guest Login to false UserDefaults.standard.set(false, forKey: "guestLoggedIn") let appDelegate = UIApplication.shared.delegate as! AppDelegate if let _ = appDelegate.window?.rootViewController as? LoginViewController { // if Login View is window's root view, dismiss to it. Otherwise set it and dismiss to it. self.view.window?.rootViewController?.dismiss(animated: true, completion: nil) } else { let loginViewController = self.storyboard?.instantiateViewController(withIdentifier: "LoginViewController") as! LoginViewController appDelegate.window?.rootViewController = loginViewController self.view.window?.rootViewController?.dismiss(animated: true, completion: nil) } } } } // MARK: Helpers func searchForPins(with coordinate: CLLocationCoordinate2D, searchCompletionStatus: @escaping(_ success: Bool) -> Void) { getVenuesBySearch(using: interest!, latitude: coordinate.latitude, longitude: coordinate.longitude) { (success, venues, error) in performUIUpdatesOnMain { guard success else { self.displayError(from: self, with: error) return } guard let venues = venues, venues.count > 0 else { self.displayError(from: self, with: BopError.NoVenues) return } for venue in venues { let locationCoord = CLLocationCoordinate2DMake(venue.latitude!, venue.longitude!) let _ = Pin(name: venue.name, id: venue.id, latitude: locationCoord.latitude, longitude: locationCoord.longitude, address: "", checkinsCount: venue.checkinsCount!, context: AppDelegate.stack.context) AppDelegate.stack.save() } searchCompletionStatus(true) } } } private func placePinsOnMap() { CoreDataObject.sharedInstance().executePinSearch() var pinsToAdd = [Pin]() if let pins = CoreDataObject.sharedInstance().fetchedPinResultsController.fetchedObjects as? [Pin] { for pin in pins { pinsToAdd.append(pin) } } else { self.displayError(from: self, with: BopError.PinPlacement) } mapView.addAnnotations(pinsToAdd) } func removePinsFromMap(removePinCompletionStatus: @escaping(_ success: Bool) -> Void) { for annotation in mapView.annotations { mapView.removeAnnotation(annotation) } deletePinInfo(deleteCompletionStatus: removePinCompletionStatus) } func deletePinInfo(deleteCompletionStatus: @escaping(_ success: Bool) -> Void) { if let pins = CoreDataObject.sharedInstance().fetchedPinResultsController.fetchedObjects as? [Pin] { for pin in pins { AppDelegate.stack.context.delete(pin) AppDelegate.stack.save() } } deleteCompletionStatus(true) } func setRegionFromSearch(using center: CLLocationCoordinate2D) { let region = MKCoordinateRegionMakeWithDistance(center, 15000, 15000) mapView.setRegion(region, animated: true) } func loadMapRegion() { if let region = UserDefaults.standard.object(forKey: "region") as AnyObject? { let latitude = region["latitude"] as! CLLocationDegrees let longitude = region["longitude"] as! CLLocationDegrees let center = CLLocationCoordinate2D(latitude: latitude, longitude: longitude) let latDelta = region["latitudeDelta"] as! CLLocationDegrees let longDelta = region["longitudeDelta"] as! CLLocationDegrees let span = MKCoordinateSpan(latitudeDelta: latDelta, longitudeDelta: longDelta) let updatedRegion = MKCoordinateRegion(center: center, span: span) mapView.setRegion(updatedRegion, animated: true) } } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { switch segueIdentifierForSegue(segue: segue) { case .MapPinPressed: let pin = sender as! Pin let detailController = segue.destination as! BopDetailViewController detailController.pin = pin } } // MARK: Utilities func configureUI() { if let interest = interest { self.navigationItem.title = "Venues for \(interest)" } self.navigationItem.leftBarButtonItem?.setTitleTextAttributes([NSAttributedStringKey.foregroundColor:UIColor.white, NSAttributedStringKey.font:UIFont(name: "Avenir-Light", size: 15)!], for: .normal) } } // MARK: - MKMapViewDelegate extension BopMapViewController: MKMapViewDelegate { func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? { if annotation.isMember(of: MKUserLocation.self) { return nil } let reuseID = "pin" var pinView = mapView.dequeueReusableAnnotationView(withIdentifier: reuseID) as? MKPinAnnotationView if pinView == nil { pinView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: reuseID) pinView!.pinTintColor = .red pinView!.animatesDrop = true pinView?.canShowCallout = true pinView?.rightCalloutAccessoryView = UIButton(type: .detailDisclosure) } else { pinView!.annotation = annotation } return pinView } func mapView(_ mapView: MKMapView, annotationView view: MKAnnotationView, calloutAccessoryControlTapped control: UIControl) { if control == view.rightCalloutAccessoryView { let pin = view.annotation as! Pin performSegue(withIdentifier: .MapPinPressed, sender: pin) } } func mapView(_ mapView: MKMapView, regionDidChangeAnimated animated: Bool) { let persistedRegion = [ "latitude":mapView.region.center.latitude, "longitude":mapView.region.center.longitude, "latitudeDelta":mapView.region.span.latitudeDelta, "longitudeDelta":mapView.region.span.longitudeDelta ] UserDefaults.standard.set(persistedRegion, forKey: "region") } } // MARK: - CLLocationManagerDelegate extension BopMapViewController { func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { let location = locations[0] let currentRegion = MKCoordinateRegionMakeWithDistance(location.coordinate, 15000, 15000) self.userRegion = currentRegion self.mapView.showsUserLocation = true } }
apache-2.0
1945bbffe9381d4239b19963a101a05e
37.598706
219
0.602415
5.560373
false
false
false
false
Fenrikur/ef-app_ios
EurofurenceTests/Presenter Tests/Announcements/Presenter Tests/WhenBindingAnnouncement_AnnouncementsPresenterShould.swift
1
4204
@testable import Eurofurence import EurofurenceModel import XCTest class WhenBindingAnnouncement_AnnouncementsPresenterShould: XCTestCase { func testBindTheTitleOntoTheComponent() { let viewModel = FakeAnnouncementsListViewModel() let interactor = FakeAnnouncementsInteractor(viewModel: viewModel) let context = AnnouncementsPresenterTestBuilder().with(interactor).build() let randomAnnouncement = viewModel.announcements.randomElement() context.simulateSceneDidLoad() let boundComponent = context.bindAnnouncement(at: randomAnnouncement.index) XCTAssertEqual(randomAnnouncement.element.title, boundComponent.capturedTitle) } func testBindTheSubtitleOntoTheComponent() { let viewModel = FakeAnnouncementsListViewModel() let interactor = FakeAnnouncementsInteractor(viewModel: viewModel) let context = AnnouncementsPresenterTestBuilder().with(interactor).build() let randomAnnouncement = viewModel.announcements.randomElement() context.simulateSceneDidLoad() let boundComponent = context.bindAnnouncement(at: randomAnnouncement.index) XCTAssertEqual(randomAnnouncement.element.detail, boundComponent.capturedDetail) } func testBindTheAnnouncementDateTimeOntoTheComponent() { let viewModel = FakeAnnouncementsListViewModel() let interactor = FakeAnnouncementsInteractor(viewModel: viewModel) let context = AnnouncementsPresenterTestBuilder().with(interactor).build() let randomAnnouncement = viewModel.announcements.randomElement() context.simulateSceneDidLoad() let boundComponent = context.bindAnnouncement(at: randomAnnouncement.index) XCTAssertEqual(randomAnnouncement.element.receivedDateTime, boundComponent.capturedReceivedDateTime) } func testTellTheSceneToHideTheUnreadIndicatorForReadAnnouncements() { var announcement = AnnouncementComponentViewModel.random announcement.isRead = true let viewModel = FakeAnnouncementsListViewModel(announcements: [announcement]) let interactor = FakeAnnouncementsInteractor(viewModel: viewModel) let context = AnnouncementsPresenterTestBuilder().with(interactor).build() context.simulateSceneDidLoad() let boundComponent = context.bindAnnouncement(at: 0) XCTAssertTrue(boundComponent.didHideUnreadIndicator) } func testNotTellTheSceneToHideTheUnreadIndicatorForUnreadAnnouncements() { var announcement = AnnouncementComponentViewModel.random announcement.isRead = false let viewModel = FakeAnnouncementsListViewModel(announcements: [announcement]) let interactor = FakeAnnouncementsInteractor(viewModel: viewModel) let context = AnnouncementsPresenterTestBuilder().with(interactor).build() context.simulateSceneDidLoad() let boundComponent = context.bindAnnouncement(at: 0) XCTAssertFalse(boundComponent.didHideUnreadIndicator) } func testTellTheSceneToShowTheUnreadIndicatorForUnreadAnnouncements() { var announcement = AnnouncementComponentViewModel.random announcement.isRead = false let viewModel = FakeAnnouncementsListViewModel(announcements: [announcement]) let interactor = FakeAnnouncementsInteractor(viewModel: viewModel) let context = AnnouncementsPresenterTestBuilder().with(interactor).build() context.simulateSceneDidLoad() let boundComponent = context.bindAnnouncement(at: 0) XCTAssertTrue(boundComponent.didShowUnreadIndicator) } func testNotTellTheSceneToShowTheUnreadIndicatorForReadAnnouncements() { var announcement = AnnouncementComponentViewModel.random announcement.isRead = true let viewModel = FakeAnnouncementsListViewModel(announcements: [announcement]) let interactor = FakeAnnouncementsInteractor(viewModel: viewModel) let context = AnnouncementsPresenterTestBuilder().with(interactor).build() context.simulateSceneDidLoad() let boundComponent = context.bindAnnouncement(at: 0) XCTAssertFalse(boundComponent.didShowUnreadIndicator) } }
mit
dfde170a70714dc07c89fde2b5c61443
46.772727
108
0.762131
6.312312
false
true
false
false
terietor/GTForms
Source/Table Views/SelectionFormHelper.swift
1
5131
// Copyright (c) 2015-2016 Giorgos Tsiapaliokas <[email protected]> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import UIKit class SelectionFormHelper { class func toggleItems( _ formRow: FormRow, tableView: UITableView, indexPath: IndexPath ) { if let selectionForm = formRow.form as? BaseSelectionForm , !selectionForm.shouldAlwaysShowAllItems { var selectionIndexPaths = [IndexPath]() let rowIndex = (indexPath as NSIndexPath).row let sectionIndex = (indexPath as NSIndexPath).section for (index, _) in selectionForm.items.enumerated() { let targetIndexPath = IndexPath( row: rowIndex + index + 1, section: sectionIndex ) selectionIndexPaths.append(targetIndexPath) } tableView.beginUpdates() if let showItems = selectionForm.showItems , showItems { tableView.deleteRows( at: selectionIndexPaths, with: selectionForm.animation ) selectionForm.showItems = false } else { tableView.insertRows( at: selectionIndexPaths, with: selectionForm.animation ) selectionForm.showItems = true } tableView.endUpdates() } } class func handleAccessory( _ cellItems: [AnyObject], tableView: UITableView, indexPath: IndexPath ) { let cellItem = cellItems[(indexPath as NSIndexPath).row] guard let selectionItem = cellItem as? BaseSelectionFormItem else { return } let cell = tableView.cellForRow(at: indexPath) if selectionItem.selected { selectionItem.selected = false selectionItem.selectionForm?.didDeselectItem?(selectionItem) cell?.accessoryType = .none if let _ = selectionItem as? SelectionCustomizedFormItem, let cell = cell as? SelectionCustomizedFormItemCell { cell.didDeSelect() } } else { defer { selectionItem.selected = true if let selectionItem = selectionItem as? SelectionFormItem { cell?.accessoryType = selectionItem.accessoryType } else if let _ = selectionItem as? SelectionCustomizedFormItem, let cell = cell as? SelectionCustomizedFormItemCell { cell.didSelect() } selectionItem.selectionForm?.didSelectItem?(selectionItem) } if let allowsMultipleSelection = selectionItem.selectionForm? .allowsMultipleSelection , allowsMultipleSelection { return } let rowCount = tableView.numberOfRows(inSection: (indexPath as NSIndexPath).section) for index in 1...rowCount { let cellIndexPath = IndexPath( row: index - 1, section: (indexPath as NSIndexPath).section ) if let otherSelectionItem = cellItems[index - 1] as? BaseSelectionFormItem , otherSelectionItem.selectionForm === selectionItem.selectionForm { otherSelectionItem.selected = false let cell = tableView.cellForRow(at: cellIndexPath) if let _ = selectionItem as? SelectionFormItem { cell?.accessoryType = .none } else if let _ = selectionItem as? SelectionCustomizedFormItem, let cell = cell as? SelectionCustomizedFormItemCell { cell.didDeSelect() } } } } } }
mit
e12ea5bff67c10518455141708cef90c
37.871212
96
0.579614
5.663355
false
false
false
false
rudkx/swift
test/Generics/requirement_machine_diagnostics.swift
1
7119
// RUN: %target-typecheck-verify-swift -requirement-machine-protocol-signatures=on -requirement-machine-inferred-signatures=on func testInvalidConformance() { // expected-error@+1 {{type 'T' constrained to non-protocol, non-class type 'Int'}} func invalidIntConformance<T>(_: T) where T: Int {} // expected-error@+1 {{type 'T' constrained to non-protocol, non-class type 'Int'}} struct InvalidIntConformance<T: Int> {} struct S<T> { // expected-error@+2 {{type 'T' constrained to non-protocol, non-class type 'Int'}} // expected-note@+1 {{use 'T == Int' to require 'T' to be 'Int'}} func method() where T: Int {} } } // Check directly-concrete same-type constraints typealias NotAnInt = Double protocol X {} // expected-error@+1{{generic signature requires types 'NotAnInt' (aka 'Double') and 'Int' to be the same}} extension X where NotAnInt == Int {} protocol EqualComparable { func isEqual(_ other: Self) -> Bool } func badTypeConformance1<T>(_: T) where Int : EqualComparable {} // expected-error{{type 'Int' in conformance requirement does not refer to a generic parameter or associated type}} func badTypeConformance2<T>(_: T) where T.Blarg : EqualComparable { } // expected-error{{'Blarg' is not a member type of type 'T'}} func badTypeConformance3<T>(_: T) where (T) -> () : EqualComparable { } // expected-error@-1{{type '(T) -> ()' in conformance requirement does not refer to a generic parameter or associated type}} func badTypeConformance4<T>(_: T) where (inout T) throws -> () : EqualComparable { } // expected-error@-1{{type '(inout T) throws -> ()' in conformance requirement does not refer to a generic parameter or associated type}} func badTypeConformance5<T>(_: T) where T & Sequence : EqualComparable { } // expected-error@-1 {{non-protocol, non-class type 'T' cannot be used within a protocol-constrained type}} func badTypeConformance6<T>(_: T) where [T] : Collection { } // expected-warning@-1{{redundant conformance constraint '[T]' : 'Collection'}} func concreteSameTypeRedundancy<T>(_: T) where Int == Int {} // expected-warning@-1{{redundant same-type constraint 'Int' == 'Int'}} func concreteSameTypeRedundancy<T>(_: T) where Array<Int> == Array<T> {} // expected-warning@-1{{redundant same-type constraint 'Array<Int>' == 'Array<T>'}} protocol P {} struct S: P {} func concreteConformanceRedundancy<T>(_: T) where S : P {} // expected-warning@-1{{redundant conformance constraint 'S' : 'P'}} class C {} func concreteLayoutRedundancy<T>(_: T) where C : AnyObject {} // expected-warning@-1{{redundant constraint 'C' : 'AnyObject'}} func concreteLayoutConflict<T>(_: T) where Int : AnyObject {} // expected-error@-1{{type 'Int' in conformance requirement does not refer to a generic parameter or associated type}} class C2: C {} func concreteSubclassRedundancy<T>(_: T) where C2 : C {} // expected-warning@-1{{redundant superclass constraint 'C2' : 'C'}} class D {} func concreteSubclassConflict<T>(_: T) where D : C {} // expected-error@-1{{type 'D' in conformance requirement does not refer to a generic parameter or associated type}} protocol UselessProtocolWhereClause where Int == Int {} // expected-warning@-1 {{redundant same-type constraint 'Int' == 'Int'}} protocol InvalidProtocolWhereClause where Self: Int {} // expected-error@-1 {{type 'Self' constrained to non-protocol, non-class type 'Int'}} typealias Alias<T> = T where Int == Int // expected-warning@-1 {{redundant same-type constraint 'Int' == 'Int'}} func cascadingConflictingRequirement<T>(_: T) where DoesNotExist : EqualComparable { } // expected-error@-1 {{cannot find type 'DoesNotExist' in scope}} func cascadingInvalidConformance<T>(_: T) where T : DoesNotExist { } // expected-error@-1 {{cannot find type 'DoesNotExist' in scope}} func trivialRedundant1<T>(_: T) where T: P, T: P {} // expected-warning@-1 {{redundant conformance constraint 'T' : 'P'}} func trivialRedundant2<T>(_: T) where T: AnyObject, T: AnyObject {} // expected-warning@-1 {{redundant constraint 'T' : 'AnyObject'}} func trivialRedundant3<T>(_: T) where T: C, T: C {} // expected-warning@-1 {{redundant superclass constraint 'T' : 'C'}} func trivialRedundant4<T>(_: T) where T == T {} // expected-warning@-1 {{redundant same-type constraint 'T' == 'T'}} protocol TrivialRedundantConformance: P, P {} // expected-warning@-1 {{redundant conformance constraint 'Self' : 'P'}} protocol TrivialRedundantLayout: AnyObject, AnyObject {} // expected-warning@-1 {{redundant constraint 'Self' : 'AnyObject'}} // expected-error@-2 {{duplicate inheritance from 'AnyObject'}} protocol TrivialRedundantSuperclass: C, C {} // expected-warning@-1 {{redundant superclass constraint 'Self' : 'C'}} // expected-error@-2 {{duplicate inheritance from 'C'}} protocol TrivialRedundantSameType where Self == Self { // expected-warning@-1 {{redundant same-type constraint 'Self' == 'Self'}} associatedtype T where T == T // expected-warning@-1 {{redundant same-type constraint 'Self.T' == 'Self.T'}} } struct G<T> { } protocol Pair { associatedtype A associatedtype B } func test1<T: Pair>(_: T) where T.A == G<Int>, T.A == G<T.B>, T.B == Int { } // expected-warning@-1 {{redundant same-type constraint 'T.A' == 'G<T.B>'}} protocol P1 { func p1() } protocol P2 : P1 { } protocol P3 { associatedtype P3Assoc : P2 } protocol P4 { associatedtype P4Assoc : P1 } func inferSameType2<T : P3, U : P4>(_: T, _: U) where U.P4Assoc : P2, T.P3Assoc == U.P4Assoc {} // expected-warning@-1{{redundant conformance constraint 'U.P4Assoc' : 'P2'}} protocol P5 { associatedtype Element } protocol P6 { associatedtype AssocP6 : P5 } protocol P7 : P6 { associatedtype AssocP7: P6 } // expected-warning@+1{{redundant conformance constraint 'Self.AssocP6.Element' : 'P6'}} extension P7 where AssocP6.Element : P6, AssocP7.AssocP6.Element : P6, AssocP6.Element == AssocP7.AssocP6.Element { func nestedSameType1() { } } protocol P8 { associatedtype A associatedtype B } protocol P9 : P8 { associatedtype A associatedtype B } protocol P10 { associatedtype A associatedtype C } class X3 { } func sameTypeConcrete2<T : P9 & P10>(_: T) where T.B : X3, T.C == T.B, T.C == X3 { } // expected-warning@-1{{redundant superclass constraint 'T.B' : 'X3'}} // Redundant requirement warnings are suppressed for inferred requirements. protocol P11 { associatedtype X associatedtype Y associatedtype Z } func inferred1<T : Hashable>(_: Set<T>) {} func inferred2<T>(_: Set<T>) where T: Hashable {} func inferred3<T : P11>(_: T) where T.X : Hashable, T.Z == Set<T.Y>, T.X == T.Y {} func inferred4<T : P11>(_: T) where T.Z == Set<T.Y>, T.X : Hashable, T.X == T.Y {} func inferred5<T : P11>(_: T) where T.Z == Set<T.X>, T.Y : Hashable, T.X == T.Y {} func inferred6<T : P11>(_: T) where T.Y : Hashable, T.Z == Set<T.X>, T.X == T.Y {} func typeMatcherSugar<T>(_: T) where Array<Int> == Array<T>, Array<Int> == Array<T> {} // expected-warning@-1 2{{redundant same-type constraint 'Array<Int>' == 'Array<T>'}} // expected-warning@-2{{redundant same-type constraint 'T' == 'Int'}}
apache-2.0
c9c37c2937bbbbc2523003604dd79092
34.6
180
0.68577
3.493131
false
false
false
false
ahoppen/swift
test/SILGen/synthesized_conformance_enum.swift
9
8003
// RUN: %target-swift-frontend -emit-silgen %s -swift-version 4 | %FileCheck -check-prefix CHECK -check-prefix CHECK-FRAGILE %s // RUN: %target-swift-frontend -emit-silgen %s -swift-version 4 -enable-library-evolution | %FileCheck -check-prefix CHECK -check-prefix CHECK-RESILIENT %s enum Enum<T> { case a(T), b(T) } // CHECK-LABEL: enum Enum<T> { // CHECK: case a(T), b(T) // CHECK: } enum NoValues { case a, b } // CHECK-LABEL: enum NoValues { // CHECK: case a, b // CHECK-FRAGILE: @_implements(Equatable, ==(_:_:)) static func __derived_enum_equals(_ a: NoValues, _ b: NoValues) -> Bool // CHECK-RESILIENT: static func == (a: NoValues, b: NoValues) -> Bool // CHECK: func hash(into hasher: inout Hasher) // CHECK: var hashValue: Int { get } // CHECK: } // CHECK-LABEL: extension Enum : Equatable where T : Equatable { // CHECK-FRAGILE: @_implements(Equatable, ==(_:_:)) static func __derived_enum_equals(_ a: Enum<T>, _ b: Enum<T>) -> Bool // CHECK-RESILIENT: static func == (a: Enum<T>, b: Enum<T>) -> Bool // CHECK: } // CHECK-LABEL: extension Enum : Hashable where T : Hashable { // CHECK: func hash(into hasher: inout Hasher) // CHECK: var hashValue: Int { get } // CHECK: } // CHECK-LABEL: extension NoValues : CaseIterable { // CHECK: typealias AllCases = [NoValues] // CHECK: static var allCases: [NoValues] { get } // CHECK: } extension Enum: Equatable where T: Equatable {} // CHECK-FRAGILE-LABEL: // static Enum<A>.__derived_enum_equals(_:_:) // CHECK-FRAGILE-NEXT: sil hidden [ossa] @$s28synthesized_conformance_enum4EnumOAASQRzlE010__derived_C7_equalsySbACyxG_AEtFZ : $@convention(method) <T where T : Equatable> (@in_guaranteed Enum<T>, @in_guaranteed Enum<T>, @thin Enum<T>.Type) -> Bool { // CHECK-RESILIENT-LABEL: // static Enum<A>.== infix(_:_:) // CHECK-RESILIENT-NEXT: sil hidden [ossa] @$s28synthesized_conformance_enum4EnumOAASQRzlE2eeoiySbACyxG_AEtFZ : $@convention(method) <T where T : Equatable> (@in_guaranteed Enum<T>, @in_guaranteed Enum<T>, @thin Enum<T>.Type) -> Bool { extension Enum: Hashable where T: Hashable {} // CHECK-LABEL: // Enum<A>.hash(into:) // CHECK-NEXT: sil hidden [ossa] @$s28synthesized_conformance_enum4EnumOAASHRzlE4hash4intoys6HasherVz_tF : $@convention(method) <T where T : Hashable> (@inout Hasher, @in_guaranteed Enum<T>) -> () { // CHECK-LABEL: // Enum<A>.hashValue.getter // CHECK-NEXT: sil hidden [ossa] @$s28synthesized_conformance_enum4EnumOAASHRzlE9hashValueSivg : $@convention(method) <T where T : Hashable> (@in_guaranteed Enum<T>) -> Int { extension Enum: Codable where T: Codable {} // CHECK-LABEL: // Enum<A>.encode(to:) // CHECK-NEXT: sil hidden [ossa] @$s28synthesized_conformance_enum4EnumOAASeRzSERzlE6encode2toys7Encoder_p_tKF : $@convention(method) <T where T : Decodable, T : Encodable> (@in_guaranteed Encoder, @in_guaranteed Enum<T>) -> @error Error { // CHECK-LABEL: // Enum<A>.init(from:) // CHECK-NEXT: sil hidden [ossa] @$s28synthesized_conformance_enum4EnumOAASeRzSERzlE4fromACyxGs7Decoder_p_tKcfC : $@convention(method) <T where T : Decodable, T : Encodable> (@in Decoder, @thin Enum<T>.Type) -> (@out Enum<T>, @error Error) extension NoValues: CaseIterable {} // CHECK-LABEL: // static NoValues.allCases.getter // CHECK-NEXT: sil hidden [ossa] @$s28synthesized_conformance_enum8NoValuesO8allCasesSayACGvgZ : $@convention(method) (@thin NoValues.Type) -> @owned Array<NoValues> { extension NoValues: Codable {} // CHECK-LABEL: // NoValues.encode(to:) // CHECK-NEXT: sil hidden [ossa] @$s28synthesized_conformance_enum8NoValuesO6encode2toys7Encoder_p_tKF : $@convention(method) (@in_guaranteed Encoder, NoValues) -> @error Error { // CHECK-LABEL: // NoValues.init(from:) // CHECK-NEXT: sil hidden [ossa] @$s28synthesized_conformance_enum8NoValuesO4fromACs7Decoder_p_tKcfC : $@convention(method) (@in Decoder, @thin NoValues.Type) -> (NoValues, @error Error) // Witness tables for Enum // CHECK-LABEL: sil_witness_table hidden <T where T : Equatable> Enum<T>: Equatable module synthesized_conformance_enum { // CHECK-NEXT: method #Equatable."==": <Self where Self : Equatable> (Self.Type) -> (Self, Self) -> Bool : @$s28synthesized_conformance_enum4EnumOyxGSQAASQRzlSQ2eeoiySbx_xtFZTW // protocol witness for static Equatable.== infix(_:_:) in conformance <A> Enum<A> // CHECK-NEXT: conditional_conformance (T: Equatable): dependent // CHECK-NEXT: } // CHECK-LABEL: sil_witness_table hidden <T where T : Hashable> Enum<T>: Hashable module synthesized_conformance_enum { // CHECK-DAG: base_protocol Equatable: <T where T : Equatable> Enum<T>: Equatable module synthesized_conformance_enum // CHECK-DAG: method #Hashable.hashValue!getter: <Self where Self : Hashable> (Self) -> () -> Int : @$s28synthesized_conformance_enum4EnumOyxGSHAASHRzlSH9hashValueSivgTW // protocol witness for Hashable.hashValue.getter in conformance <A> Enum<A> // CHECK-DAG: method #Hashable.hash: <Self where Self : Hashable> (Self) -> (inout Hasher) -> () : @$s28synthesized_conformance_enum4EnumOyxGSHAASHRzlSH4hash4intoys6HasherVz_tFTW // protocol witness for Hashable.hash(into:) in conformance <A> Enum<A> // CHECK-DAG: method #Hashable._rawHashValue: <Self where Self : Hashable> (Self) -> (Int) -> Int : @$s28synthesized_conformance_enum4EnumOyxGSHAASHRzlSH13_rawHashValue4seedS2i_tFTW // protocol witness for Hashable._rawHashValue(seed:) in conformance <A> Enum<A> // CHECK-DAG: conditional_conformance (T: Hashable): dependent // CHECK: } // CHECK-LABEL: sil_witness_table hidden <T where T : Decodable, T : Encodable> Enum<T>: Decodable module synthesized_conformance_enum { // CHECK-NEXT: method #Decodable.init!allocator: <Self where Self : Decodable> (Self.Type) -> (Decoder) throws -> Self : @$s28synthesized_conformance_enum4EnumOyxGSeAASeRzSERzlSe4fromxs7Decoder_p_tKcfCTW // protocol witness for Decodable.init(from:) in conformance <A> Enum<A> // CHECK-NEXT: conditional_conformance (T: Decodable): dependent // CHECK-NEXT: conditional_conformance (T: Encodable): dependent // CHECK-NEXT: } // CHECK-LABEL: sil_witness_table hidden <T where T : Decodable, T : Encodable> Enum<T>: Encodable module synthesized_conformance_enum { // CHECK-NEXT: method #Encodable.encode: <Self where Self : Encodable> (Self) -> (Encoder) throws -> () : @$s28synthesized_conformance_enum4EnumOyxGSEAASeRzSERzlSE6encode2toys7Encoder_p_tKFTW // protocol witness for Encodable.encode(to:) in conformance <A> Enum<A> // CHECK-NEXT: conditional_conformance (T: Decodable): dependent // CHECK-NEXT: conditional_conformance (T: Encodable): dependent // CHECK-NEXT: } // Witness tables for NoValues // CHECK-LABEL: sil_witness_table hidden NoValues: CaseIterable module synthesized_conformance_enum { // CHECK-NEXT: associated_type_protocol (AllCases: Collection): [NoValues]: specialize <NoValues> (<Element> Array<Element>: Collection module Swift) // CHECK-NEXT: associated_type AllCases: Array<NoValues> // CHECK-NEXT: method #CaseIterable.allCases!getter: <Self where Self : CaseIterable> (Self.Type) -> () -> Self.AllCases : @$s28synthesized_conformance_enum8NoValuesOs12CaseIterableAAsADP8allCases03AllI0QzvgZTW // protocol witness for static CaseIterable.allCases.getter in conformance NoValues // CHECK-NEXT: } // CHECK-LABEL: sil_witness_table hidden NoValues: Decodable module synthesized_conformance_enum { // CHECK-NEXT: method #Decodable.init!allocator: <Self where Self : Decodable> (Self.Type) -> (Decoder) throws -> Self : @$s28synthesized_conformance_enum8NoValuesOSeAASe4fromxs7Decoder_p_tKcfCTW // protocol witness for Decodable.init(from:) in conformance NoValues // CHECK-NEXT: } // CHECK-LABEL: sil_witness_table hidden NoValues: Encodable module synthesized_conformance_enum { // CHECK-NEXT: method #Encodable.encode: <Self where Self : Encodable> (Self) -> (Encoder) throws -> () : @$s28synthesized_conformance_enum8NoValuesOSEAASE6encode2toys7Encoder_p_tKFTW // protocol witness for Encodable.encode(to:) in conformance NoValues // CHECK-NEXT: }
apache-2.0
8aac610ee08a19a427eec8145cedd0ff
72.431193
296
0.728352
3.418625
false
false
false
false
nerdishbynature/OysterKit
Common/Framework/Base/Tokenizer.swift
1
2894
/* Copyright (c) 2014, RED When Excited All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ import Foundation let __emancipateStates = true public class Tokenizer : TokenizationState { var namedStates = [String:Named]() public override init(){ super.init() } public init(states:[TokenizationState]){ super.init() branches = states } public func tokenize(string: String, newToken: (Token)->Bool) { let emancipatedTokenization = TokenizeOperation(legacyTokenizer: self) emancipatedTokenization.tokenize(string, tokenReceiver: newToken) } public func tokenize(string:String) -> [Token]{ var tokens = Array<Token>() tokenize(string, newToken: {(token:Token)->Bool in tokens.append(token) return true }) return tokens } override public class func convertFromStringLiteral(value: String) -> Tokenizer { if let parsedTokenizer = OKStandard.parseTokenizer(value) { return parsedTokenizer } return Tokenizer() } override public class func convertFromExtendedGraphemeClusterLiteral(value: String) -> Tokenizer { return Tokenizer.convertFromStringLiteral(value) } override func serialize(indentation: String) -> String { var output = "" for (name,state) in namedStates { _ = state.serialize("") output+="\(name) = \(state.rootState.description)\n" } output+="begin\n" return output+"{\n"+serializeStateArray("\t", states: branches)+"}" } }
bsd-2-clause
44009a1613786355974494c8f07aa119
31.516854
102
0.692467
4.913413
false
false
false
false
psturm-swift/FoundationTools
Sources/DateSequence.swift
1
2343
/* Copyright (c) 2016 Patrick Sturm <[email protected]> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ import Foundation public struct DateIterator: IteratorProtocol { public typealias Element = Date public init(start: Date, end: Date, matching: DateComponents, matchingPolicy: Calendar.MatchingPolicy, calendar: Calendar) { self.calendar = calendar self.matching = matching self.matchingPolicy = matchingPolicy self.end = end self.current = start } public mutating func next() -> Date? { guard let _current = self.current, _current <= end else { return nil } self.current = calendar.nextDate(after: _current, matching: matching, matchingPolicy: matchingPolicy) return _current } private let calendar: Calendar private let end: Date private let matching: DateComponents private let matchingPolicy: Calendar.MatchingPolicy private var current: Date? } public func dateSequence( start: Date, end: Date, matching: DateComponents, matchingPolicy: Calendar.MatchingPolicy = .strict, calendar: Calendar = Calendar.current) -> AnySequence<Date> { return AnySequence({ DateIterator(start: start, end: end, matching: matching, matchingPolicy: matchingPolicy, calendar: calendar) }) }
mit
bf613ec9e4dcc7ecb0b499cc40775496
38.711864
136
0.734528
4.733333
false
false
false
false
zadr/conservatory
Code/Components/Color/ColorCreation.swift
1
11165
public extension Color { enum InitializationMistake: Error { case invalidHexString } /** A convenience initializer, to create a *Color* given integral red, green, blue and alpha values. - Parameter red: The red value of a color. This parameter has a default value of **255**. - Parameter green: The red value of a color. This parameter has a default value of **255**. - Parameter blue: The red value of a color. This parameter has a default value of **255**. - Parameter alpha: The red value of a color. This parameter has a default value of **255**. `init(red: 127)`, `init(red: 12, green: 24, blue: 48)`, and `init(red: 12, green: 24, blue: 48, alpha: 96)` are all valid. */ init(red _red: UInt8 = 255, green _green: UInt8 = 255, blue _blue: UInt8 = 255, alpha _alpha: UInt8 = 255) { let red = (Double(_red) / 255.0) let green = (Double(_green) / 255.0) let blue = (Double(_blue) / 255.0) let alpha = (Double(_alpha) / 255.0) self.init(red: red, green: green, blue: blue, alpha: alpha) } /** A convenience initializer, to create a *Color* given HSB View. init(hue: 0.0 to 360.0, saturation: 0.0 to 1.0, brightness: 0.0 to 1.0, alpha: 0.0 to 1.0) The parameters specifying *hue*, *saturation*, and *brightness* are required, and do not have any default values. The parameter specifying the *alpha* has a default value of **1.0**. */ init(h _hue: Double, s _saturation: Double, b _brightness: Double, a _alpha: Double = 1.0) { var red = 0.0, green = 0.0, blue = 0.0 let c = _brightness * _saturation let x = c * (1 - (((_hue / 60.0).truncatingRemainder(dividingBy: 2.0)) - 1).absoluteValue) let m = _brightness - c switch _hue { case 0.0 ..< 60.0: red = c; green = x; blue = 0.0 case 60.0 ..< 120.0: red = x; green = c; blue = 0.0 case 120.0 ..< 180.0: red = 0; green = c; blue = x case 180.0 ..< 240.0: red = 0; green = x; blue = c case 240.0 ..< 300.0: red = x; green = 0.0; blue = c case 300.0 ... 360.0: red = c; green = 0.0; blue = x default: precondition(false, "invalid hue \(_hue)") } self.init(red: red + m, green: green + m, blue: blue + m, alpha: _alpha) } /** A convenience initializer, to create a *Color* given CMYK View. init(cyan: 0.0 to 1.0, magenta: 0.0 to 1.0, yellow: 0.0 to 1.0, key (black): 0.0 to 1.0, alpha: 0.0 to 1.0) The parameters specifying *cyan*, *magenta*, *yellow*, and *key* are required, and do not have any default values. The parameter specifying the *alpha* has a default value of **1.0**. */ init(c cyan: Double, m magenta: Double, y yellow: Double, k _key: Double, alpha: Double = 1.0) { let key = _key let red = (1.0 - cyan) * (1.0 - key) let green = (1.0 - magenta) * (1.0 - key) let blue = (1.0 - yellow) * (1.0 - key) self.init(red: red, green: green, blue: blue, alpha: alpha) } /** A convenience initializer, to create a *Color* given YUV44 View. init(Y: 0.0 to 1.0, u: 0.0 to 1.0, v: 0.0 to 1.0, alpha: 0.0 to 1.0) The parameters specifying *Y*, *u*, and *v* are required, and do not have any default values. The parameter specifying the *alpha* has a default value of **1.0**. */ init(Y _luma: Double, u _u: Double, v _v: Double, alpha: Double = 1.0) { let luma = _luma let u = _u let v = _v let r = (luma + 1.139837398373983740 * v) let g = (luma - 0.3946517043589703515 * u - 0.5805986066674976801 * v) let b = (luma + 2.032110091743119266 * u) self.init(red: r, green: g, blue: b, alpha: alpha) } /** A convenience initializer, to create a *Color* given CIE-XYZ View. init(X: 0.0 to 1.0, Y: 0.0 to 1.0, Z: 0.0 to 1.0, alpha: 0.0 to 1.0) The parameters specifying *X*, *Y*, and *Z* are required, and do not have any default values. The parameter specifying the *alpha* has a default value of **1.0**. */ init(x _mix: Double, y _luminance: Double, z _blueStimulation: Double, alpha: Double = 1.0) { let Fxyz: (Double) -> (Double) = { (t: Double) in return t <= 0.0031308 ? 12.92 * t : (1 + 0.055) * (t ** (1.0 / 2.4)) - 0.055 } let mix = _mix let luminance = _luminance let blueStimulation = _blueStimulation let red = Fxyz(mix * 3.2410 - luminance * 1.5374 - blueStimulation * 0.4986) let green = Fxyz(-mix * 0.9692 + luminance * 1.8760 - blueStimulation * 0.0416) let blue = Fxyz(mix * 0.0556 - luminance * 0.2040 + blueStimulation * 1.0570) self.init(red: red, green: green, blue: blue, alpha: alpha) } /** A convenience initializer, to create a *Color* given CIE-XYZ View. init(X: 0.0 to 1.0, Y: 0.0 to 1.0, Z: 0.0 to 1.0, alpha: 0.0 to 1.0) The parameters specifying *L*, *a*, and *b* are required, and do not have any default values. The parameter specifying the *alpha* has a default value of **1.0**. */ init(L _lightness: Double, a _a: Double, b _b: Double, alpha: Double = 1.0) { let FLab: (Double, Double) -> Double = { (t: Double, tristimulus: Double) in let delta = 6.0 / 29.0 return (t > delta) ? tristimulus * (t * t * t) : (t - 16.0 / 116.0) * 3.0 * (delta * delta) * tristimulus } let lightness = _lightness let a = _a let b = _b let fy = (lightness + 16) / 116.0 let fx = fy + (a / 500.0) let fz = fy - (b / 200.0) let x = FLab(fx, CIE.D65.X.rawValue) let y = FLab(fy, CIE.D65.Y.rawValue) let z = FLab(fz, CIE.D65.Z.rawValue) self.init(x: x, y: y, z: z, alpha: alpha) } /** A convenience initializer, to create a *Color* given a hex string. If the string is #-prefixed, the prefix will be stripped out. If the resulting string is 6 characters long, it will be treated as an RGB string. If the resulting string is 8 characters long, it will be treated as an RGBA string. Any other length string will result in nil being returned. */ init(hexString hex: String) throws { let rgb: String if hex.hasPrefix("#") { rgb = String(hex[hex.index(hex.startIndex, offsetBy: 1) ... hex.endIndex]) } else { rgb = hex } if let value = Int(rgb, radix: 16) , rgb.count == 8 { self.init(hexRGBA: value) } else if let value = Int(rgb, radix: 16) , rgb.count == 6 { self.init(hexRGB: value) } else { throw Color.InitializationMistake.invalidHexString } } /** A convenience initializer, to create a *Color* given a 32-bit integer. The 8 uppermost bits will be considered the *red* value, with the following two bits being the *green* value, and the next two bits being *blue* value. */ init(hexRGB hex: Int) { let r = UInt8((hex >> 16) & 0xFF) let g = UInt8((hex >> 8) & 0xFF) let b = UInt8(hex & 0xFF) self.init(red: r, green: g, blue: b) } /** A convenience initializer, to create a *Color* given a 32-bit integer. The 8 uppermost bits will be considered the *red* value, with the following two bits being the *green* value, and the next two bits being *blue* value. The last two bits will be considered the *alpha* value. */ init(hexRGBA hex: Int) { let r = UInt8((hex >> 24) & 0xFF) let g = UInt8((hex >> 16) & 0xFF) let b = UInt8((hex >> 8) & 0xFF) let a = UInt8(hex & 0xFF) self.init(red: r, green: g, blue: b, alpha: a) } /** Creates a color at random. - Returns: The return value is guaranteed to have an alpha of 1.0. */ static func random() -> Color { return Color(red: Double.random(in: 0.0 ..< 1.0), green: Double.random(in: 0.0 ..< 1.0), blue: Double.random(in: 0.0 ..< 1.0), alpha: 1.0) } } // MARK: - Modifying View public extension Color { // MARK: - red /** - Returns: A new color with the *red* component replaced. Values below 0.0 will be treated as 0.0, and values above 1.0 will be treated as 1.0. */ func withRed(float r: Double = 1.0) -> Color { let color = RGBView return Color(red: r, green: color.green, blue: color.blue, alpha: AView) } /** - Returns: A new color with the *red* component replaced. */ func withRed(int red: UInt8 = 255) -> Color { let r = Double(red) / 255.0 return withRed(float: r) } // MARK: - green /** - Returns: A new color with the *green* component replaced. Values below 0.0 will be treated as 0.0, and values above 1.0 will be treated as 1.0. */ func withGreen(float g: Double = 1.0) -> Color { let color = RGBView return Color(red: color.red, green: g, blue: color.blue, alpha: AView) } /** - Returns: A new color with the *green* component replaced. */ func withGreen(int green: UInt8 = 255) -> Color { let g = Double(green) / 255.0 return withGreen(float: g) } // MARK: - blue /** - Returns: A new color with the *blue* component replaced. Values below 0.0 will be treated as 0.0, and values above 1.0 will be treated as 1.0. */ func withBlue(float b: Double = 1.0) -> Color { let color = RGBView return Color(red: color.red, green: color.green, blue: b, alpha: AView) } /** - Returns: A new color with the *blue* component replaced. */ func withBlue(int blue: UInt8 = 255) -> Color { let b = Double(blue) / 255.0 return withBlue(float: b) } } // MARK: - HSB public extension Color { // MARK: - hue /** - Returns: A new color with the *hue* component replaced. */ func withHue(float hue: Double = 1.0) -> Color { let View = HSBView return Color(h: hue, s: View.saturation, b: View.brightness, a: AView) } /** - Returns: A new color with the *hue* component replaced. */ func withHue(UInt8 hue: UInt8 = 255) -> Color { let h = Double(hue) return withHue(float: h) } // MARK: - saturation /** - Returns: A new color with the *saturation* component replaced. */ func withSaturation(float saturation: Double = 1.0) -> Color { let View = HSBView return Color(h: View.hue, s: saturation, b: View.brightness, a: AView) } /** - Returns: A new color with the *saturation* component replaced. */ func withSaturation(UInt8 saturation: UInt8 = 255) -> Color { let s = Double(saturation) return withSaturation(float: s) } // MARK: - brightness /** - Returns: A new color with the *brightness* component replaced. */ func withBrightness(float brightness: Double = 1.0) -> Color { let View = HSBView return Color(h: View.hue, s: View.saturation, b: brightness, a: AView) } /** - Returns: A new color with the *brightness* component replaced. */ func withBrightness(UInt8 hue: UInt8 = 255) -> Color { let b = Double(hue) return withBrightness(float: b) } } // MARK: - W public extension Color { // MARK: - alpha func withWhite(float white: Double = 1.0) -> Color { return Color(red: white, green: white, blue: white, alpha: AView) } func withWhite(int white: UInt8 = 255) -> Color { let w = Double(white) / 255.0 return withWhite(float: w) } } // MARK: - A public extension Color { // MARK: - alpha /** - Returns: A new color with the *alpha* component replaced. Values below 0.0 will be treated as 0.0, and values above 1.0 will be treated as 1.0. */ func withAlpha(float alpha: Double = 1.0) -> Color { let View = RGBView return Color(red: View.red, green: View.green, blue: View.blue, alpha: alpha) } /** - Returns: A new color with the *alpha* component replaced. */ func withAlpha(int alpha: UInt8 = 255) -> Color { let a = Double(alpha) / 255.0 return withAlpha(float: a) } }
bsd-2-clause
8dc2e8ea09571048a2d6abc60944afc7
28.773333
229
0.639409
2.826582
false
false
false
false
4x10m/Pulley
PulleyLib/PulleyViewController+Nested.swift
1
1905
// // PulleyViewController+Nested.swift // Pulley // // Created by Ethan Gill on 8/1/17. // import Foundation extension PulleyViewController: PulleyDrawerViewControllerDelegate { public func collapsedDrawerHeight() -> CGFloat { if let drawerVCCompliant = drawerContentViewController as? PulleyDrawerViewControllerDelegate { return drawerVCCompliant.collapsedDrawerHeight() } else { return 68.0 } } public func partialRevealDrawerHeight() -> CGFloat { if let drawerVCCompliant = drawerContentViewController as? PulleyDrawerViewControllerDelegate { return drawerVCCompliant.partialRevealDrawerHeight() } else { return 264.0 } } public func supportedDrawerPositions() -> [PulleyPosition] { if let drawerVCCompliant = drawerContentViewController as? PulleyDrawerViewControllerDelegate { return drawerVCCompliant.supportedDrawerPositions() } else { return PulleyPosition.all } } public func drawerPositionDidChange(drawer: PulleyViewController) { if let drawerVCCompliant = drawerContentViewController as? PulleyDrawerViewControllerDelegate { drawerVCCompliant.drawerPositionDidChange?(drawer: drawer) } } public func makeUIAdjustmentsForFullscreen(progress: CGFloat) { if let drawerVCCompliant = drawerContentViewController as? PulleyDrawerViewControllerDelegate { drawerVCCompliant.makeUIAdjustmentsForFullscreen?(progress: progress) } } public func drawerChangedDistanceFromBottom(drawer: PulleyViewController, distance: CGFloat) { if let drawerVCCompliant = drawerContentViewController as? PulleyDrawerViewControllerDelegate { drawerVCCompliant.drawerChangedDistanceFromBottom?(drawer: drawer, distance: distance) } } }
mit
e7bc8974617b037797571873a4b998e0
35.634615
103
0.712861
5.120968
false
false
false
false
Khan/swiftz
swiftz/IxState.swift
2
2344
// // IxState.swift // swiftz // // Created by Alexander Ronald Altman on 6/11/14. // Copyright (c) 2014 Maxwell Swadling. All rights reserved. // import Foundation import swiftz_core public struct IxState<I, O, A> { let run: I -> (A, O) public init(_ run: I -> (A, O)) { self.run = run } public func eval(s: I) -> A { return run(s).0 } public func exec(s: I) -> O { return run(s).1 } public func map<B>(f: A -> B) -> IxState<I, O, B> { return f <^> self } public func contramap<H>(f: H -> I) -> IxState<H, O, A> { return f <!> self } public func imap<P>(f: O -> P) -> IxState<I, P, A> { return f <^^> self } // public func ap<E, B>(f: IxState<E, I, A -> B>) -> IxState<E, O, B> { // return f <*> self // } public func flatMap<E, B>(f: A -> IxState<O, E, B>) -> IxState<I, E, B> { return self >>- f } } public func pure<I, A>(x: A) -> IxState<I, I, A> { return IxState { (x, $0) } } public func <^><I, O, A, B>(f: A -> B, a: IxState<I, O, A>) -> IxState<I, O, B> { return IxState { s1 in let (x, s2) = a.run(s1) return (f(x), s2) } } public func <!><H, I, O, A>(f: H -> I, a: IxState<I, O, A>) -> IxState<H, O, A> { return IxState { a.run(f($0)) } } public func <^^><I, O, P, A>(f: O -> P, a: IxState<I, O, A>) -> IxState<I, P, A> { return IxState { s1 in let (x, s2) = a.run(s1) return (x, f(s2)) } } //public func <*><I, J, O, A, B>(f: IxState<I, J, A -> B>, a: IxState<J, O, A>) -> IxState<I, O, B> { // return IxState { s1 in // let (g, s2) = f.run(s1) // let (x, s3) = a.run(s2) // return (g(x), s3) // } //} public func >>-<I, J, O, A, B>(a: IxState<I, J, A>, f: A -> IxState<J, O, B>) -> IxState<I, O, B> { return IxState { s1 in let (x, s2) = a.run(s1) return f(x).run(s2) } } public func join<I, J, O, A>(a: IxState<I, J, IxState<J, O, A>>) -> IxState<I, O, A> { return IxState { s1 in let (b, s2) = a.run(s1) return b.run(s2) } } public func get<I>() -> IxState<I, I, I> { return IxState { ($0, $0) } } public func gets<I, A>(f: I -> A) -> IxState<I, I, A> { return IxState { (f($0), $0) } } public func put<I, O>(s: O) -> IxState<I, O, ()> { return IxState { _ in ((), s) } } public func modify<I, O>(f: I -> O) -> IxState<I, O, ()> { return IxState { ((), f($0)) } }
bsd-3-clause
b66fc47f0f28e279b8b14641d4b9e125
21.113208
101
0.49872
2.282376
false
false
false
false
mrackwitz/Commandant
Commandant/Command.swift
1
4202
// // Command.swift // Commandant // // Created by Justin Spahr-Summers on 2014-10-10. // Copyright (c) 2014 Carthage. All rights reserved. // import Foundation import Result /// Represents a subcommand that can be executed with its own set of arguments. public protocol CommandType { typealias ClientError /// The action that users should specify to use this subcommand (e.g., /// `help`). var verb: String { get } /// A human-readable, high-level description of what this command is used /// for. var function: String { get } /// Runs this subcommand in the given mode. func run(mode: CommandMode) -> Result<(), CommandantError<ClientError>> } /// A type-erased CommandType. public struct CommandOf<ClientError>: CommandType { public let verb: String public let function: String private let runClosure: CommandMode -> Result<(), CommandantError<ClientError>> /// Creates a command that wraps another. public init<C: CommandType where C.ClientError == ClientError>(_ command: C) { verb = command.verb function = command.function runClosure = { mode in command.run(mode) } } public func run(mode: CommandMode) -> Result<(), CommandantError<ClientError>> { return runClosure(mode) } } /// Describes the "mode" in which a command should run. public enum CommandMode { /// Options should be parsed from the given command-line arguments. case Arguments(ArgumentParser) /// Each option should record its usage information in an error, for /// presentation to the user. case Usage } /// Maintains the list of commands available to run. public final class CommandRegistry<ClientError> { private var commandsByVerb: [String: CommandOf<ClientError>] = [:] /// All available commands. public var commands: [CommandOf<ClientError>] { return sorted(commandsByVerb.values) { return $0.verb < $1.verb } } public init() {} /// Registers the given command, making it available to run. /// /// If another command was already registered with the same `verb`, it will /// be overwritten. public func register<C: CommandType where C.ClientError == ClientError>(command: C) { commandsByVerb[command.verb] = CommandOf(command) } /// Runs the command corresponding to the given verb, passing it the given /// arguments. /// /// Returns the results of the execution, or nil if no such command exists. public func runCommand(verb: String, arguments: [String]) -> Result<(), CommandantError<ClientError>>? { return self[verb]?.run(.Arguments(ArgumentParser(arguments))) } /// Returns the command matching the given verb, or nil if no such command /// is registered. public subscript(verb: String) -> CommandOf<ClientError>? { return commandsByVerb[verb] } } extension CommandRegistry { /// Hands off execution to the CommandRegistry, by parsing Process.arguments /// and then running whichever command has been identified in the argument /// list. /// /// If the chosen command executes successfully, the process will exit with /// a successful exit code. /// /// If the chosen command fails, the provided error handler will be invoked, /// then the process will exit with a failure exit code. /// /// If a matching command could not be found or a usage error occurred, /// a helpful error message will be written to `stderr`, then the process /// will exit with a failure error code. @noreturn public func main(#defaultVerb: String, errorHandler: ClientError -> ()) { var arguments = Process.arguments assert(arguments.count >= 1) // Extract the executable name. let executableName = arguments.first! arguments.removeAtIndex(0) let verb = arguments.first ?? defaultVerb if arguments.count > 0 { // Remove the command name. arguments.removeAtIndex(0) } switch runCommand(verb, arguments: arguments) { case .Some(.Success): exit(EXIT_SUCCESS) case let .Some(.Failure(error)): switch error.value { case let .UsageError(description): fputs(description + "\n", stderr) case let .CommandError(error): errorHandler(error.value) } exit(EXIT_FAILURE) case .None: fputs("Unrecognized command: '\(verb)'. See `\(executableName) help`.\n", stderr) exit(EXIT_FAILURE) } } }
mit
8455719b3108efd129798b36e6c45916
29.449275
105
0.715612
3.908837
false
false
false
false
pixyzehn/EsaKit
Sources/EsaKit/Models/Members.swift
1
2336
// // Members.swift // EsaKit // // Created by pixyzehn on 2016/11/22. // Copyright © 2016 pixyzehn. All rights reserved. // import Foundation public struct Members: AutoEquatable, AutoHashable { public let members: [MemberUser] public let page: UInt public let prevPage: UInt? public let nextPage: UInt? public let maxPerPage: UInt public let totalCount: UInt enum Key: String { case members case page case prevPage = "prev_page" case nextPage = "next_page" case maxPerPage = "max_per_page" case totalCount = "total_count" } } extension Members: Decodable { // swiftlint:disable line_length public static func decode(json: Any) throws -> Members { guard let dictionary = json as? [String: Any] else { throw DecodeError.invalidFormat(json: json) } guard let membersJSON = dictionary[Key.members.rawValue] as? [Any] else { throw DecodeError.missingValue(key: Key.members.rawValue, actualValue: dictionary[Key.members.rawValue]) } var members: [MemberUser] = [] for memberJSON in membersJSON { let member: MemberUser do { member = try MemberUser.decode(json: memberJSON) } catch { throw DecodeError.custom(error.localizedDescription) } members.append(member) } guard let page = dictionary[Key.page.rawValue] as? UInt else { throw DecodeError.missingValue(key: Key.page.rawValue, actualValue: dictionary[Key.page.rawValue]) } guard let maxPerPage = dictionary[Key.maxPerPage.rawValue] as? UInt else { throw DecodeError.missingValue(key: Key.maxPerPage.rawValue, actualValue: dictionary[Key.maxPerPage.rawValue]) } guard let totalCount = dictionary[Key.totalCount.rawValue] as? UInt else { throw DecodeError.missingValue(key: Key.totalCount.rawValue, actualValue: dictionary[Key.totalCount.rawValue]) } return Members( members: members, page: page, prevPage: dictionary["prev_page"] as? UInt, nextPage: dictionary["next_page"] as? UInt, maxPerPage: maxPerPage, totalCount: totalCount ) } }
mit
8f7f263bc38a8a08258af74e6eb3fc17
31.887324
122
0.623555
4.516441
false
false
false
false
gobetti/Swift
BasicAgenda/BasicAgenda/NewContactViewController.swift
1
1831
// // NewContactViewController.swift // BasicAgenda // // Created by Carlos Butron on 12/04/15. // Copyright (c) 2015 Carlos Butron. All rights reserved. // import UIKit protocol NewContactDelegate { func newContact(contact: Contact) } class NewContactViewController: UIViewController { @IBOutlet weak var nameTextField: UITextField! @IBOutlet weak var surnameTextField: UITextField! @IBOutlet weak var phoneTextField: UITextField! @IBOutlet weak var emailTextField: UITextField! var delegate: NewContactDelegate? @IBAction func savePushButton(sender: AnyObject) { let contact = Contact() contact.name = nameTextField.text! contact.surname = surnameTextField.text! contact.phone = phoneTextField.text! contact.email = emailTextField.text! delegate?.newContact(contact) dismissViewControllerAnimated(true, completion: nil) } @IBAction func cancelPushButton(sender: AnyObject) { dismissViewControllerAnimated(true, completion: nil) } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
mit
d622c686a5c90c9bd80c0d97efd14c92
24.430556
106
0.652103
5.322674
false
false
false
false
flypaper0/ethereum-wallet
ethereum-wallet/Classes/BusinessLayer/Services/Channel/Observer.swift
1
1244
// Copyright © 2018 Conicoin LLC. All rights reserved. // Created by Artur Guseinov import Foundation struct Identifier: Hashable { private let id: String init(_ id: String) { self.id = id } init() { self.id = UUID().uuidString } // MARK: Hashable var hashValue: Int { return id.hashValue } static func == (_ lhs: Identifier, _ rhs: Identifier) -> Bool { return lhs.id == rhs.id } } extension Identifier: ExpressibleByStringLiteral { typealias StringLiteralType = String init(stringLiteral value: String) { self.id = value } } class Observer<SignalData> { typealias Callback = (SignalData) -> Void let id: Identifier private let callback: Callback init(id: Identifier, callback: @escaping Callback) { self.id = id self.callback = callback } func send(_ value: SignalData) { self.callback(value) } } extension Observer: Hashable { var hashValue: Int { return self.id.hashValue } static func == (_ lhs: Observer, _ rhs: Observer) -> Bool { return lhs.hashValue == rhs.hashValue } } extension Observer { convenience init(id: String, callback: @escaping Callback) { self.init(id: Identifier(id), callback: callback) } }
gpl-3.0
deadcf750e601e6998d2f3cd097dee5c
18.123077
65
0.654063
3.958599
false
false
false
false
benjohnde/Clipinio
Clipinio/Classes/Application/CMHotKey.swift
1
1320
// // CMHotKey.swift // Clipinio // // Created by Ben John on 10/12/15. // Copyright © 2015 Ben John. All rights reserved. // import Cocoa import Carbon class HotKey { fileprivate var hotKey: EventHotKeyRef? = nil fileprivate var eventHandler: EventHandlerRef? = nil init(keyCode: Int, modifiers: Int, block: @escaping () -> ()) { let hotKeyID = EventHotKeyID(signature: 1, id: 1) var eventType = EventTypeSpec(eventClass: OSType(kEventClassKeyboard), eventKind: UInt32(kEventHotKeyPressed)) let ptr = UnsafeMutablePointer<Any>.allocate(capacity: 1) ptr.initialize(to: block) let eventHandlerUPP: EventHandlerUPP = {(_: OpaquePointer?, _: OpaquePointer?, ptr: UnsafeMutableRawPointer?) -> OSStatus in guard let pointer = ptr else { fatalError() } // EventHandlerProcPtr UnsafeMutablePointer<() -> ()>(OpaquePointer(pointer)).pointee() return noErr } InstallEventHandler(GetApplicationEventTarget(), eventHandlerUPP, 1, &eventType, ptr, &eventHandler) RegisterEventHotKey(UInt32(keyCode), UInt32(modifiers), hotKeyID, GetApplicationEventTarget(), OptionBits(0), &hotKey) } deinit { UnregisterEventHotKey(hotKey) RemoveEventHandler(eventHandler) } }
mit
922b7789a87af82cd5a6f218208c0669
33.710526
132
0.66793
4.595819
false
false
false
false
voyages-sncf-technologies/Collor
Collor/Classes/CollectionUpdater.swift
1
7921
// // CollectionUpdater.swift // Collor // // Created by Guihal Gwenn on 05/04/17. // Copyright (c) 2017-present, Voyages-sncf.com. All rights reserved. // import Foundation public extension NSExceptionName { static let collorMissingSectionUID = NSExceptionName("collor.missingSectionUID") static let collorMissingItemUID = NSExceptionName("collor.missingItemUID") static let collorDuplicateItemUID = NSExceptionName("collor.duplicateItemUID") static let collorDuplicateSectionUID = NSExceptionName("collor.duplicateSectionUID") static let collorSectionIndexNil = NSExceptionName("collor.sectionIndexNil") static let collorSectionBuilderNil = NSExceptionName("collor.sectionBuilderNil") } final public class CollectionUpdater { var result:UpdateCollectionResult? unowned let collectionData: CollectionData init(collectionData: CollectionData) { self.collectionData = collectionData } public func append(cells:[CollectionCellDescribable], after cell:CollectionCellDescribable) { guard let indexPath = cell.indexPath else { return } guard let section = collectionData.sections[safe: indexPath.section] else { return } section.cells.insert(contentsOf: cells, at: indexPath.item + 1) collectionData.computeIndices() result?.insertedCellDescriptors.append(contentsOf: cells) result?.insertedIndexPaths.append(contentsOf: cells.map{ $0.indexPath! } ) // unwrapped because computeIndices() called before } public func append(cells:[CollectionCellDescribable], before cell:CollectionCellDescribable) { guard let indexPath = cell.indexPath else { return } guard let section = collectionData.sections[safe: indexPath.section] else { return } section.cells.insert(contentsOf: cells, at: indexPath.item) collectionData.computeIndices() result?.insertedCellDescriptors.append(contentsOf: cells) result?.insertedIndexPaths.append(contentsOf: cells.map{ $0.indexPath! } ) // unwrapped because computeIndices() called before } public func append(cells:[CollectionCellDescribable], in section:CollectionSectionDescribable) { section.cells.append(contentsOf: cells) collectionData.computeIndices() result?.insertedCellDescriptors.append(contentsOf: cells) result?.insertedIndexPaths.append(contentsOf: cells.map{ $0.indexPath! } ) // unwrapped because computeIndices() called before } public func remove(cells:[CollectionCellDescribable]) { var needTocomputeIndices = false cells.forEach { cellToDelete in guard let section = collectionData.sectionDescribable(for: cellToDelete) else { return } guard let indexPath = cellToDelete.indexPath else { return } guard let index = section.cells.firstIndex(where: {$0 === cellToDelete}) else { return } section.cells.remove(at: index) result?.deletedIndexPaths.append( indexPath ) result?.deletedCellDescriptors.append(cellToDelete ) needTocomputeIndices = true } if needTocomputeIndices { collectionData.computeIndices() } } public func reload(cells:[CollectionCellDescribable]) { let cellsToReload = cells.filter{ $0.indexPath != nil } result?.reloadedIndexPaths.append(contentsOf: cellsToReload.map { $0.indexPath! } ) result?.reloadedCellDescriptors.append(contentsOf: cellsToReload) } public func append(sections:[CollectionSectionDescribable], after section:CollectionSectionDescribable) { guard let sectionIndex = section.index else { return } collectionData.sections.insert(contentsOf: sections, at: sectionIndex + 1) result?.insertedSectionsIndexSet.insert(integersIn: Range(uncheckedBounds: (lower: sectionIndex + 1, upper: sectionIndex + 1 + sections.count))) result?.insertedSectionDescriptors.append(contentsOf: sections) collectionData.computeIndices() } public func append(sections:[CollectionSectionDescribable], before section:CollectionSectionDescribable) { guard let sectionIndex = section.index else { return } collectionData.sections.insert(contentsOf: sections, at: sectionIndex) result?.insertedSectionsIndexSet.insert(integersIn: Range(uncheckedBounds: (lower: sectionIndex, upper: sectionIndex + sections.count))) result?.insertedSectionDescriptors.append(contentsOf: sections) collectionData.computeIndices() } public func append(sections:[CollectionSectionDescribable]) { let oldSectionsCount = collectionData.sections.count collectionData.sections.append(contentsOf: sections) result?.insertedSectionsIndexSet.insert(integersIn: Range(uncheckedBounds: (lower: oldSectionsCount, upper: oldSectionsCount + sections.count))) result?.insertedSectionDescriptors.append(contentsOf: sections) collectionData.computeIndices() } public func remove(sections:[CollectionSectionDescribable]) { var needTocomputeIndices = false sections.forEach { (sectionToDelete) in guard let index = collectionData.sections.firstIndex(where: {$0 === sectionToDelete} ) else { return } collectionData.sections.remove(at: index) result?.deletedSectionsIndexSet.insert(index) result?.deletedSectionDescriptors.append(sectionToDelete) needTocomputeIndices = true } if needTocomputeIndices { collectionData.computeIndices() } } public func reload(sections:[CollectionSectionDescribable]) { sections.forEach { (sectionToReload) in guard let index = collectionData.sections.firstIndex(where: {$0 === sectionToReload} ) else { return } sectionToReload.cells.removeAll() sectionToReload.supplementaryViews.removeAll() if let builderObject = sectionToReload.builderObject { let sectionBuilder = SectionBuilder() builderObject(sectionBuilder) sectionToReload.cells = sectionBuilder.cells sectionToReload.supplementaryViews = sectionBuilder.supplementaryViews } else if let builder = sectionToReload.builder { builder(&sectionToReload.cells) } collectionData.computeIndexPaths(in:sectionToReload) result?.reloadedSectionsIndexSet.insert(index) result?.reloadedSectionDescriptors.append(sectionToReload) } } } public struct UpdateCollectionResult { public var insertedIndexPaths = [IndexPath]() public var insertedCellDescriptors = [CollectionCellDescribable]() public var deletedIndexPaths = [IndexPath]() public var deletedCellDescriptors = [CollectionCellDescribable]() public var reloadedIndexPaths = [IndexPath]() public var reloadedCellDescriptors = [CollectionCellDescribable]() public var insertedSectionsIndexSet = IndexSet() public var insertedSectionDescriptors = [CollectionSectionDescribable]() public var deletedSectionsIndexSet = IndexSet() public var deletedSectionDescriptors = [CollectionSectionDescribable]() public var reloadedSectionsIndexSet = IndexSet() public var reloadedSectionDescriptors = [CollectionSectionDescribable]() public var movedIndexPaths = [(from:IndexPath,to:IndexPath)]() public var movedCellDescriptors = [CollectionCellDescribable]() }
bsd-3-clause
f572f889ef64fa39707761e23b417305
42.048913
152
0.684636
5.3412
false
false
false
false
corchwll/amos-ss15-proj5_ios
MobileTimeAccounting/UserInterface/Recording/RecordingViewController.swift
1
14049
/* Mobile Time Accounting Copyright (C) 2015 This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero 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 Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ import UIKit class RecordingViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, NewSessionDelegate, SessionTimerDelegate { @IBOutlet weak var timeLabel: UILabel! @IBOutlet weak var startStopButton: UIButton! @IBOutlet weak var newSessionButton: UIBarButtonItem! @IBOutlet weak var chooseProjectButton: UIButton! @IBOutlet weak var projectIdLabel: UILabel! @IBOutlet weak var projectNameLabel: UILabel! @IBOutlet weak var projectSessionsTableView: UITableView! let notificationTime = (hour: 21, minute: 23, seconds: 0) var sessionTimer: SessionTimer! var project: Project! var projectSessions = [Session]() var session: Session = Session() /* iOS life-cycle function. Looks up recent project and handles what to do if no recent projects was found. @methodtype Hook @pre - @post - */ override func viewDidLoad() { super.viewDidLoad() sessionTimer = SessionTimer(delegate: self) setNotification(NSDate().dateBySettingTime(notificationTime.hour, minute: notificationTime.minute, second: notificationTime.seconds)!) loadRecentProject() if project != nil { setUpNavigationItemButton() } } /* iOS life-cycle function, called when view did appear. Enables/Hides all buttons based on current project situation (if a project is active or not). @methodtype Hook @pre - @post Buttons are enabled/disabled/hidden/visible */ override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) if sessionTimer.isPaused { sessionTimer.resume() } else { loadRecentProject() if project != nil { setButtonStateForHasProject(true) setUpNavigationItemButton() } else { setButtonStateForHasProject(false) projectIdLabel.text = "" projectNameLabel.text = "" } } } /* iOS life-cycle function, called when view did disappear. Pauses session timer if it is running. @methodtype Hook @pre - @post Pauses session timer */ override func viewDidDisappear(animated: Bool) { super.viewDidDisappear(animated) projectSessionsTableView.setEditing(false, animated: false) if sessionTimer.isRunning { sessionTimer.pause() } } /* Sets new notifaction for a given time after canceling all other local notifiactions. If the given time is not an empty day it will check day after day unitl a valid day for setting a notifiaction is found. @methodtype Command @pre - @post Notification is set */ func setNotification(time: NSDate) { var fireDate = time while !sessionManager.isEmptySessionDay(fireDate) { fireDate = fireDate.dateByAddingDays(1)! } var notification = UILocalNotification() notification.alertBody = "You did not record any time for today!" notification.fireDate = fireDate UIApplication.sharedApplication().cancelAllLocalNotifications() UIApplication.sharedApplication().scheduleLocalNotification(notification) } /* Sets up left navigation item button for editing recorded sessions. @methodtype Command @pre Left navigation item button isn't already set up @post Sets up left navigation item button */ func setUpNavigationItemButton() { navigationItem.setLeftBarButtonItem(UIBarButtonItem(barButtonSystemItem: .Edit, target: self, action: Selector("edit")), animated: true) } /* Function for 'edit'-button selector. Enables editing of projects and morphs 'edit' into 'done'. @methodtype Command @pre - @post Editing of projects enabled */ func edit() { projectSessionsTableView.setEditing(true, animated: true) navigationItem.setLeftBarButtonItem(UIBarButtonItem(barButtonSystemItem: .Done, target: self, action: Selector("done")), animated: true) } /* Function for 'done'-button selector. Disables editing of projects and morphs 'done' into 'edit'. @methodtype Command @pre - @post Editing of projects disabled */ func done() { projectSessionsTableView.setEditing(false, animated: true) navigationItem.setLeftBarButtonItem(UIBarButtonItem(barButtonSystemItem: .Edit, target: self, action: Selector("edit")), animated: true) } /* Function is setting the button status of 'start'/'stop'-button, 'new session'-button and 'choose project'-button. @methodtype Command @pre Buttons are available @post Status of buttons has been changed */ func setButtonStateForHasProject(hasProject: Bool) { startStopButton.enabled = hasProject newSessionButton.enabled = hasProject chooseProjectButton.hidden = hasProject } /* Function is loading the most recent project. If no project can be found, it is set to nil. @methodtype Command @pre There must be a recent project @post Recent project has been set */ func loadRecentProject() { if let project = projectManager.getRecentProject() { self.project = project setProjectHeading() loadProjectSessions() } else { self.project = nil } } /* Function is setting the heading for projects. @methodtype Command @pre Project must be set @post Heading has been set */ func setProjectHeading() { projectIdLabel.text = String(project.id) projectNameLabel.text = project.name } /* Function is loading all project sessions. @methodtype Command @pre Project must be set @post Project sessions have been loaded */ func loadProjectSessions() { projectSessions = sessionDAO.getSessions(project) projectSessionsTableView.reloadData() } /* iOS life-cycle function, called right before performing a segue. @methodtype Hook @pre Valid segue identifier @post Set delegates for future callbacks */ override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == "new_session_segue" { var navigationController = segue.destinationViewController as! UINavigationController navigationController.popoverPresentationController!.backgroundColor = UINavigationBar.appearance().barTintColor var viewController = navigationController.visibleViewController as! NewSessionViewController viewController.project = project viewController.delegate = self } } /* Function is called when asking the total number of cells in table view. @methodtype Command @pre - @post Session count is returned */ func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return projectSessions.count } /* Function is called when populating table row cells. Project session are loaded into table view cells. @methodtype Command @pre Project sessions are available @post Session cell has been created */ func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell: SessionTableViewCell = projectSessionsTableView.dequeueReusableCellWithIdentifier("session_cell", forIndexPath: indexPath) as! SessionTableViewCell let startTime = projectSessions[indexPath.row].startTime let endTime = projectSessions[indexPath.row].endTime cell.sessionDate.text = getCellStringForDate(startTime) cell.sessionTime.text = getCellStringforTime(startTime, endTime: endTime) cell.sessionDuration.text = getCellStringForDuration(startTime, endTime: endTime) return cell } /* Returns string representation of a given date. @methodtype Conversion @pre - @post Returns string representation of date */ func getCellStringForDate(date: NSDate)->String { let dateFormatter = NSDateFormatter() dateFormatter.timeStyle = NSDateFormatterStyle.NoStyle dateFormatter.dateStyle = NSDateFormatterStyle.MediumStyle dateFormatter.locale = NSLocale(localeIdentifier: "en_DE") return dateFormatter.stringFromDate(date) } /* Returns string representation of a given start and end time. @methodtype Conversion @pre - @post Returns string representation of start and end time */ func getCellStringforTime(startTime: NSDate, endTime: NSDate)->String { let timeFormatter = NSDateFormatter() timeFormatter.timeStyle = NSDateFormatterStyle.ShortStyle timeFormatter.dateStyle = NSDateFormatterStyle.NoStyle timeFormatter.locale = NSLocale(localeIdentifier: "en_DE") return "\(timeFormatter.stringFromDate(startTime)) - \(timeFormatter.stringFromDate(endTime))" } /* Returns string representation of a duration in hours from a given start to a given end time. @methodtype Conversion @pre - @post Returns string representation of duration from start to end time. */ func getCellStringForDuration(startTime: NSDate, endTime: NSDate)->String { let durationInHours = (Double(endTime.timeIntervalSince1970 - startTime.timeIntervalSince1970)) / 3600 let durationInHoursRounded = Double(Int(durationInHours * 10)) / 10.0 return "\(durationInHoursRounded) h" } /* Function is called when editing table cell. Deletes the selected session and removes corrosponding table cell. @methodtype Command @pre - @post Table cell removed, project archived */ func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { sessionDAO.removeSession(projectSessions[indexPath.row]) projectSessions.removeAtIndex(indexPath.row) projectSessionsTableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Bottom) } /* Function is called when pressing 'Choose project'-button. If this button is visible, it means that no project is currently active, switches to 'Projects'-tab. @methodtype Command @pre - @post 'Projects'-tab is active */ @IBAction func chooseProjectForRecording(sender: AnyObject) { tabBarController?.selectedIndex = 1 } /* Function is called when pressing play button. Toggles time recording functionality. @methodtype Command @pre - @post Time recording is toggled */ @IBAction func toggleTimeRecording(sender: AnyObject) { if sessionTimer.isRunning { session.endTime = sessionTimer.stop() sessionManager.addSession(session, project: project!) didAddNewSession() startStopButton.setTitle("START", forState: .Normal) startStopButton.backgroundColor = UIColor(red: 0x00, green: 0x91/0xff, blue: 0x8e/0xff, alpha: 0xff) } else { session.startTime = sessionTimer.start() startStopButton.setTitle("STOP", forState: .Normal) startStopButton.backgroundColor = UIColor.redColor() timeLabel.text = "0:00" } } /* Called when a new session has been added. Reloads all project sessions and sets new notification to next possible day. @methodtype Command @pre - @post Reloads all sessions and sets notification */ func didAddNewSession() { loadProjectSessions() setNotification(NSDate().dateByAddingDays(1)!.dateBySettingTime(notificationTime.hour, minute: notificationTime.minute, second: notificationTime.seconds)!) } /* Callback function for timer. Updates elapsed time along with ui. @methodtype Command @pre - @post Update on ui and elapsed time */ func didUpdateTimer(elapsedTime: String) { timeLabel.text = elapsedTime } }
agpl-3.0
fecc44ef387edd31d3ac6a4f0a02da94
30.573034
165
0.632501
5.55077
false
false
false
false
royratcliffe/Snippets
Sources/objc_getClasses.swift
1
2404
// Snippets objc_getClasses.swift // // Copyright © 2016, Roy Ratcliffe, Pioneering Software, United Kingdom // // 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, EITHER // EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. 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 /// Obtains all registered Objective-C classes. /// - returns: an array of AnyClass types, one for each Objective-C class. The /// array is only a sample of the classes at the current point in time. It /// does not include any classes not yet registered. Therefore, two calls to /// *get* the classes may answer two different arrays. public func objc_getClasses() -> [AnyClass] { var classes = [AnyClass]() let classCount = objc_getClassList(nil, 0) let classList = UnsafeMutablePointer<AnyClass?>.allocate(capacity: Int(classCount)) defer { classList.deallocate(capacity: Int(classCount)) } let classBuffer = AutoreleasingUnsafeMutablePointer<AnyClass?>(classList) objc_getClassList(classBuffer, classCount) for classIndex in 0..<classCount { guard let anyClass = classList[Int(classIndex)] else { continue } classes.append(anyClass) } return classes } /// Convenience method for obtaining all Objective-C class names. public func objc_getClassNames() -> [String] { return objc_getClasses().map { (anyClass) -> String in NSStringFromClass(anyClass) } }
mit
7b7cf976d55e7e59e8cabee17c182d18
45.960784
85
0.725678
4.485019
false
false
false
false
sarvex/Stormy
Stormy/ViewController.swift
1
3987
// // ViewController.swift // Stormy // // Created by Sarvex Jatasra on 12/04/2015. // Copyright (c) 2015 Sarvex Jatasra. All rights reserved. // import UIKit class ViewController: UIViewController { private let apiKey = "67956a9ceb424f3351b13961904768a4" @IBOutlet weak var iconView: UIImageView! @IBOutlet weak var currentTimeLabel: UILabel! @IBOutlet weak var temperatureLabel: UILabel! @IBOutlet weak var humidityLabel: UILabel! @IBOutlet weak var precipitationLabel: UILabel! @IBOutlet var summaryLabel: UILabel! @IBOutlet weak var refreshButton: UIButton! @IBOutlet weak var refreshActivityIndicator: UIActivityIndicatorView! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. refreshActivityIndicator.hidden = true downloadTemperature() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func refreshClicked(sender: UIButton) { refreshButton.hidden = true; refreshActivityIndicator.hidden = false; refreshActivityIndicator.startAnimating(); downloadTemperature() } private func downloadTemperature () { let baseUrl = NSURL(string: "https://api.forecast.io/forecast/\(apiKey)/") let coordinateUrl = NSURL(string: "28.4700,77.0300", relativeToURL: baseUrl) let forecastUrl = NSURL(string: "?units=ca", relativeToURL: coordinateUrl) let sharedSession = NSURLSession.sharedSession() let downloadTask: NSURLSessionDownloadTask = sharedSession.downloadTaskWithURL(forecastUrl!, completionHandler:{ (location: NSURL!, response: NSURLResponse!, error: NSError!) -> Void in if (error == nil) { let dataObject = NSData(contentsOfURL: location) let weatherDictionary:NSDictionary = NSJSONSerialization.JSONObjectWithData(dataObject!, options: nil, error: nil) as! NSDictionary let currentWeather = Current(weatherDictionary: weatherDictionary) dispatch_async(dispatch_get_main_queue(), { () -> Void in self.iconView.image = currentWeather.icon! self.currentTimeLabel.text = "At \(currentWeather.currentTime!) it is" self.temperatureLabel.text = "\(currentWeather.temperature)" self.humidityLabel.text = "\(currentWeather.humidity)" self.precipitationLabel.text = "\(currentWeather.precipitationProbability)" self.summaryLabel.text = "\(currentWeather.summary)" self.refreshActivityIndicator.stopAnimating() self.refreshActivityIndicator.hidden = true self.refreshButton.hidden = false }) } else { let networkIssueController = UIAlertController(title: "Error", message: "Unable to load data. Connectivity Error", preferredStyle: .Alert) let okButton = UIAlertAction(title: "OK", style: .Default, handler: nil) networkIssueController.addAction(okButton) let cancelButton = UIAlertAction(title: "Cancel", style: .Cancel, handler: nil) networkIssueController.addAction(cancelButton) self.presentViewController(networkIssueController, animated: true, completion: nil) dispatch_async(dispatch_get_main_queue(), { () -> Void in self.refreshActivityIndicator.stopAnimating() self.refreshActivityIndicator.hidden = true self.refreshButton.hidden = false }) } }) downloadTask.resume() } }
isc
2bcbefa4bcb1417f5f04df7979f6d7d9
43.3
158
0.62779
5.5375
false
false
false
false
RocketJourney/RaceTracker
Example/RaceTracker/RunSettingsController.swift
1
4538
// // RunSetingsController.swift // RaceTracker // // Created by Ernesto Cambuston on 10/4/15. // Copyright © 2015 CocoaPods. All rights reserved. // import UIKit protocol RunSettingsDelegate { func updateUnitSystem(unitSystem:Bool) func updateFeedbackLabel(type:Int, value:Int) } class RunSettingsController : UITableViewController { var delegate:RunSettingsDelegate? var unitSystem = Preferences.instance.unitSystem var autopause = Preferences.instance.autopause private var unitString = "km" override func viewDidLoad() { super.viewDidLoad() title = "Settings" setupNavbar() updateUnitString() } private func updateUnitString() { unitString = unitSystem ? "km" : "mi" } private func setupNavbar() { let navBar = navigationController!.navigationBar navBar.barTintColor = UIColor.blackColor() navBar.tintColor = UIColor.whiteColor() navBar.translucent = false let nav = UIBarButtonItem(title: "Done", style: .Done, target: self, action: "dismiss") navigationItem.rightBarButtonItem = nav } func dismiss() { dismissViewControllerAnimated(true, completion: nil) } override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 6 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { switch section { case 1, 2: return 3 default: return 1 } } override func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return 60.0 } override func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { let xview = UIView() xview.backgroundColor = UIColor.lightGrayColor() return xview } weak var uiswitch:UISwitch? override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = UITableViewCell() cell.backgroundColor = UIColor.blackColor() cell.textLabel?.textColor = UIColor.whiteColor() switch indexPath.section { case 0: cell.textLabel?.text = "No Feedback" case 1: switch indexPath.row { case 0: cell.textLabel?.text = "1.0 \(unitString)" case 1: cell.textLabel?.text = "1.5 \(unitString)" case 2: cell.textLabel?.text = "2.0 \(unitString)" default: break } case 2: switch indexPath.row { case 0: cell.textLabel?.text = "5:00 min" case 1: cell.textLabel?.text = "10:00 min" case 2: cell.textLabel?.text = "15:00 min" default: break } case 3: cell.textLabel?.text = unitSystem ? "Metric" : "Imperial" case 4: cell.textLabel?.text = "Pace tracking" case 5: if let uiswitch = uiswitch { cell.addSubview(uiswitch) } else { let _uiswitch = UISwitch() cell.addSubview(_uiswitch) uiswitch = _uiswitch } cell.selectionStyle = .None uiswitch!.center = CGPointMake(view.frame.size.width * 0.9, 20) uiswitch!.on = autopause uiswitch!.addTarget(self, action: "toggleAutopause:", forControlEvents: .ValueChanged) cell.textLabel?.text = "Autopause" default: break } return cell } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { switch indexPath.section { case 0: setNoSound() case 1: setDistance(indexPath.row) case 2: setTime(indexPath.row) case 3: toggleMetric() case 4: paceSelect() default: break } } func toggleAutopause(uiswitch:UISwitch) { autopause = !autopause Preferences.instance.autopause = autopause uiswitch.setOn(autopause, animated: true) } private func setNoSound() { Preferences.instance.voiceFeedbackEnabled = 0 delegate!.updateFeedbackLabel(0, value: 0) dismiss() } private func setDistance(value:Int) { Preferences.instance.voiceFeedbackEnabled = 1 Preferences.instance.voiceFeedbackDistance = value delegate!.updateFeedbackLabel(1, value: value) dismiss() } private func setTime(value:Int) { Preferences.instance.voiceFeedbackEnabled = 2 delegate!.updateFeedbackLabel(2, value: value) Preferences.instance.voiceFeedbackTime = value dismiss() } private func toggleMetric() { let prefs = Preferences.instance unitSystem = !prefs.unitSystem prefs.unitSystem = unitSystem updateUnitString() delegate!.updateUnitSystem(unitSystem) tableView.reloadData() } private func paceSelect() { } }
mit
44897152db649cad5853887d2259e50f
29.456376
116
0.688561
4.170037
false
false
false
false
AndyQ/C64Emulator
C64Emulator/Views/EmulatorBackgroundView.swift
1
1550
// // EmulatorBackgroundView.swift // C64Emulator // // Created by Andy Qua on 10/08/2016. // Copyright © 2016 Andy Qua. All rights reserved. // import UIKit class EmulationBackgroundView : UIView { @IBOutlet var _emulationViewController : EmulatorViewController! var _keyboardWasVisible = false override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { _keyboardWasVisible = _emulationViewController._keyboardVisible; if _emulationViewController._keyboardVisible { _emulationViewController.clickKeyboardButton(self) return; } for touch in touches { if touch.tapCount == 2 { // _emulationViewController.cancelControlFade() // _emulationViewController.shrinkOrGrowViceView() // _emulationViewController.scheduleControlFadeOut(delay:0.0) return; } } } override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) { if (_keyboardWasVisible) { return; } for touch in touches { if touch.tapCount == 1 { // if !_emulationViewController.controlsVisible() { // _emulationViewController.scheduleControlFadeIn(delay:0.5) // } else { // _emulationViewController.scheduleControlFadeOut(delay:0.5) // } } } } }
gpl-2.0
1634a5c787266fda888677500e5c65ed
27.163636
80
0.561653
4.795666
false
false
false
false
wordpress-mobile/WordPress-iOS
WordPress/Classes/ViewRelated/Post/PostCompactCell.swift
1
8069
import AutomatticTracks import UIKit import Gridicons class PostCompactCell: UITableViewCell, ConfigurablePostView { @IBOutlet weak var titleLabel: UILabel! @IBOutlet weak var timestampLabel: UILabel! @IBOutlet weak var badgesLabel: UILabel! @IBOutlet weak var menuButton: UIButton! @IBOutlet weak var featuredImageView: CachedAnimatedImageView! @IBOutlet weak var headerStackView: UIStackView! @IBOutlet weak var innerView: UIView! @IBOutlet weak var contentStackView: UIStackView! @IBOutlet weak var ghostView: UIView! @IBOutlet weak var progressView: UIProgressView! @IBOutlet weak var separator: UIView! @IBOutlet weak var trailingContentConstraint: NSLayoutConstraint! private var iPadReadableLeadingAnchor: NSLayoutConstraint? private var iPadReadableTrailingAnchor: NSLayoutConstraint? private weak var actionSheetDelegate: PostActionSheetDelegate? lazy var imageLoader: ImageLoader = { return ImageLoader(imageView: featuredImageView, gifStrategy: .mediumGIFs) }() private var post: Post? { didSet { guard let post = post, post != oldValue else { return } viewModel = PostCardStatusViewModel(post: post) } } private var viewModel: PostCardStatusViewModel? func configure(with post: Post) { self.post = post resetGhostStyles() configureTitle() configureDate() configureStatus() configureFeaturedImage() configureProgressView() } @IBAction func more(_ sender: Any) { guard let viewModel = viewModel, let button = sender as? UIButton else { return } actionSheetDelegate?.showActionSheet(viewModel, from: button) } override func awakeFromNib() { super.awakeFromNib() applyStyles() setupReadableGuideForiPad() setupSeparator() setupAccessibility() } private func resetGhostStyles() { toggleGhost(visible: false) menuButton.layer.opacity = Constants.opacity } private func applyStyles() { WPStyleGuide.configureTableViewCell(self) WPStyleGuide.applyPostCardStyle(self) WPStyleGuide.applyPostProgressViewStyle(progressView) WPStyleGuide.configureLabel(timestampLabel, textStyle: .subheadline) WPStyleGuide.configureLabel(badgesLabel, textStyle: .subheadline) titleLabel.font = WPStyleGuide.serifFontForTextStyle(.headline, fontWeight: .bold) titleLabel.adjustsFontForContentSizeCategory = true titleLabel.textColor = .text timestampLabel.textColor = .textSubtle menuButton.tintColor = .textSubtle menuButton.setImage(.gridicon(.ellipsis), for: .normal) featuredImageView.layer.cornerRadius = Constants.imageRadius innerView.backgroundColor = .listForeground backgroundColor = .listForeground contentView.backgroundColor = .listForeground } private func setupSeparator() { WPStyleGuide.applyBorderStyle(separator) } private func setupReadableGuideForiPad() { guard WPDeviceIdentification.isiPad() else { return } iPadReadableLeadingAnchor = innerView.leadingAnchor.constraint(equalTo: readableContentGuide.leadingAnchor) iPadReadableTrailingAnchor = innerView.trailingAnchor.constraint(equalTo: readableContentGuide.trailingAnchor) iPadReadableLeadingAnchor?.isActive = true iPadReadableTrailingAnchor?.isActive = true } private func configureFeaturedImage() { if let post = post, let url = post.featuredImageURL { featuredImageView.isHidden = false let host = MediaHost(with: post, failure: { error in // We'll log the error, so we know it's there, but we won't halt execution. WordPressAppDelegate.crashLogging?.logError(error) }) imageLoader.loadImage(with: url, from: host, preferredSize: CGSize(width: featuredImageView.frame.width, height: featuredImageView.frame.height)) } else { featuredImageView.isHidden = true } } private func configureTitle() { titleLabel.text = post?.titleForDisplay() } private func configureDate() { guard let post = post else { return } timestampLabel.text = post.latest().dateStringForDisplay() timestampLabel.isHidden = false } private func configureExcerpt() { guard let post = post else { return } timestampLabel.text = post.contentPreviewForDisplay() timestampLabel.isHidden = false } private func configureStatus() { guard let viewModel = viewModel else { return } badgesLabel.textColor = viewModel.statusColor badgesLabel.text = viewModel.statusAndBadges(separatedBy: Constants.separator) if badgesLabel.text?.isEmpty ?? true { badgesLabel.isHidden = true } else { badgesLabel.isHidden = false } } private func configureProgressView() { guard let viewModel = viewModel else { return } let shouldHide = viewModel.shouldHideProgressView progressView.isHidden = shouldHide progressView.progress = viewModel.progress if !shouldHide && viewModel.progressBlock == nil { viewModel.progressBlock = { [weak self] progress in self?.progressView.setProgress(progress, animated: true) if progress >= 1.0, let post = self?.post { self?.configure(with: post) } } } } private func setupAccessibility() { menuButton.accessibilityLabel = NSLocalizedString("More", comment: "Accessibility label for the More button in Post List (compact view).") } private enum Constants { static let separator = " · " static let contentSpacing: CGFloat = 8 static let imageRadius: CGFloat = 2 static let labelsVerticalAlignment: CGFloat = -1 static let opacity: Float = 1 static let margin: CGFloat = 16 } } extension PostCompactCell: InteractivePostView { func setInteractionDelegate(_ delegate: InteractivePostViewDelegate) { // Do nothing, since this cell doesn't support actions in `InteractivePostViewDelegate`. } func setActionSheetDelegate(_ delegate: PostActionSheetDelegate) { actionSheetDelegate = delegate } } extension PostCompactCell: GhostableView { func ghostAnimationWillStart() { toggleGhost(visible: true) menuButton.layer.opacity = GhostConstants.opacity } private func toggleGhost(visible: Bool) { isUserInteractionEnabled = !visible menuButton.isGhostableDisabled = true separator.isGhostableDisabled = true ghostView.isHidden = !visible ghostView.backgroundColor = .listForeground contentStackView.isHidden = visible } private enum GhostConstants { static let opacity: Float = 0.5 } } extension PostCompactCell: NibReusable { } // MARK: - For display on the Posts Card (Dashboard) extension PostCompactCell { /// Configure the cell to be displayed in the Posts Card /// No "more" button and show a description, instead of a date func configureForDashboard(with post: Post) { configure(with: post) separator.isHidden = true menuButton.isHidden = true trailingContentConstraint.constant = Constants.margin headerStackView.spacing = Constants.margin disableiPadReadableMargin() if !post.isScheduled() { configureExcerpt() } } func hideSeparator() { separator.isHidden = true } func disableiPadReadableMargin() { iPadReadableLeadingAnchor?.isActive = false iPadReadableTrailingAnchor?.isActive = false } }
gpl-2.0
494ac1ea598ca7c7eab969949302eb26
30.515625
157
0.665097
5.382255
false
true
false
false
ijinmao/JMMaterialTableView
JMMaterialTableViewDemo/JMMaterialTableView/JMMaterialTableView/JMMaterialTableView.swift
2
11578
// // JMMaterialTableView.swift // JMMaterialTableView // // Created by dingnan on 15/10/20. // Copyright © 2015年 ijinmao. All rights reserved. // import Foundation import UIKit class JMMaterialTableView: UICollectionView, UIScrollViewDelegate, UICollectionViewDelegateFlowLayout, JMMaterialLayoutDelegate { // ------ configurable properties var shadowOffset: CGFloat = -3.0 var shadowRadius: CGFloat = 2.0 var shadowOpacity: Float = 0.15 var shadowColor: CGColorRef = UIColor.darkGrayColor().CGColor var transformCoef: CGFloat = 0.04 { didSet { materialLayout?.kAttributesTransform = transformCoef } } var enableTransformation: Bool = true { didSet { materialLayout?.enableTransformation = enableTransformation } } var enableAutoScroll: Bool = true var enableCellShadow: Bool = true var scrollDecelerationRate: CGFloat = 0.3 var shadowAnimationDuration: CFTimeInterval = 0.3 var cellSize: CGSize = CGSize.zero var materialLayout: JMMaterialLayout! //-------- private var cellMinSpacing: CGFloat = 0 private var isScrollEndDecelerating: Bool = true private var lastScrollViewOffsetY: CGFloat = 0 private var scrollWillEndOffsetY: CGFloat = 0 override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) { super.init(frame: frame, collectionViewLayout: layout) self.delegate = self self.decelerationRate = scrollDecelerationRate materialLayout = layout as! JMMaterialLayout materialLayout?.delegate = self } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } // MARK: UICollectionViewDelegateFlowLayout func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize { return cellSize } func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAtIndex section: Int) -> CGFloat { return cellMinSpacing } func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAtIndex section: Int) -> UIEdgeInsets { return UIEdgeInsetsZero } // MARK: JMMaterialLayoutDelegate func updateItemsAttributes(allItemsAttributes: [UICollectionViewLayoutAttributes]?) { //the index of the first cell of not transformed var notTransformCellIndexPath: NSIndexPath? = nil //get indexs of shadowed cell and normal cells var shadowIndexPaths = [NSIndexPath]() var normalIndexPaths = [NSIndexPath]() var lastItemAttributes: UICollectionViewLayoutAttributes? = nil if let allItems = allItemsAttributes { for attributes in allItems { let indexPath = attributes.indexPath if indexPath.row > 0 { if lastItemAttributes == nil { shadowIndexPaths.append(attributes.indexPath) }else if let lastItemAttr = lastItemAttributes { if lastItemAttr.frame.origin.y + lastItemAttr.frame.size.height > attributes.frame.origin.y { shadowIndexPaths.append(attributes.indexPath) } else { normalIndexPaths.append(attributes.indexPath) } } } else { normalIndexPaths.append(attributes.indexPath) } lastItemAttributes = attributes //query the first cell of not transformed if attributes.frame.origin.x == 0 && notTransformCellIndexPath == nil { notTransformCellIndexPath = attributes.indexPath } } //hide the cells before the first cell of not transformed if notTransformCellIndexPath != nil { if let firstAttributs = allItemsAttributes?.first { for var i=firstAttributs.indexPath.row; i<notTransformCellIndexPath!.row-1; i++ { let indexPath = NSIndexPath(forItem: i, inSection: 0) if let cell = self.cellForItemAtIndexPath(indexPath) { cell.hidden = true } } } } //add shadow to the cells if isScrollEndDecelerating { for indexPath in shadowIndexPaths { //pass the cells not displayed in the screen if notTransformCellIndexPath != nil { if indexPath.row < notTransformCellIndexPath!.row-1 { continue } } if let cell = self.cellForItemAtIndexPath(indexPath) { cell.hidden = false //默认radius == 3.0 if enableCellShadow { if cell.layer.shadowOpacity == 0.0 { cell.layer.shadowColor = shadowColor cell.layer.shadowRadius = shadowRadius cell.layer.shadowOffset = CGSizeMake(0, shadowOffset) animationShadowOpacity(0, to: shadowOpacity, duration: shadowAnimationDuration, cell: cell) } } } } } //remove shadow of normal cells for indexPath in normalIndexPaths { //confirm whether the cells already hidden if notTransformCellIndexPath != nil { if indexPath.row < notTransformCellIndexPath!.row-1 { continue } } if let cell = self.cellForItemAtIndexPath(indexPath) { cell.hidden = false if notTransformCellIndexPath != nil { if indexPath.row == notTransformCellIndexPath!.row+1 && indexPath.row > 0 { if cell.layer.shadowOpacity != 0.0 { animationShadowOpacity(shadowOpacity, to: 0, duration: shadowAnimationDuration, cell: cell) } } else { cell.layer.shadowOpacity = 0.0 } } else { cell.layer.shadowOpacity = 0.0 } } } } } // MARK: UIScrollViewDelegate func scrollViewDidScroll(scrollView: UIScrollView) { if enableCellShadow { if !isScrollEndDecelerating { //when collectionView is going to top, hide all shadow of cell if let allItems = materialLayout.layoutAttributesForElementsInRect(CGRectMake(0, 0 , self.frame.size.width, self.frame.size.height*2)) { for attributes in allItems { let indexPath = attributes.indexPath if let cell = self.cellForItemAtIndexPath(indexPath) { if cell.layer.shadowOpacity > 0 { animationShadowOpacity(shadowOpacity, to: 0, duration: shadowAnimationDuration, cell: cell) } } } } } } } func scrollViewDidEndDragging(scrollView: UIScrollView, willDecelerate decelerate: Bool) { if !enableCellShadow { return } print("scrollViewDidEndDragging") //when tableView is about going to top, hide the shadow gradually if self.contentOffset.y < 0 { isScrollEndDecelerating = false if let allItems = materialLayout.layoutAttributesForElementsInRect(CGRectMake(0, 0, self.frame.size.width, self.frame.size.height*2)) { for attributes in allItems { let indexPath = attributes.indexPath if let cell = self.cellForItemAtIndexPath(indexPath) { animationShadowOpacity(shadowOpacity, to: 0, duration: shadowAnimationDuration, cell: cell) } } } } } func scrollViewWillEndDragging(scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) { print("scrollViewWillEndDragging at %f", targetContentOffset.move().y) scrollWillEndOffsetY = targetContentOffset.move().y lastScrollViewOffsetY = scrollView.contentOffset.y if enableAutoScroll { //auto scroll when end offset is in the middle of a cell if abs(scrollView.contentOffset.y - scrollWillEndOffsetY) <= cellSize.height { if scrollWillEndOffsetY > 0 { let topCellIndexPath = NSIndexPath(forItem: Int(scrollWillEndOffsetY / cellSize.height) + 1, inSection: 0) self.setContentOffset(CGPointMake(0, CGFloat(topCellIndexPath.row)*self.cellSize.height), animated: true) self.showsVerticalScrollIndicator = false } } } } func scrollViewDidEndScrollingAnimation(scrollView: UIScrollView) { self.showsVerticalScrollIndicator = true } func scrollViewDidEndDecelerating(scrollView: UIScrollView) { print("scrollViewDidEndDecelerating") isScrollEndDecelerating = true } func scrollViewWillBeginDecelerating(scrollView: UIScrollView) { print("scrollViewWillBeginDecelerating") if enableAutoScroll { //dicide the srolling orientation if scrollWillEndOffsetY < lastScrollViewOffsetY { //scrolling up if scrollWillEndOffsetY > 0 { let topCellIndexPath = NSIndexPath(forItem: Int(scrollWillEndOffsetY / cellSize.height), inSection: 0) self.setContentOffset(CGPointMake(0, CGFloat(topCellIndexPath.row)*cellSize.height), animated: true) self.showsVerticalScrollIndicator = false } } else if scrollWillEndOffsetY > lastScrollViewOffsetY && scrollWillEndOffsetY != 0 { //scrolling down let top2CellIndexPath = NSIndexPath(forItem: Int(abs(scrollWillEndOffsetY) / cellSize.height + 1.0), inSection: 0) self.setContentOffset(CGPointMake(0, CGFloat(top2CellIndexPath.row)*cellSize.height), animated: true) self.showsVerticalScrollIndicator = false } } } //generate shadow func animationShadowOpacity(from: Float, to: Float, duration: CFTimeInterval, cell: UICollectionViewCell) { cell.layer.shadowOpacity = to; // Note: You need the final value here let animation = CABasicAnimation(keyPath: "shadowOpacity") animation.fromValue = from animation.toValue = to animation.duration = duration cell.layer.addAnimation(animation, forKey: "shadowOpacity") } }
mit
a4b3b194739d05ca9783b4877363fca8
43
173
0.581194
6.064465
false
false
false
false
kickstarter/ios-oss
KsApi/models/ShippingRule.swift
1
766
public struct ShippingRule { public let cost: Double public let id: Int? public let location: Location } extension ShippingRule: Decodable { enum CodingKeys: String, CodingKey { case cost case id case location } public init(from decoder: Decoder) throws { let values = try decoder.container(keyedBy: CodingKeys.self) self.cost = try Double(values.decode(String.self, forKey: .cost)) ?? 0 self.id = try values.decodeIfPresent(Int.self, forKey: .id) self.location = try values.decode(Location.self, forKey: .location) } } extension ShippingRule: Equatable {} public func == (lhs: ShippingRule, rhs: ShippingRule) -> Bool { // TODO: change to compare id once that api is deployed return lhs.location == rhs.location }
apache-2.0
11df4ca5ae61bd274a522ab640e98056
26.357143
74
0.707572
3.888325
false
false
false
false
coderLL/PageView
TestPageVIew/TestPageVIew/PageView/PageContentView.swift
1
6152
// // PageContentView.swift // DYTV // // Created by coderLL on 16/9/28. // Copyright © 2016年 coderLL. All rights reserved. // import UIKit protocol PageContentViewDelegate : class { func pageContentView(contentView: PageContentView, progress: CGFloat, sourceIndex: Int, targetIndex: Int) } private let ContentCellID = "ContentCellID" class PageContentView: UIView { // MARK:- 定义属性 private var childVcs : [UIViewController] private weak var parentViewController : UIViewController? private var startOffsetX : CGFloat = 0 private var isForbidScrollDelegate : Bool = false weak var delegate : PageContentViewDelegate? // MARK:- 懒加载属性 private lazy var collectionView : UICollectionView = {[weak self] in // 1.创建layout let layout = UICollectionViewFlowLayout() layout.itemSize = (self?.bounds.size)! layout.minimumLineSpacing = 0 layout.minimumInteritemSpacing = 0 layout.scrollDirection = .Horizontal // 2.创建UICollectionView let collectionView = UICollectionView(frame: CGRectZero, collectionViewLayout: layout) collectionView.showsHorizontalScrollIndicator = false collectionView.pagingEnabled = true collectionView.bounces = false collectionView.dataSource = self collectionView.delegate = self collectionView.registerClass(UICollectionViewCell.self, forCellWithReuseIdentifier: ContentCellID) return collectionView }() // MARK:- 自定义构造函数 init(frame: CGRect, childVcs: [UIViewController], parentViewController: UIViewController?) { self.childVcs = childVcs self.parentViewController = parentViewController super.init(frame: frame) // 设置UI界面 self.setupUI() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } // MARK:- 设置UI界面 extension PageContentView { private func setupUI() { // 1.将所有的控制器添加到父控制器中 for childVc in childVcs { parentViewController?.addChildViewController(childVc) } // 2.添加UICollectionView, 用于在cell中存放控制器的view addSubview(collectionView) collectionView.frame = bounds } } // MARK:- 遵守UICollectionViewDataSource extension PageContentView: UICollectionViewDataSource { func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return self.childVcs.count } func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { // 1.创建cell let cell = collectionView.dequeueReusableCellWithReuseIdentifier(ContentCellID, forIndexPath: indexPath) // 2.给Cell设置内容 // 2.1 由于循环利用, 避免循环添加, 先删除所有的子视图 for view in cell.contentView.subviews { view.removeFromSuperview() } let childVc = childVcs[indexPath.item] childVc.view.frame = cell.contentView.bounds cell.contentView.addSubview(childVc.view) return cell } } // MARK:- 遵守UICollectionViewDelegate extension PageContentView: UICollectionViewDelegate { func scrollViewWillBeginDragging(scrollView: UIScrollView) { // 关闭禁止代理方法 isForbidScrollDelegate = false startOffsetX = scrollView.contentOffset.x } func scrollViewDidScroll(scrollView: UIScrollView) { // 0.判断是否是点击事件 if isForbidScrollDelegate { return } // 1.定义需要获取的数据 var progress : CGFloat = 0 var sourceIndex : Int = 0 var targetIndex : Int = 0 // 2.判断是左滑动还是右滑动 let currentOffsetX : CGFloat = scrollView.contentOffset.x let scrollViewW = scrollView.frame.width if currentOffsetX > startOffsetX { // 左滑动 // 1.计算progress progress = currentOffsetX / scrollViewW - floor(currentOffsetX / scrollViewW) // 2.计算sourceIndex sourceIndex = Int(currentOffsetX / scrollViewW) // 3.计算targetIndex targetIndex = sourceIndex + 1 if targetIndex >= childVcs.count { targetIndex = childVcs.count - 1 } // 4.如果完全划过去 if currentOffsetX - startOffsetX == scrollViewW { progress = 1.0 targetIndex = sourceIndex } } else { // 右滑动 // 1.计算progres s progress = 1 - (currentOffsetX / scrollViewW - floor(currentOffsetX / scrollViewW)) // 2.计算targetIndex targetIndex = Int(currentOffsetX / scrollViewW) // 3.计算sourceIndex sourceIndex = targetIndex + 1 if sourceIndex >= childVcs.count { sourceIndex = childVcs.count - 1 } // 4.如果完全划过去 if startOffsetX - currentOffsetX == scrollViewW { progress = 1.0 sourceIndex = targetIndex } } // 3.将progress/sourceIndex/targetIndex传递给titleView delegate?.pageContentView(self, progress: progress, sourceIndex: sourceIndex, targetIndex: targetIndex) } } // MARK:- 对外暴露的方法 extension PageContentView { func setCurrentIndex(currentIndex : Int) { // 0.记录需要禁止的代理方法 isForbidScrollDelegate = true // 1.计算偏移量 let offsetX = CGFloat(currentIndex) * collectionView.frame.width // 2.设置collectionView的偏移位置 collectionView.setContentOffset(CGPoint(x: offsetX, y: 0), animated: false) } }
mit
60ed15a3df096773324a299d5cb130a3
30.878453
130
0.624025
5.751745
false
false
false
false
y0ke/actor-platform
actor-sdk/sdk-core-ios/ActorSDK/Sources/Controllers/Content/Conversation/Cell/AABubbleServiceCell.swift
2
3319
// // Copyright (c) 2014-2016 Actor LLC. <https://actor.im> // import Foundation public class AABubbleServiceCell : AABubbleCell { private static let serviceBubbleFont = UIFont.boldSystemFontOfSize(12) private static let maxServiceTextWidth: CGFloat = 260 private let serviceText = YYLabel() private var bindedLayout: ServiceCellLayout! public init(frame: CGRect) { super.init(frame: frame, isFullSize: true) // Configuring service label serviceText.font = AABubbleServiceCell.serviceBubbleFont; serviceText.lineBreakMode = .ByWordWrapping; serviceText.numberOfLines = 0; serviceText.textColor = appStyle.chatServiceTextColor serviceText.contentMode = UIViewContentMode.Center serviceText.textAlignment = NSTextAlignment.Center contentView.addSubview(serviceText) // Setting content and bubble insets contentInsets = UIEdgeInsets(top: 3, left: 8, bottom: 3, right: 8) bubbleInsets = UIEdgeInsets(top: 3, left: 0, bottom: 3, right: 0) // Setting bubble background bindBubbleType(.Service, isCompact: false) } public required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } public override func bind(message: ACMessage, receiveDate: jlong, readDate: jlong, reuse: Bool, cellLayout: AACellLayout, setting: AACellSetting) { self.bindedLayout = cellLayout as! ServiceCellLayout if (!reuse) { serviceText.text = bindedLayout.text } } public override func layoutContent(maxWidth: CGFloat, offsetX: CGFloat) { let insets = fullContentInsets let contentWidth = self.contentView.frame.width let serviceWidth = bindedLayout.textSize.width let serviceHeight = bindedLayout.textSize.height serviceText.frame = CGRectMake((contentWidth - serviceWidth) / 2.0, insets.top, serviceWidth, serviceHeight); layoutBubble(serviceWidth, contentHeight: serviceHeight) } } public class ServiceCellLayout: AACellLayout { var text: String var textSize: CGSize public init(text: String, date: Int64, layouter: AABubbleLayouter) { // Saving text size self.text = text // Measuring text size self.textSize = UIViewMeasure.measureText(text, width: AABubbleServiceCell.maxServiceTextWidth, font: AABubbleServiceCell.serviceBubbleFont) // Creating layout super.init(height: textSize.height + 6, date: date, key: "service", layouter: layouter) } } public class AABubbleServiceCellLayouter: AABubbleLayouter { public func isSuitable(message: ACMessage) -> Bool { return message.content is ACServiceContent } public func buildLayout(peer: ACPeer, message: ACMessage) -> AACellLayout { let serviceText = Actor.getFormatter().formatFullServiceMessageWithSenderId(message.senderId, withContent: message.content as! ACServiceContent) return ServiceCellLayout(text: serviceText, date: Int64(message.date), layouter: self) } public func cellClass() -> AnyClass { return AABubbleServiceCell.self } }
agpl-3.0
53739c40260040d1c39a99d97764cb18
33.936842
152
0.675505
4.880882
false
false
false
false
SusanDoggie/Doggie
Sources/DoggieGeometry/Geometry/Matrix.swift
1
21645
// // Matrix.swift // // The MIT License // Copyright (c) 2015 - 2022 Susan Cheng. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // /// /// Transformation Matrix: /// /// ⎛ a e i 0 ⎞ /// ⎜ b f j 0 ⎟ /// ⎜ c g k 0 ⎟ /// ⎝ d h l 1 ⎠ /// @frozen public struct Matrix: Hashable { public var a: Double public var b: Double public var c: Double public var d: Double public var e: Double public var f: Double public var g: Double public var h: Double public var i: Double public var j: Double public var k: Double public var l: Double @inlinable @inline(__always) public init(a: Double, b: Double, c: Double, d: Double, e: Double, f: Double, g: Double, h: Double, i: Double, j: Double, k: Double, l: Double) { self.a = a self.b = b self.c = c self.d = d self.e = e self.f = f self.g = g self.h = h self.i = i self.j = j self.k = k self.l = l } @inlinable @inline(__always) public init<T: BinaryFloatingPoint>(a: T, b: T, c: T, d: T, e: T, f: T, g: T, h: T, i: T, j: T, k: T, l: T) { self.a = Double(a) self.b = Double(b) self.c = Double(c) self.d = Double(d) self.e = Double(e) self.f = Double(f) self.g = Double(g) self.h = Double(h) self.i = Double(i) self.j = Double(j) self.k = Double(k) self.l = Double(l) } } extension Matrix: CustomStringConvertible { @inlinable @inline(__always) public var description: String { return "Matrix(a: \(a), b: \(b), c: \(c), d: \(d), e: \(e), f: \(f), g: \(g), h: \(h), i: \(i), j: \(j), k: \(k), l: \(l))" } } extension Matrix: Codable { @inlinable @inline(__always) public init(from decoder: Decoder) throws { var container = try decoder.unkeyedContainer() self.a = try container.decode(Double.self) self.e = try container.decode(Double.self) self.i = try container.decode(Double.self) self.b = try container.decode(Double.self) self.f = try container.decode(Double.self) self.j = try container.decode(Double.self) self.c = try container.decode(Double.self) self.g = try container.decode(Double.self) self.k = try container.decode(Double.self) self.d = try container.decode(Double.self) self.h = try container.decode(Double.self) self.l = try container.decode(Double.self) } @inlinable @inline(__always) public func encode(to encoder: Encoder) throws { var container = encoder.unkeyedContainer() try container.encode(self.a) try container.encode(self.e) try container.encode(self.i) try container.encode(self.b) try container.encode(self.f) try container.encode(self.j) try container.encode(self.c) try container.encode(self.g) try container.encode(self.k) try container.encode(self.d) try container.encode(self.h) try container.encode(self.l) } } @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) extension Matrix: Sendable { } extension Matrix { @inlinable @inline(__always) public var invertible: Bool { let determinant = self.determinant return determinant.isFinite && !determinant.almostZero() } @inlinable @inline(__always) public var inverse: Matrix { let _a = g * j - f * k let _b = c * j - b * k let _c = c * f - b * g let _d = _a * d - _b * h + _c * l let _e = g * i - e * k let _f = c * i - a * k let _g = c * e - a * g let _h = _e * d - _f * h + _g * l let _i = f * i - e * j let _j = b * i - a * j let _k = b * e - a * f let _l = _i * d - _j * h + _k * l let det = _c * i - _g * j + _k * k return Matrix(a: _a / det, b: -_b / det, c: _c / det, d: -_d / det, e: -_e / det, f: _f / det, g: -_g / det, h: _h / det, i: _i / det, j: -_j / det, k: _k / det, l: -_l / det) } } extension Matrix { @inlinable @inline(__always) public var tx: Double { get { return d } set { d = newValue } } @inlinable @inline(__always) public var ty: Double { get { return h } set { h = newValue } } @inlinable @inline(__always) public var tz: Double { get { return l } set { l = newValue } } } extension Matrix { @inlinable @inline(__always) public var determinant: Double { let _c = c * f - b * g let _g = c * e - a * g let _k = b * e - a * f return _c * i - _g * j + _k * k } } extension Matrix { /// /// Transformation Matrix: /// /// ⎛ 1 0 0 0 ⎞ /// ⎜ 0 1 0 0 ⎟ /// ⎜ 0 0 1 0 ⎟ /// ⎝ 0 0 0 1 ⎠ /// @inlinable @inline(__always) public static var identity: Matrix { return Matrix(a: 1, b: 0, c: 0, d: 0, e: 0, f: 1, g: 0, h: 0, i: 0, j: 0, k: 1, l: 0) } } extension Matrix { /// /// Transformation Matrix: /// /// ⎛ 1 0 0 0 ⎞ /// ⎜ 0 cos(a) sin(a) 0 ⎟ /// ⎜ 0 -sin(a) cos(a) 0 ⎟ /// ⎝ 0 0 0 1 ⎠ /// @inlinable @inline(__always) public static func rotateX(_ angle: Double) -> Matrix { return Matrix(a: 1, b: 0, c: 0, d: 0, e: 0, f: cos(angle), g: -sin(angle), h: 0, i: 0, j: sin(angle), k: cos(angle), l: 0) } /// /// Transformation Matrix: /// /// ⎛ 1 0 0 0 ⎞ /// ⎜ 0 cos(a) sin(a) 0 ⎟ /// ⎜ 0 -sin(a) cos(a) 0 ⎟ /// ⎝ 0 0 0 1 ⎠ /// @inlinable @inline(__always) public static func rotateX<T: BinaryFloatingPoint>(_ angle: T) -> Matrix { return .rotateX(Double(angle)) } } extension Matrix { /// /// Transformation Matrix: /// /// ⎛ cos(a) 0 -sin(a) 0 ⎞ /// ⎜ 0 1 0 0 ⎟ /// ⎜ sin(a) 0 cos(a) 0 ⎟ /// ⎝ 0 0 0 1 ⎠ /// @inlinable @inline(__always) public static func rotateY(_ angle: Double) -> Matrix { return Matrix(a: cos(angle), b: 0, c: sin(angle), d: 0, e: 0, f: 1, g: 0, h: 0, i: -sin(angle), j: 0, k: cos(angle), l: 0) } /// /// Transformation Matrix: /// /// ⎛ cos(a) 0 -sin(a) 0 ⎞ /// ⎜ 0 1 0 0 ⎟ /// ⎜ sin(a) 0 cos(a) 0 ⎟ /// ⎝ 0 0 0 1 ⎠ /// @inlinable @inline(__always) public static func rotateY<T: BinaryFloatingPoint>(_ angle: T) -> Matrix { return .rotateY(Double(angle)) } } extension Matrix { /// /// Transformation Matrix: /// /// ⎛ cos(a) sin(a) 0 0 ⎞ /// ⎜ -sin(a) cos(a) 0 0 ⎟ /// ⎜ 0 0 1 0 ⎟ /// ⎝ 0 0 0 1 ⎠ /// @inlinable @inline(__always) public static func rotateZ(_ angle: Double) -> Matrix { return Matrix(a: cos(angle), b: -sin(angle), c: 0, d: 0, e: sin(angle), f: cos(angle), g: 0, h: 0, i: 0, j: 0, k: 1, l: 0) } /// /// Transformation Matrix: /// /// ⎛ cos(a) sin(a) 0 0 ⎞ /// ⎜ -sin(a) cos(a) 0 0 ⎟ /// ⎜ 0 0 1 0 ⎟ /// ⎝ 0 0 0 1 ⎠ /// @inlinable @inline(__always) public static func rotateZ<T: BinaryFloatingPoint>(_ angle: T) -> Matrix { return .rotateZ(Double(angle)) } } extension Matrix { /// /// Transformation Matrix: /// /// ⎛ x 0 0 0 ⎞ /// ⎜ 0 y 0 0 ⎟ /// ⎜ 0 0 z 0 ⎟ /// ⎝ 0 0 0 1 ⎠ /// @inlinable @inline(__always) public static func scale(_ scale: Double) -> Matrix { return Matrix(a: scale, b: 0, c: 0, d: 0, e: 0, f: scale, g: 0, h: 0, i: 0, j: 0, k: scale, l: 0) } /// /// Transformation Matrix: /// /// ⎛ x 0 0 0 ⎞ /// ⎜ 0 y 0 0 ⎟ /// ⎜ 0 0 z 0 ⎟ /// ⎝ 0 0 0 1 ⎠ /// @inlinable @inline(__always) public static func scale(_ scale: Int) -> Matrix { return .scale(Double(scale)) } /// /// Transformation Matrix: /// /// ⎛ x 0 0 0 ⎞ /// ⎜ 0 y 0 0 ⎟ /// ⎜ 0 0 z 0 ⎟ /// ⎝ 0 0 0 1 ⎠ /// @inlinable @inline(__always) public static func scale<T: BinaryInteger>(_ scale: T) -> Matrix { return .scale(Double(scale)) } /// /// Transformation Matrix: /// /// ⎛ x 0 0 0 ⎞ /// ⎜ 0 y 0 0 ⎟ /// ⎜ 0 0 z 0 ⎟ /// ⎝ 0 0 0 1 ⎠ /// @inlinable @inline(__always) public static func scale<T: BinaryFloatingPoint>(_ scale: T) -> Matrix { return .scale(Double(scale)) } } extension Matrix { /// /// Transformation Matrix: /// /// ⎛ x 0 0 0 ⎞ /// ⎜ 0 y 0 0 ⎟ /// ⎜ 0 0 z 0 ⎟ /// ⎝ 0 0 0 1 ⎠ /// @inlinable @inline(__always) public static func scale(x: Double = 1, y: Double = 1, z: Double = 1) -> Matrix { return Matrix(a: x, b: 0, c: 0, d: 0, e: 0, f: y, g: 0, h: 0, i: 0, j: 0, k: z, l: 0) } /// /// Transformation Matrix: /// /// ⎛ x 0 0 0 ⎞ /// ⎜ 0 y 0 0 ⎟ /// ⎜ 0 0 z 0 ⎟ /// ⎝ 0 0 0 1 ⎠ /// @inlinable @inline(__always) public static func scale(x: Int = 1, y: Int = 1, z: Int = 1) -> Matrix { return .scale(x: Double(x), y: Double(y), z: Double(z)) } /// /// Transformation Matrix: /// /// ⎛ x 0 0 0 ⎞ /// ⎜ 0 y 0 0 ⎟ /// ⎜ 0 0 z 0 ⎟ /// ⎝ 0 0 0 1 ⎠ /// @inlinable @inline(__always) public static func scale<T: BinaryInteger>(x: T = 1, y: T = 1, z: T = 1) -> Matrix { return .scale(x: Double(x), y: Double(y), z: Double(z)) } /// /// Transformation Matrix: /// /// ⎛ x 0 0 0 ⎞ /// ⎜ 0 y 0 0 ⎟ /// ⎜ 0 0 z 0 ⎟ /// ⎝ 0 0 0 1 ⎠ /// @inlinable @inline(__always) public static func scale<T: BinaryFloatingPoint>(x: T = 1, y: T = 1, z: T = 1) -> Matrix { return .scale(x: Double(x), y: Double(y), z: Double(z)) } } extension Matrix { /// /// Transformation Matrix: /// /// ⎛ 1 0 0 0 ⎞ /// ⎜ 0 1 0 0 ⎟ /// ⎜ 0 0 1 0 ⎟ /// ⎝ x y z 1 ⎠ /// @inlinable @inline(__always) public static func translate(x: Double = 0, y: Double = 0, z: Double = 0) -> Matrix { return Matrix(a: 1, b: 0, c: 0, d: x, e: 0, f: 1, g: 0, h: y, i: 0, j: 0, k: 1, l: z) } /// /// Transformation Matrix: /// /// ⎛ 1 0 0 0 ⎞ /// ⎜ 0 1 0 0 ⎟ /// ⎜ 0 0 1 0 ⎟ /// ⎝ x y z 1 ⎠ /// @inlinable @inline(__always) public static func translate(x: Int = 0, y: Int = 0, z: Int = 0) -> Matrix { return .translate(x: Double(x), y: Double(y), z: Double(z)) } /// /// Transformation Matrix: /// /// ⎛ 1 0 0 0 ⎞ /// ⎜ 0 1 0 0 ⎟ /// ⎜ 0 0 1 0 ⎟ /// ⎝ x y z 1 ⎠ /// @inlinable @inline(__always) public static func translate<T: BinaryInteger>(x: T = 0, y: T = 0, z: T = 0) -> Matrix { return .translate(x: Double(x), y: Double(y), z: Double(z)) } /// /// Transformation Matrix: /// /// ⎛ 1 0 0 0 ⎞ /// ⎜ 0 1 0 0 ⎟ /// ⎜ 0 0 1 0 ⎟ /// ⎝ x y z 1 ⎠ /// @inlinable @inline(__always) public static func translate<T: BinaryFloatingPoint>(x: T = 0, y: T = 0, z: T = 0) -> Matrix { return .translate(x: Double(x), y: Double(y), z: Double(z)) } } extension Matrix { /// /// Transformation Matrix: /// /// ⎛ -1 0 0 0 ⎞ /// ⎜ 0 1 0 0 ⎟ /// ⎜ 0 0 1 0 ⎟ /// ⎝ 2x 0 0 1 ⎠ /// @inlinable @inline(__always) public static func reflectX(_ x: Double = 0) -> Matrix { return Matrix(a: -1, b: 0, c: 0, d: 2 * x, e: 0, f: 1, g: 0, h: 0, i: 0, j: 0, k: 1, l: 0) } /// /// Transformation Matrix: /// /// ⎛ -1 0 0 0 ⎞ /// ⎜ 0 1 0 0 ⎟ /// ⎜ 0 0 1 0 ⎟ /// ⎝ 2x 0 0 1 ⎠ /// @inlinable @inline(__always) public static func reflectX(_ x: Int) -> Matrix { return .reflectX(Double(x)) } /// /// Transformation Matrix: /// /// ⎛ -1 0 0 0 ⎞ /// ⎜ 0 1 0 0 ⎟ /// ⎜ 0 0 1 0 ⎟ /// ⎝ 2x 0 0 1 ⎠ /// @inlinable @inline(__always) public static func reflectX<T: BinaryInteger>(_ x: T) -> Matrix { return .reflectX(Double(x)) } /// /// Transformation Matrix: /// /// ⎛ -1 0 0 0 ⎞ /// ⎜ 0 1 0 0 ⎟ /// ⎜ 0 0 1 0 ⎟ /// ⎝ 2x 0 0 1 ⎠ /// @inlinable @inline(__always) public static func reflectX<T: BinaryFloatingPoint>(_ x: T) -> Matrix { return .reflectX(Double(x)) } } extension Matrix { /// /// Transformation Matrix: /// /// ⎛ 1 0 0 0 ⎞ /// ⎜ 0 -1 0 0 ⎟ /// ⎜ 0 0 1 0 ⎟ /// ⎝ 0 2y 0 1 ⎠ /// @inlinable @inline(__always) public static func reflectY(_ y: Double = 0) -> Matrix { return Matrix(a: 1, b: 0, c: 0, d: 0, e: 0, f: -1, g: 0, h: 2 * y, i: 0, j: 0, k: 1, l: 0) } /// /// Transformation Matrix: /// /// ⎛ 1 0 0 0 ⎞ /// ⎜ 0 -1 0 0 ⎟ /// ⎜ 0 0 1 0 ⎟ /// ⎝ 0 2y 0 1 ⎠ /// @inlinable @inline(__always) public static func reflectY(_ y: Int) -> Matrix { return .reflectY(Double(y)) } /// /// Transformation Matrix: /// /// ⎛ 1 0 0 0 ⎞ /// ⎜ 0 -1 0 0 ⎟ /// ⎜ 0 0 1 0 ⎟ /// ⎝ 0 2y 0 1 ⎠ /// @inlinable @inline(__always) public static func reflectY<T: BinaryInteger>(_ y: T) -> Matrix { return .reflectY(Double(y)) } /// /// Transformation Matrix: /// /// ⎛ 1 0 0 0 ⎞ /// ⎜ 0 -1 0 0 ⎟ /// ⎜ 0 0 1 0 ⎟ /// ⎝ 0 2y 0 1 ⎠ /// @inlinable @inline(__always) public static func reflectY<T: BinaryFloatingPoint>(_ y: T) -> Matrix { return .reflectY(Double(y)) } } extension Matrix { /// /// Transformation Matrix: /// /// ⎛ 1 0 0 0 ⎞ /// ⎜ 0 1 0 0 ⎟ /// ⎜ 0 0 -1 0 ⎟ /// ⎝ 0 0 2z 1 ⎠ /// @inlinable @inline(__always) public static func reflectZ(_ z: Double = 0) -> Matrix { return Matrix(a: 1, b: 0, c: 0, d: 0, e: 0, f: 1, g: 0, h: 0, i: 0, j: 0, k: -1, l: 2 * z) } /// /// Transformation Matrix: /// /// ⎛ 1 0 0 0 ⎞ /// ⎜ 0 1 0 0 ⎟ /// ⎜ 0 0 -1 0 ⎟ /// ⎝ 0 0 2z 1 ⎠ /// @inlinable @inline(__always) public static func reflectZ(_ z: Int) -> Matrix { return .reflectZ(Double(z)) } /// /// Transformation Matrix: /// /// ⎛ 1 0 0 0 ⎞ /// ⎜ 0 1 0 0 ⎟ /// ⎜ 0 0 -1 0 ⎟ /// ⎝ 0 0 2z 1 ⎠ /// @inlinable @inline(__always) public static func reflectZ<T: BinaryInteger>(_ z: T) -> Matrix { return .reflectZ(Double(z)) } /// /// Transformation Matrix: /// /// ⎛ 1 0 0 0 ⎞ /// ⎜ 0 1 0 0 ⎟ /// ⎜ 0 0 -1 0 ⎟ /// ⎝ 0 0 2z 1 ⎠ /// @inlinable @inline(__always) public static func reflectZ<T: BinaryFloatingPoint>(_ z: T) -> Matrix { return .reflectZ(Double(z)) } } extension Matrix { @inlinable @inline(__always) public static func rotate(roll x: Double, pitch y: Double, yaw z: Double) -> Matrix { return rotateX(x) * rotateY(y) * rotateZ(z) } @inlinable @inline(__always) public static func rotate<T: BinaryFloatingPoint>(roll x: T, pitch y: T, yaw z: T) -> Matrix { return .rotate(roll: Double(x), pitch: Double(y), yaw: Double(z)) } } extension Matrix { @inlinable @inline(__always) public static func rotate(radian: Double, x: Double, y: Double, z: Double) -> Matrix { let _abs = sqrt(x * x + y * y + z * z) let vx = x / _abs let vy = y / _abs let vz = z / _abs let _cos = cos(radian) let _cosp = 1.0 - _cos let _sin = sin(radian) return Matrix(a: _cos + _cosp * vx * vx, b: _cosp * vx * vy - vz * _sin, c: _cosp * vx * vz + vy * _sin, d: 0.0, e: _cosp * vy * vx + vz * _sin, f: _cos + _cosp * vy * vy, g: _cosp * vy * vz - vx * _sin, h: 0.0, i: _cosp * vz * vx - vy * _sin, j: _cosp * vz * vy + vx * _sin, k: _cos + _cosp * vz * vz, l: 0.0) } @inlinable @inline(__always) public static func rotate<T: BinaryFloatingPoint>(radian: T, x: T, y: T, z: T) -> Matrix { return .rotate(radian: Double(radian), x: Double(x), y: Double(y), z: Double(z)) } } extension Matrix { @inlinable @inline(__always) public static func camera(position tx: Double, _ ty: Double, _ tz: Double, rotate ax: Double, _ ay: Double, _ az: Double) -> Matrix { return translate(x: -tx, y: -ty, z: -tz) * rotateZ(-az) * rotateY(-ay) * rotateX(-ax) } @inlinable @inline(__always) public static func camera<T: BinaryFloatingPoint>(position tx: T, _ ty: T, _ tz: T, rotate ax: T, _ ay: T, _ az: T) -> Matrix { return .camera(position: Double(tx), Double(ty), Double(tz), rotate: Double(ax), Double(ay), Double(az)) } } extension Matrix: Multiplicative { } @inlinable @inline(__always) public func *(lhs: Matrix, rhs: Matrix) -> Matrix { let a = lhs.a * rhs.a + lhs.e * rhs.b + lhs.i * rhs.c let b = lhs.b * rhs.a + lhs.f * rhs.b + lhs.j * rhs.c let c = lhs.c * rhs.a + lhs.g * rhs.b + lhs.k * rhs.c let d = lhs.d * rhs.a + lhs.h * rhs.b + lhs.l * rhs.c + rhs.d let e = lhs.a * rhs.e + lhs.e * rhs.f + lhs.i * rhs.g let f = lhs.b * rhs.e + lhs.f * rhs.f + lhs.j * rhs.g let g = lhs.c * rhs.e + lhs.g * rhs.f + lhs.k * rhs.g let h = lhs.d * rhs.e + lhs.h * rhs.f + lhs.l * rhs.g + rhs.h let i = lhs.a * rhs.i + lhs.e * rhs.j + lhs.i * rhs.k let j = lhs.b * rhs.i + lhs.f * rhs.j + lhs.j * rhs.k let k = lhs.c * rhs.i + lhs.g * rhs.j + lhs.k * rhs.k let l = lhs.d * rhs.i + lhs.h * rhs.j + lhs.l * rhs.k + rhs.l return Matrix(a: a, b: b, c: c, d: d, e: e, f: f, g: g, h: h, i: i, j: j, k: k, l: l) } @inlinable @inline(__always) public func *=(lhs: inout Matrix, rhs: Matrix) { lhs = lhs * rhs } @inlinable @inline(__always) public func *(lhs: Vector, rhs: Matrix) -> Vector { return Vector(x: lhs.x * rhs.a + lhs.y * rhs.b + lhs.z * rhs.c + rhs.d, y: lhs.x * rhs.e + lhs.y * rhs.f + lhs.z * rhs.g + rhs.h, z: lhs.x * rhs.i + lhs.y * rhs.j + lhs.z * rhs.k + rhs.l) } @inlinable @inline(__always) public func *=(lhs: inout Vector, rhs: Matrix) { lhs = lhs * rhs }
mit
23ffd9b84c5c0d61ee664b36c96bb542
25.252174
191
0.450338
3.120183
false
false
false
false
myandy/shi_ios
shishi/UI/Edit/EditBGImageVC.swift
1
15249
// // EditBGImageVC.swift // shishi // // Created by tb on 2017/10/15. // Copyright © 2017年 andymao. All rights reserved. // import UIKit import Photos import FXBlurView private let cellIdentifier = "cellIdentifier" class EditBGImageVC: UIViewController { internal lazy var poetryContainerView: SharePoetryView = { let poetryContainerView = SharePoetryView(frame: CGRect.zero) return poetryContainerView }() internal lazy var poetryScrollView: UIScrollView = { let poetryScrollView = UIScrollView() return poetryScrollView }() //滚动视图的背景 internal lazy var scrollBGView: UIView = { let bgView = UIView() return bgView }() lazy var collectionViewLayout: UICollectionViewLayout = { [unowned self] in let layout = UICollectionViewFlowLayout() layout.scrollDirection = .horizontal layout.minimumInteritemSpacing = 10 layout.minimumLineSpacing = 10 layout.sectionInset = UIEdgeInsets.init(top: 10, left: 10, bottom: 10, right: 10) return layout }() internal lazy var collectionView: UICollectionView = { let collectionView = UICollectionView(frame: CGRect.zero, collectionViewLayout: self.collectionViewLayout) collectionView.translatesAutoresizingMaskIntoConstraints = false collectionView.backgroundColor = UIColor.clear collectionView.showsHorizontalScrollIndicator = false collectionView.dataSource = self collectionView.delegate = self return collectionView }() //滑动条父视图 internal lazy var sliderContainerView: UIView = { let containerView = UIView() return containerView }() internal lazy var brightnessSlider = UISlider() internal lazy var blurSlider = UISlider() internal var albumImage: UIImage? //背景图片 internal var bgImageArray = PoetryImage.allValues internal var selectedImageIndex = 0 override func viewDidLoad() { super.viewDidLoad() self.setupUI() self.showFirstBGImage() if PHPhotoLibrary.authorizationStatus() != .authorized { PHPhotoLibrary.requestAuthorization({ [unowned self] (status) in if status == .authorized { self.resoveFirstAlbumImage() } }) } else { self.resoveFirstAlbumImage() } let guesture = UITapGestureRecognizer(target: self, action: #selector(self.tapHandler)) self.poetryContainerView.addGestureRecognizer(guesture) } internal func setupUI() { self.setupViews() self.setupConstraints() self.setupPoetryView() self.hiddenSliderView(isHidden: true) FontsUtils.setFont(self.poetryScrollView) } internal func setupViews() { self.view.addSubview(self.scrollBGView) self.scrollBGView.addSubview(self.poetryScrollView) self.view.addSubview(self.collectionView) self.collectionView.register(ShareImageCollectionViewCell.self, forCellWithReuseIdentifier: cellIdentifier) self.setupSliderView() } internal func setupPoetryView() { self.poetryScrollView.addSubview(self.poetryContainerView) self.poetryContainerView.snp.makeConstraints { (make) in make.edges.equalToSuperview() make.width.equalToSuperview()//.offset(convertWidth(pix: -20)) make.height.greaterThanOrEqualToSuperview() } } internal func setupConstraints() { self.scrollBGView.snp.makeConstraints { (make) in make.top.equalToSuperview().offset(convertWidth(pix: 100)) make.centerX.equalToSuperview() make.width.equalToSuperview().multipliedBy(0.9) make.height.equalTo(self.scrollBGView.snp.width) } self.poetryScrollView.snp.makeConstraints { (make) in make.edges.equalToSuperview() make.width.equalToSuperview() //make.height.equalTo(self.poetryScrollView.snp.width) } self.collectionView.snp.makeConstraints { (make) in make.centerX.equalToSuperview() make.width.equalToSuperview().offset(convertWidth(pix: -10)) make.top.equalTo(self.poetryScrollView.snp.bottom).offset(convertWidth(pix: 40)) make.height.equalTo(convertWidth(pix: 250)) } } internal func setupSliderView() { self.view.addSubview(self.sliderContainerView) self.sliderContainerView.snp.makeConstraints { (make) in make.centerX.equalToSuperview() make.width.equalToSuperview().offset(convertWidth(pix: -30)) make.top.bottom.equalTo(self.collectionView) } self.sliderContainerView.addSubview(brightnessSlider) brightnessSlider.isContinuous = true brightnessSlider.value = 0.5 brightnessSlider.snp.makeConstraints { (make) in make.centerX.equalToSuperview() make.width.equalToSuperview().offset(convertWidth(pix: -20)) make.top.equalToSuperview().offset(convertWidth(pix: 20)) } brightnessSlider.rx.controlEvent(.valueChanged).subscribe(onNext: { [unowned self] _ in self.onBrightnessSliderChange(value: self.brightnessSlider.value) }).addDisposableTo(self.rx_disposeBag) self.sliderContainerView.addSubview(blurSlider) blurSlider.isContinuous = true blurSlider.value = 0.3 blurSlider.maximumValue = 0.6 blurSlider.snp.makeConstraints { (make) in make.centerX.equalToSuperview() make.width.equalToSuperview().offset(convertWidth(pix: -20)) make.top.equalTo(brightnessSlider.snp.bottom).offset(convertWidth(pix: 20)) } blurSlider.rx.controlEvent(.valueChanged).subscribe(onNext: { [unowned self] _ in self.onBlurSliderChange(value: self.blurSlider.value) }).addDisposableTo(self.rx_disposeBag) } func tapHandler() { } //获取相册第一张图片 //改成使用内置图片 // internal func resoveFirstAlbumImage() { // let fetchOptions = PHFetchOptions() // let smartAlbums:PHFetchResult = PHAsset.fetchAssets(with: .image, options: fetchOptions) // smartAlbums.enumerateObjects({ [weak self] (asset, index, isStop) in // let imageManager = PHImageManager.default() // let requestOptions = PHImageRequestOptions() // requestOptions.isSynchronous = true // let size = CGSize(width: 720, height: 1280) // isStop.pointee = true // imageManager.requestImage(for: asset, targetSize: size, contentMode: .aspectFill, options: requestOptions) { image, info in // if let image = image { // self?.albumImage = self?.resizedImage(image: image) // // } // } // }) // } internal func resoveFirstAlbumImage() { self.albumImage = UIImage(named: "zuibaichi")! } //相册选择图片 func selectImage() { let picker = UIImagePickerController() picker.delegate = self picker.allowsEditing = false picker.sourceType = .photoLibrary self.present(picker, animated: true, completion: nil) } //背景图片变化,子类处理 internal func onBGImageUpdate(image: UIImage) { } //显示第一张背景图 internal func showFirstBGImage() { self.poetryContainerView.setupBGImage(image: self.bgImageArray[0].image(), imageId: self.bgImageArray[0].rawValue) } internal func updateImageWithSlider() { if let image = self.albumImage { let resultImage = self.imageUpdate(image: image, blur: self.blurSlider.value, brightness: self.brightnessSlider.value) self.poetryContainerView.setupBGImage(image: resultImage, imageId: nil) } } internal func onBrightnessSliderChange(value: Float) { // if let image = self.albumImage { // let resultImage = self.imageUpdate(image: image, blur: self.blurSlider.value, brightness: value) // self.poetryContainerView.setupBGImage(image: resultImage) // } self.updateImageWithSlider() } internal func onBlurSliderChange(value: Float) { // if let image = self.albumImage { // let resultImage = self.imageUpdate(image: image, blur: value, brightness: self.brightnessSlider.value) // self.poetryContainerView.setupBGImage(image: resultImage) // } self.updateImageWithSlider() } //显示图片列表 internal func hiddenBgImageCollectionView(isHidden: Bool) { self.collectionView.isHidden = isHidden } //显示图片属性调节视图 internal func hiddenSliderView(isHidden: Bool) { self.sliderContainerView.isHidden = isHidden } internal func imageUpdate(image: UIImage, blur: Float, brightness: Float) -> UIImage { let blurImage = self.imageUpdateBlur(image: image, value: blur) return self.imageUpdateBrightness(image: blurImage, value: brightness) } internal func imageUpdateBlur(image: UIImage, value: Float) -> UIImage { let radius: CGFloat = CGFloat(40 * value) let iterations: UInt = UInt(10 * value) let blurImage = image.blurredImage(withRadius: radius, iterations: iterations, tintColor: nil)! //self.poetryContainerView.setupBGImage(image: blurImage) return blurImage } internal func imageUpdateBrightness(image: UIImage, value: Float) -> UIImage { // // 修改亮度 -255---255 数越大越亮 let brightnessValue = (2 * value - 1)/2 * 255 * 0.6 let brigntImage = image.cgImage!.brightened(value: brightnessValue) return UIImage(cgImage: brigntImage!) // let context = CIContext(options: nil) // let superImage = CIImage(cgImage:image.cgImage!) // let lighten = CIFilter(name:"CIColorControls") // lighten?.setValue(superImage, forKey: kCIInputImageKey) // // 修改亮度 -1---1 数越大越亮 // let brightnessValue = (2 * value - 1)/2 // lighten?.setValue(brightnessValue, forKey: "inputBrightness") // let result:CIImage = lighten?.value(forKey: kCIOutputImageKey) as! CIImage // let cgImage:CGImage = context.createCGImage(result, from: superImage.extent)! // // // 得到修改后的图片 // let myImage = UIImage(cgImage: cgImage) // // return myImage } } extension EditBGImageVC: UICollectionViewDataSource { public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return self.bgImageArray.count } public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellIdentifier, for: indexPath) as! ShareImageCollectionViewCell let image = self.bgImageArray[indexPath.row] cell.imageView.image = image.smallImage() cell.updateSelectedStatus(isSelected: self.selectedImageIndex == indexPath.row) return cell } } extension EditBGImageVC: UICollectionViewDelegate { public func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { let image = self.bgImageArray[indexPath.row] self.poetryContainerView.setupBGImage(image: image.image(), imageId: image.rawValue) self.onBGImageUpdate(image: image.image()) if let cell = collectionView.cellForItem(at: indexPath) as? ShareImageCollectionViewCell { cell.updateSelectedStatus(isSelected: true) } if let cell = collectionView.cellForItem(at: IndexPath(row: self.selectedImageIndex, section: indexPath.section)) as? ShareImageCollectionViewCell { cell.updateSelectedStatus(isSelected: false) } self.selectedImageIndex = indexPath.row } // public func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat { // return 10 // } // // func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets { // return UIEdgeInsets.init(top: 10, left: 10, bottom: 10, right: 10) // } } extension EditBGImageVC: UICollectionViewDelegateFlowLayout { public func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { return CGSize(width: self.collectionView.bounds.size.height, height: self.collectionView.bounds.size.height) } } extension EditBGImageVC: UIImagePickerControllerDelegate, UINavigationControllerDelegate { func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) { let chosenImage = info[UIImagePickerControllerOriginalImage] as! UIImage // use the image //self.albumImage = chosenImage.fixOrientation() let image = chosenImage.fixOrientation()! self.albumImage = self.resizedImage(image: image) self.poetryContainerView.setupBGImage(image: self.albumImage!, imageId: nil) self.onBGImageUpdate(image: self.albumImage!) picker.dismiss(animated: true, completion: nil) } func imagePickerControllerDidCancel(_ picker: UIImagePickerController) { picker.dismiss(animated: true, completion: nil) } internal func resizedImage(image: UIImage) -> UIImage { let maxWidth: CGFloat = 720 if image.size.width <= maxWidth { return image } let resizeSize = CGSize(width: maxWidth, height: image.size.height / image.size.width * maxWidth) return image.imageScaledToSize(newSize: resizeSize) } } internal extension UIImage { func imageScaledToSize(newSize:CGSize) -> UIImage { UIGraphicsBeginImageContextWithOptions(newSize, false, self.scale) self.draw(in: CGRect(x:0, y:0, width:newSize.width, height:newSize.height)) let image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return image! } }
apache-2.0
5f79345aefd3bb83b5d563e276de5b35
37.284987
188
0.642629
4.998671
false
false
false
false
Shopify/unity-buy-sdk
PluginDependencies/iOSPlugin/UnityBuySDKPluginTests/ApplePayEventDispatcherTests.swift
1
7882
// // ApplePayEventDispatcherTests.swift // UnityBuySDK // // Created by Shopify. // Copyright © 2017 Shopify Inc. 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 XCTest import PassKit @testable import UnityBuySDKPlugin class ApplePayEventDispatcherTests: XCTestCase { let timeout = 10.0 override func setUp() { super.setUp() if Tester.hasLoaded == false { let didLoad = expectation(description: "Tester failed to load") Tester.completion = { didLoad.fulfill() } self.wait(for: [didLoad], timeout: timeout) } let setupMessage = UnityMessage(content: "", object: TesterName, method: TesterMethod.setupApplePayEventTest.rawValue) let messageExpectation = self.expectation(description: "MessageCenter.send(setupApplePayEventTest) failed to complete") MessageCenter.send(setupMessage) { response in messageExpectation.fulfill() } self.wait(for: [messageExpectation], timeout: timeout) } override func tearDown() { MockAuthorizationController.instances.removeAll() super.tearDown() } /// Tests that the correct serialized message was sent to Unity func testPaymentSessionFinish() { let session = Models.createPaymentSession(requiringShippingAddressFields: true, usingNonDefault: MockAuthorizationController.self) let dispatcher = ApplePayEventDispatcher(receiver:TesterName) session.delegate = dispatcher session.presentAuthorizationController() /// Since we did not authorize before invoking finish, we expect to send Unity a status of PaymentStatus.cancelled MockAuthorizationController.invokeDidFinish() assertLastMessageContentEqual(to: PaymentStatus.cancelled.description) } /// Tests that the correct serialized payment was sent to Unity, and the expected response was parsed correctly func testPaymentAuthorization() { let session = Models.createPaymentSession(requiringShippingAddressFields: true, usingNonDefault: MockAuthorizationController.self) let dispatcher = ApplePayEventDispatcher(receiver: TesterName) let payment = Models.createPayment() session.delegate = dispatcher session.presentAuthorizationController() // Check that the proper response was received from the delegate // The value we expect to receive is defined in the Unity Tester object let authExpectation = self.expectation(description: "MockAuthorizationController.invokeDidAuthorizePayment failed to complete") MockAuthorizationController.invokeDidAuthorizePayment(payment) { (status: PKPaymentAuthorizationStatus) in XCTAssertEqual(.success, status) authExpectation.fulfill() } wait(for: [authExpectation], timeout: timeout) assertLastMessageContentEqual(to: try! payment.serializedString()) MockAuthorizationController.invokeDidFinish() assertLastMessageContentEqual(to: PaymentStatus.success.description) } /// Tests that the correct serialized shipping method was sent to Unity, and the expected response was parsed correctly func testSelectShippingMethod() { let session = Models.createPaymentSession(requiringShippingAddressFields: true, usingNonDefault: MockAuthorizationController.self) let dispatcher = ApplePayEventDispatcher(receiver: TesterName) session.delegate = dispatcher session.presentAuthorizationController() // Check that the proper response was received from the delegate // The value we expect to receive is defined in the Unity Tester object let shippingMethods = Models.createShippingMethods() let selectedMethod = shippingMethods[1] let expectation = self.expectation(description: "MockAuthorizationController.invokeDidSelectShippingMethod failed to complete") let expectedItem = Models.createSummaryItem() MockAuthorizationController.invokeDidSelectShippingMethod(selectedMethod) { status, items in XCTAssertEqual(.success, status) XCTAssertEqual(items.count, 1) XCTAssertEqual(expectedItem, items[0]) expectation.fulfill() } wait(for: [expectation], timeout: timeout) assertLastMessageContentEqual(to: selectedMethod.identifier) MockAuthorizationController.invokeDidFinish() } /// Tests that the correct serialized shipping contact was sent to Unity, and the expected response was parsed correctly func testSelectShippingContact() { let session = Models.createPaymentSession(requiringShippingAddressFields: true, usingNonDefault: MockAuthorizationController.self) let dispatcher = ApplePayEventDispatcher(receiver: TesterName) session.delegate = dispatcher session.presentAuthorizationController() // Check that the proper response was received from the delegate // The value we expect to receive is defined in the Unity Tester object let selectedContact = Models.createContact(with: Models.createPostalAddress()) let expectation = self.expectation(description: "MockAuthorizationController.invokeDidSelectShippingContact failed to complete") let expectedMethod = Models.createShippingMethod() let expectedItem = Models.createSummaryItem() MockAuthorizationController.invokeDidSelectShippingContact(selectedContact) { status, methods, items in XCTAssertEqual(.success, status) XCTAssertEqual(items.count, 1) XCTAssertEqual(methods.count, 1) XCTAssertEqual(expectedItem, items[0]) XCTAssertEqual(expectedMethod, methods[0]) expectation.fulfill() } self.wait(for: [expectation], timeout: timeout) assertLastMessageContentEqual(to: try! selectedContact.serializedString()) MockAuthorizationController.invokeDidFinish() } } extension ApplePayEventDispatcherTests { func assertLastMessageContentEqual(to content: String?) { let getLastMessage = UnityMessage(content: "", object: TesterName, method: TesterMethod.getLastMessage.rawValue) let messageExpectation = self.expectation(description: "MessageCenter.send(getLastMessage) failed to complete") MessageCenter.send(getLastMessage) { response in XCTAssertEqual(response, content) messageExpectation.fulfill() } self.wait(for: [messageExpectation], timeout: timeout) } }
mit
ce568cf89b61eeea61d99a5beda32d28
46.763636
143
0.707398
5.386876
false
true
false
false
sabbek/EasySwift
EasySwift/EasySwift/UIButton.swift
1
3659
// // UIButton.swift // EasySwift // // Created by Sabbe on 21/03/17. // Copyright © 2017 sabbe.kev. All rights reserved. // // MIT License // // Copyright (c) 2017 sabbek // // 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 // MARK: - Extensions - extension UIButton { // MARK: - Button with Text title convenience init(x: CGFloat, y: CGFloat, w: CGFloat, h: CGFloat, titleColor: UIColor?, bgColor: UIColor?, title: String?, alignment: UIControlContentHorizontalAlignment?, selector: Selector?, superView: UIView?) { self.init() self.frame = CGRect(x: x, y: y, w: w, h: h) if titleColor != nil { self.setTitleColor(titleColor, for: .normal) } if bgColor != nil { self.backgroundColor = bgColor } if title != nil { self.setTitle(title, for: .normal) } if alignment != nil { self.contentHorizontalAlignment = alignment! } if selector != nil { self.addTarget(nil, action: selector!, for: .touchUpInside) } if superView != nil { superView!.addSubview(self) } } // MARK: - Button with Image convenience init(x: CGFloat, y: CGFloat, w: CGFloat, h: CGFloat, bgColor: UIColor?, image: UIImage?, contentMode: UIViewContentMode?, insets: UIEdgeInsets?, selector: Selector?, superView: UIView?) { self.init() self.frame = CGRect(x: x, y: y, w: w, h: h) if image != nil { self.setImage(image!, for: .normal) } if contentMode != nil { self.contentMode = contentMode! } if insets != nil { self.imageEdgeInsets = insets! } if selector != nil { self.addTarget(nil, action: selector!, for: .touchUpInside) } if superView != nil { superView!.addSubview(self) } } // MARK: - Properties func setProperties(text: String, size: CGFloat, color: UIColor?) { self.setTitle(text, for: .normal) self.titleLabel!.font = UIFont(name: self.titleLabel!.font.fontName, size: size) color != nil ? self.setTitleColor(color, for: .normal) : () } func setAction(action: Selector, tag: Int?) { self.addTarget(nil, action: action, for: .touchUpInside) if tag != nil { self.tag = tag! } } }
mit
a869075b1bd68c94bfdb8fc83c62e6d3
31.371681
89
0.5924
4.460976
false
false
false
false
silt-lang/silt
Sources/InnerCore/TypeInfo.swift
1
27139
/// TypeInfo.swift /// /// Copyright 2019, The Silt Language Project. /// /// This project is released under the MIT license, a copy of which is /// available in the repository. import Foundation import LLVM import Seismography // MARK: Basic Type Info /// A type that provides the IR-level implementation details for a type. /// // swiftlint:disable line_length protocol TypeInfo: Explodable, Assignable, Destroyable, StackAllocatable, PODable { /// The LLVM representation of a stored value of this type. For /// non-fixed types, this is really useful only for forming pointers to it. var llvmType: IRType { get } /// The minimum alignment of a value of this type. var alignment: Alignment { get } } extension TypeInfo { /// Computes and returns the explosion schema for values of this type. var schema: Explosion.Schema { let s = Explosion.Schema.Builder() self.buildExplosionSchema(s) return s.finalize() } /// Crafts an address value from an IR value with the same underlying type /// as this type info object. /// /// If the pointer's underlying type does not match this type info, a fatal /// error is raised. /// /// FIXME: Opaque pointers make this invariant useless. /// /// - Parameter v: A value of pointer type. /// - Returns: An address value for the pointer value. func address(for v: IRValue) -> Address { guard let ptrTy = v.type as? PointerType else { fatalError() } precondition(ptrTy.pointee.asLLVM() == self.llvmType.asLLVM()) return Address(v, self.alignment, self.llvmType) } /// Computes an address value for an `undef` pointer value to the underlying /// type of this type info object. /// /// - Returns: The address value of an `undef` pointer. func undefAddress() -> Address { return Address(PointerType(pointee: self.llvmType).undef(), self.alignment, self.llvmType) } } /// A refinement of `TypeInfo` for those types with a known internal layout. /// /// Implementing this protocol frees you from having to provide an `alignment` /// accessor. Types should implement the `fixedAlignment` accessor instead. protocol FixedTypeInfo: TypeInfo { /// The exact size of values of the underlying type. var fixedSize: Size { get } /// The exact alignment of values of the underlying type. var fixedAlignment: Alignment { get } /// Whether the underlying type is known to require no bits to represent. var isKnownEmpty: Bool { get } } extension FixedTypeInfo { var alignment: Alignment { return self.fixedAlignment } } extension FixedTypeInfo { func allocateStack(_ IGF: IRGenFunction, _ : GIRType) -> StackAddress { guard !self.isKnownEmpty else { return StackAddress(self.undefAddress()) } let alloca = IGF.B.createAlloca(self.llvmType, alignment: self.alignment) _ = IGF.B.createLifetimeStart(alloca, self.fixedSize) return StackAddress(alloca) } func deallocateStack(_ IGF: IRGenFunction, _ adr: StackAddress, _ : GIRType) { guard !self.isKnownEmpty else { return } _ = IGF.B.createLifetimeEnd(adr.address, self.fixedSize) } } // MARK: Loadable Type Info /// A refinement of `TypeInfo` that describes values where load and store are /// well-defined operations. protocol LoadableTypeInfo: FixedTypeInfo, Loadable, Aggregable { } /// The implementation of type info for an object with zero size and alignment. /// /// All operations on this type are a no-op. final class EmptyTypeInfo: LoadableTypeInfo { let fixedSize: Size = .zero let llvmType: IRType var fixedAlignment: Alignment { return Alignment.one } var isKnownEmpty: Bool { return true } init(_ ty: IRType) { self.llvmType = ty } func buildExplosionSchema(_ : Explosion.Schema.Builder) { } func buildAggregateLowering(_ : IRGenModule, _ : AggregateLowering.Builder, _ : Size) { } func explosionSize() -> Int { return 0 } func initialize(_ : IRGenFunction, _ : Explosion, _ : Address) { } func loadAsCopy(_ : IRGenFunction, _ : Address, _ : Explosion) { } func loadAsTake(_ : IRGenFunction, _ : Address, _ : Explosion) { } func copy(_ : IRGenFunction, _ : Explosion, _ : Explosion) { } func consume(_ : IRGenFunction, _ : Explosion) { } func reexplode(_ : IRGenFunction, _ : Explosion, _ : Explosion) { } func packIntoPayload(_ : IRGenFunction, _ : Payload, _ : Explosion, _ : Size) { } func unpackFromPayload(_ : IRGenFunction, _ : Payload, _ : Explosion, _ : Size) { } func destroy(_ : IRGenFunction, _ : Address, _ : GIRType) { } func assign(_ : IRGenFunction, _ : Explosion, _ : Address) { } func assignWithCopy(_ : IRGenFunction, _ : Address, _ : Address, _ : GIRType) { } } // MARK: Indirect Type Info /// A refinement of `TypeInfo` for types with an indirect representation. /// /// This can be useful in situations where an aggregate may not be entirely /// loadable, but still has a fixed layout. Note that `FixedTypeInfo` is not /// a requirement. protocol IndirectTypeInfo: TypeInfo { } extension IndirectTypeInfo { func buildExplosionSchema(_ schema: Explosion.Schema.Builder) { schema.append(.aggregate(self.llvmType, self.alignment)) } } // MARK: Runtime Type Info /// A refinement of `TypeInfo` for types that require the Silt runtime to /// manipulate their values. Very little static information is known about /// these types. protocol WitnessSizedTypeInfo: IndirectTypeInfo { } extension WitnessSizedTypeInfo { func allocateStack(_ IGF: IRGenFunction, _ T: GIRType) -> StackAddress { let alloca = IGF.GR.emitDynamicAlloca(T, "") IGF.B.createLifetimeStart(alloca.address) let ptrTy = PointerType(pointee: self.llvmType) let addr = IGF.B.createPointerBitCast(of: alloca.address, to: ptrTy) return alloca.withAddress(addr) } func deallocateStack(_ IGF: IRGenFunction, _ addr: StackAddress, _ type: GIRType) { IGF.B.createLifetimeEnd(addr.address) IGF.GR.emitDeallocateDynamicAlloca(addr) } func destroy(_ IGF: IRGenFunction, _ addr: Address, _ type: GIRType) { IGF.GR.emitDestroyCall(type, addr) } func assignWithCopy(_ IGF: IRGenFunction, _ dest: Address, _ src: Address, _ type: GIRType) { IGF.GR.emitAssignWithCopyCall(type, dest, src) } } // MARK: Data Type Info /// The concrete implementation of type information for a fixed-layout data /// type. final class FixedDataTypeTypeInfo: Strategizable, FixedTypeInfo { let llvmType: IRType let strategy: DataTypeStrategy let fixedSize: Size let fixedAlignment: Alignment var isKnownEmpty: Bool { return self.fixedSize == .zero } init(_ strategy: DataTypeStrategy, _ llvmType: StructType, _ size: Size, _ align: Alignment) { self.strategy = strategy self.fixedSize = size self.llvmType = llvmType self.fixedAlignment = align } func destroy(_ IGF: IRGenFunction, _ addr: Address, _ type: GIRType) { self.strategy.destroy(IGF, addr, type) } func assignWithCopy(_ IGF: IRGenFunction, _ dest: Address, _ src: Address, _ type: GIRType) { self.strategy.assignWithCopy(IGF, dest, src, type) } } /// The concrete implementation of type information for a loadable data /// type. final class LoadableDataTypeTypeInfo: Strategizable, LoadableTypeInfo { let strategy: DataTypeStrategy let fixedSize: Size let llvmType: IRType let fixedAlignment: Alignment init(_ strategy: DataTypeStrategy, _ llvmType: StructType, _ size: Size, _ align: Alignment) { self.strategy = strategy self.fixedSize = size self.llvmType = llvmType self.fixedAlignment = align } var isKnownEmpty: Bool { return self.fixedSize == .zero } func buildAggregateLowering(_ IGM: IRGenModule, _ builder: AggregateLowering.Builder, _ offset: Size) { self.strategy.buildAggregateLowering(IGM, builder, offset) } func copy(_ IGF: IRGenFunction, _ src: Explosion, _ dest: Explosion) { self.strategy.copy(IGF, src, dest) } func explosionSize() -> Int { return self.strategy.explosionSize() } func reexplode(_ IGF: IRGenFunction, _ src: Explosion, _ dest: Explosion) { return self.strategy.reexplode(IGF, src, dest) } func initialize(_ IGF: IRGenFunction, _ from: Explosion, _ addr: Address) { return self.strategy.initialize(IGF, from, addr) } func loadAsCopy(_ IGF: IRGenFunction, _ addr: Address, _ explosion: Explosion) { self.strategy.loadAsCopy(IGF, addr, explosion) } func loadAsTake(_ IGF: IRGenFunction, _ addr: Address, _ explosion: Explosion) { self.strategy.loadAsTake(IGF, addr, explosion) } func consume(_ IGF: IRGenFunction, _ explosion: Explosion) { self.strategy.consume(IGF, explosion) } func packIntoPayload(_ IGF: IRGenFunction, _ payload: Payload, _ source: Explosion, _ offset: Size) { self.strategy.packIntoPayload(IGF, payload, source, offset) } func unpackFromPayload(_ IGF: IRGenFunction, _ payload: Payload, _ destination: Explosion, _ offset: Size) { self.strategy.unpackFromPayload(IGF, payload, destination, offset) } func destroy(_ IGF: IRGenFunction, _ addr: Address, _ type: GIRType) { self.strategy.destroy(IGF, addr, type) } func assign(_ IGF: IRGenFunction, _ src: Explosion, _ dest: Address) { self.strategy.assign(IGF, src, dest) } func assignWithCopy(_ IGF: IRGenFunction, _ dest: Address, _ src: Address, _ type: GIRType) { self.strategy.assignWithCopy(IGF, dest, src, type) } } /// The concrete implementation of type information for a runtime-sized data /// type. final class DynamicDataTypeTypeInfo: Strategizable, WitnessSizedTypeInfo { let strategy: DataTypeStrategy let llvmType: IRType let alignment: Alignment init(_ strategy: DataTypeStrategy, _ irTy: IRType, _ align: Alignment) { self.strategy = strategy self.llvmType = irTy self.alignment = align } func buildExplosionSchema(_ schema: Explosion.Schema.Builder) { self.strategy.buildExplosionSchema(schema) } func allocateStack(_ IGF: IRGenFunction, _ T: GIRType) -> StackAddress { let alloca = IGF.GR.emitDynamicAlloca(T, "") IGF.B.createLifetimeStart(alloca.address) let ptrTy = PointerType(pointee: self.llvmType) let addr = IGF.B.createPointerBitCast(of: alloca.address, to: ptrTy) return alloca.withAddress(addr) } func deallocateStack(_ IGF: IRGenFunction, _ addr: StackAddress, _ type: GIRType) { IGF.B.createLifetimeEnd(addr.address) IGF.GR.emitDeallocateDynamicAlloca(addr) } func destroy(_ IGF: IRGenFunction, _ addr: Address, _ type: GIRType) { self.strategy.destroy(IGF, addr, type) } func assignWithCopy(_ IGF: IRGenFunction, _ dest: Address, _ src: Address, _ type: GIRType) { self.strategy.assignWithCopy(IGF, dest, src, type) } } // MARK: Heap Type Info /// A refinement of `TypeInfo` for types whose representation is a single /// heap pointer value. protocol HeapTypeInfo: LoadableTypeInfo, SingleScalarizable { } extension HeapTypeInfo { static var isPOD: Bool { return false } } /// The concrete implementation of type information for an object value managed /// by the Silt runtime. final class ManagedObjectTypeInfo: HeapTypeInfo { static let isPOD: Bool = false let fixedSize: Size let fixedAlignment: Alignment var isKnownEmpty: Bool { return false } var isPOD: Bool { return false } let llvmType: IRType init(_ storage: PointerType, _ size: Size, _ align: Alignment) { self.llvmType = storage self.fixedSize = size self.fixedAlignment = align } func explosionSize() -> Int { return 1 } func initialize(_ IGF: IRGenFunction, _ from: Explosion, _ addr: Address) { IGF.B.buildStore(from.claimSingle(), to: addr.address) } func loadAsCopy(_ IGF: IRGenFunction, _ addr: Address, _ explosion: Explosion) { let value = IGF.B.createLoad(addr) self.emitScalarRetain(IGF, value) explosion.append(value) } func loadAsTake(_ IGF: IRGenFunction, _ addr: Address, _ explosion: Explosion) { explosion.append(IGF.B.createLoad(addr)) } func copy(_ IGF: IRGenFunction, _ src: Explosion, _ dest: Explosion) { let value = src.claimSingle() self.emitScalarRetain(IGF, value) dest.append(value) } func consume(_ IGF: IRGenFunction, _ explosion: Explosion) { let value = explosion.claimSingle() self.emitScalarRelease(IGF, value) } func buildAggregateLowering(_ IGM: IRGenModule, _ lowering: AggregateLowering.Builder, _ offset: Size) { let end = offset + IGM.dataLayout.storeSize(of: self.llvmType) lowering.append(.concrete(type: self.llvmType, begin: offset, end: end)) } func reexplode(_ IGF: IRGenFunction, _ src: Explosion, _ dest: Explosion) { let size = self.explosionSize() src.transfer(into: dest, size) } func packIntoPayload(_ IGF: IRGenFunction, _ payload: Payload, _ source: Explosion, _ offset: Size) { payload.insertValue(IGF, source.claimSingle(), offset) } func unpackFromPayload(_ IGF: IRGenFunction, _ payload: Payload, _ destination: Explosion, _ offset: Size) { destination.append(payload.extractValue(IGF, self.llvmType, offset)) } func buildExplosionSchema(_ schema: Explosion.Schema.Builder) { schema.append(.scalar(self.llvmType)) } func destroy(_ IGF: IRGenFunction, _ addr: Address, _ type: GIRType) { let value = IGF.B.createLoad(addr, alignment: addr.alignment, name: "toDestroy") self.emitScalarRelease(IGF, value) } func assignWithCopy(_ IGF: IRGenFunction, _ dest: Address, _ src: Address, _ : GIRType) { let temp = Explosion() self.loadAsCopy(IGF, src, temp) self.assign(IGF, temp, dest) } } // MARK: Box Type Info /// A refinement of heap type information for a `Box`ed value. The underlying /// representation is opaque, and its lifetime is managed by the Silt /// runtime. Unlike a `ManagedObject` value, a box may only be manipulated /// indirectly: its address must be projected, and allocation and deallocation /// routines are provided by the Silt runtime. protocol BoxTypeInfo: HeapTypeInfo { /// Allocate a box of the given type. /// /// This function is used to implement the `alloc_box` instruction. /// /// - Parameters: /// - IGF: The IR Builder for the current function. /// - boxedType: The underlying type to allocate a box for. /// - Returns: An owned address value representing the address of /// the boxed value. func allocate(_ IGF: IRGenFunction, _ boxedType: GIRType) -> OwnedAddress /// Deallocate a box of the given type. /// /// This function is used to implement the `dealloc_box` instruction. /// /// - Parameters: /// - IGF: The IR Builder for the current function. /// - box: The box value. /// - boxedType: The underlying type to deallocate a box for. func deallocate(_ IGF: IRGenFunction, _ box: IRValue, _ boxedType: GIRType) /// Project the address value from a box. /// /// This function is used to implement the `project_box` instruction. /// /// - Parameters: /// - IGF: The IR Builder for the current function. /// - box: The box value. /// - boxedType: The underlying type to allocate a box for. /// - Returns: An address value describing the the projected value of the box. func project(_ IGF: IRGenFunction, _ box: IRValue, _ boxedType: GIRType) -> Address } extension BoxTypeInfo { func explosionSize() -> Int { return 1 } func initialize(_ IGF: IRGenFunction, _ from: Explosion, _ addr: Address) { IGF.B.buildStore(from.claimSingle(), to: addr.address) } func loadAsCopy(_ IGF: IRGenFunction, _ addr: Address, _ explosion: Explosion) { let value = IGF.B.createLoad(addr) self.emitScalarRetain(IGF, value) explosion.append(value) } func loadAsTake(_ IGF: IRGenFunction, _ addr: Address, _ explosion: Explosion) { explosion.append(IGF.B.createLoad(addr)) } func copy(_ IGF: IRGenFunction, _ src: Explosion, _ dest: Explosion) { let value = src.claimSingle() self.emitScalarRetain(IGF, value) dest.append(value) } func consume(_ IGF: IRGenFunction, _ explosion: Explosion) { let value = explosion.claimSingle() self.emitScalarRelease(IGF, value) } func buildAggregateLowering(_ IGM: IRGenModule, _ builder: AggregateLowering.Builder, _ offset: Size) { let end = offset + IGM.dataLayout.storeSize(of: self.llvmType) builder.append(.concrete(type: self.llvmType, begin: offset, end: end)) } func reexplode(_ IGF: IRGenFunction, _ src: Explosion, _ dest: Explosion) { let size = self.explosionSize() src.transfer(into: dest, size) } func packIntoPayload(_ IGF: IRGenFunction, _ payload: Payload, _ source: Explosion, _ offset: Size) { payload.insertValue(IGF, source.claimSingle(), offset) } func unpackFromPayload(_ IGF: IRGenFunction, _ payload: Payload, _ destination: Explosion, _ offset: Size) { destination.append(payload.extractValue(IGF, self.llvmType, offset)) } func buildExplosionSchema(_ schema: Explosion.Schema.Builder) { schema.append(.scalar(self.llvmType)) } func destroy(_ IGF: IRGenFunction, _ addr: Address, _ type: GIRType) { let value = IGF.B.createLoad(addr, alignment: addr.alignment, name: "toDestroy") self.emitScalarRelease(IGF, value) } func assignWithCopy(_ IGF: IRGenFunction, _ dest: Address, _ src: Address, _ : GIRType) { let temp = Explosion() self.loadAsCopy(IGF, src, temp) self.assign(IGF, temp, dest) } } /// Concrete type information for an empty boxed value. /// /// All operations on values of an empty box are implemented in terms /// of `undef`. final class EmptyBoxTypeInfo: BoxTypeInfo { let llvmType: IRType let fixedSize: Size let fixedAlignment: Alignment var isKnownEmpty: Bool { return false } var isPOD: Bool { return true } init(_ IGM: IRGenModule) { self.fixedSize = IGM.getPointerSize() self.fixedAlignment = IGM.getPointerAlignment() self.llvmType = IGM.refCountedPtrTy } func allocate(_ IGF: IRGenFunction, _ boxedType: GIRType) -> OwnedAddress { return OwnedAddress(IGF.getTypeInfo(boxedType).undefAddress(), IGF.emitAllocEmptyBoxCall()) } func deallocate(_ IGF: IRGenFunction, _ box: IRValue, _ boxedType: GIRType) { } func project(_ IGF: IRGenFunction, _ box: IRValue, _ boxedType: GIRType) -> Address { return IGF.getTypeInfo(boxedType).undefAddress() } } /// Provides type information about a boxed value where the underlying type has /// a fixed layout. /// /// In this case, we can often choose to skip a level of indirection and /// allocate the box header in-line with the data for the boxed value. final class FixedBoxTypeInfo: FixedHeapLayout, BoxTypeInfo { let llvmType: IRType let fixedSize: Size let fixedAlignment: Alignment let layout: RecordLayout var isKnownEmpty: Bool { return self.fixedSize == .zero } var isPOD: Bool { return false } init(_ IGM: IRGenModule, _ type: GIRType) { self.layout = RecordLayout(.heapObject, IGM, [type], [IGM.getTypeInfo(type)]) self.fixedSize = IGM.getPointerSize() self.fixedAlignment = IGM.getPointerAlignment() self.llvmType = IGM.refCountedPtrTy } } /// Provides type information about a boxed value where the underlying type /// has a dynamic layout. /// /// As the underlying value must be manipulated indirectly, the box is /// implemented as a reference-counted pointer. final class NonFixedBoxTypeInfo: BoxTypeInfo { let llvmType: IRType let fixedSize: Size let fixedAlignment: Alignment var isKnownEmpty: Bool { return false } var isPOD: Bool { return false } init(_ IGM: IRGenModule) { self.llvmType = IGM.refCountedPtrTy self.fixedSize = IGM.getPointerSize() self.fixedAlignment = IGM.getPointerAlignment() } func allocate(_ IGF: IRGenFunction, _ boxedType: GIRType) -> OwnedAddress { let ti = IGF.getTypeInfo(boxedType) let metadata = IGF.emitTypeMetadataRefForLayout(boxedType) let (box, address) = IGF.emitAllocBoxCall(metadata) let ptrTy = PointerType(pointee: ti.llvmType) let castAddr = IGF.B.createPointerBitCast(of: address, to: ptrTy) return OwnedAddress(castAddr, box) } func deallocate(_ IGF: IRGenFunction, _ box: IRValue, _ boxedType: GIRType) { let metadata = IGF.emitTypeMetadataRefForLayout(boxedType) IGF.emitDeallocBoxCall(box, metadata) } func project(_ IGF: IRGenFunction, _ box: IRValue, _ boxedType: GIRType) -> Address { let ti = IGF.getTypeInfo(boxedType) let metadata = IGF.emitTypeMetadataRefForLayout(boxedType) let address = IGF.B.buildBitCast(IGF.emitProjectBoxCall(box, metadata), type: PointerType(pointee: ti.llvmType)) return ti.address(for: address) } } // MARK: Function Type Info /// Provides type information for a function or function reference. /// /// FIXME: We currently assume that all functions are "thick" - that is, they /// consist of a function pointer and an environment pointer. In many cases, /// we can optimize this by providing "thin" single-scalar type information ' /// instead. final class FunctionTypeInfo: LoadableTypeInfo { let llvmType: IRType let fixedSize: Size let fixedAlignment: Alignment let formalType: Seismography.FunctionType init(_ IGM: IRGenModule, _ formalType: Seismography.FunctionType, _ storageType: IRType, _ size: Size, _ align: Alignment) { self.formalType = formalType self.llvmType = storageType self.fixedSize = size self.fixedAlignment = align } var isKnownEmpty: Bool { return self.fixedSize == .zero } func explosionSize() -> Int { return 2 } func initialize(_ IGF: IRGenFunction, _ from: Explosion, _ addr: Address) { // Store the function pointer. let fnAddr = self.projectFunction(IGF, addr) IGF.B.buildStore(from.claimSingle(), to: fnAddr.address, alignment: fnAddr.alignment) // Store the environment pointer. let envAddr = self.projectEnvironment(IGF, addr) let context = from.claimSingle() IGF.B.buildStore(context, to: envAddr.address, alignment: envAddr.alignment) } func loadAsCopy(_ IGF: IRGenFunction, _ addr: Address, _ explosion: Explosion) { let fnAddr = self.projectFunction(IGF, addr) let first = IGF.B.createLoad(fnAddr) explosion.append(first) let envAddr = self.projectEnvironment(IGF, addr) let second = IGF.B.createLoad(envAddr) explosion.append(second) } func loadAsTake(_ IGF: IRGenFunction, _ addr: Address, _ explosion: Explosion) { // Load the function. let fnAddr = self.projectFunction(IGF, addr) explosion.append(IGF.B.createLoad(fnAddr)) // Load the environment pointer. let dataAddr = self.projectEnvironment(IGF, addr) explosion.append(IGF.B.createLoad(dataAddr)) } func copy(_ IGF: IRGenFunction, _ src: Explosion, _ dest: Explosion) { src.transfer(into: dest, 1) let data = src.claimSingle() dest.append(data) } func consume(_ IGF: IRGenFunction, _ explosion: Explosion) { _ = explosion.claimSingle() _ = explosion.claimSingle() fatalError("Release the data pointer box!") } func reexplode(_ IGF: IRGenFunction, _ src: Explosion, _ dest: Explosion) { let size = self.explosionSize() src.transfer(into: dest, size) } func packIntoPayload(_ IGF: IRGenFunction, _ payload: Payload, _ src: Explosion, _ offset: Size) { payload.insertValue(IGF, src.claimSingle(), offset) payload.insertValue(IGF, src.claimSingle(), offset + IGF.IGM.getPointerSize()) } func unpackFromPayload(_ IGF: IRGenFunction, _ payload: Payload, _ destination: Explosion, _ offset: Size) { fatalError("Unimplemented") } func destroy(_ IGF: IRGenFunction, _ addr: Address, _ type: GIRType) { _ = IGF.B.createLoad(self.projectEnvironment(IGF, addr)) fatalError("Release the data pointer box!") } func assign(_ IGF: IRGenFunction, _ src: Explosion, _ dest: Address) { let firstAddr = projectFunction(IGF, dest) IGF.B.buildStore(src.claimSingle(), to: firstAddr.address) let secondAddr = projectEnvironment(IGF, dest) IGF.B.buildStore(src.claimSingle(), to: secondAddr.address) } func assignWithCopy(_ IGF: IRGenFunction, _ dest: Address, _ src: Address, _ T: GIRType) { let temp = Explosion() self.loadAsCopy(IGF, src, temp) self.assign(IGF, temp, dest) } func buildAggregateLowering(_ IGM: IRGenModule, _ builder: AggregateLowering.Builder, _ offset: Size) { let size = IGM.dataLayout.storeSize(of: self.llvmType) as Size builder.append(.concrete(type: self.llvmType, begin: offset, end: size)) } func buildExplosionSchema(_ schema: Explosion.Schema.Builder) { schema.append(.scalar(self.llvmType)) } private func projectFunction(_ IGF: IRGenFunction, _ address: Address) -> Address { return IGF.B.createStructGEP(address, 0, Size.zero, ".fn") } private func projectEnvironment(_ IGF: IRGenFunction, _ address: Address) -> Address { return IGF.B.createStructGEP(address, 1, IGF.IGM.getPointerSize(), ".data") } } // MARK: Generic Type Info /// Provides type information for a runtime-sized generic value. final class OpaqueArchetypeTypeInfo: WitnessSizedTypeInfo { let llvmType: IRType let alignment: Alignment init(_ storageType: IRType) { self.llvmType = storageType self.alignment = Alignment.one } } // MARK: Tuple Type Info protocol TupleTypeInfo: TypeInfo { var fields: [RecordField] { get } } extension TupleTypeInfo { func projectElementAddress( _ IGF: IRGenFunction, _ tuple: Address, _ type: GIRType, _ fieldNo: Int ) -> Address { let field = self.fields[fieldNo] guard !field.isEmpty else { return field.layout.typeInfo.undefAddress() } let offsets = (self as? DynamicOffsetable)?.dynamicOffsets(IGF, type) return field.projectAddress(IGF, tuple, offsets) } }
mit
9e0e376a5dd6e39d12393ea3d3838dc1
31.11716
94
0.667195
4.039744
false
false
false
false
silt-lang/silt
Sources/Seismography/Mangling.swift
1
1977
/// Mangling.swift /// /// Copyright 2018, The Silt Language Project. /// /// This project is released under the MIT license, a copy of which is /// available in the repository. public let MANGLING_PREFIX = "_S" internal let MAXIMUM_WORDS_CAPACITY = 26 internal enum ManglingScalars { static let NUL = UInt8(ascii: "\0") static let LOWERCASE_A = UInt8(ascii: "a") static let UPPERCASE_A = UInt8(ascii: "A") static let UPPERCASE_B = UInt8(ascii: "B") static let UPPERCASE_D = UInt8(ascii: "D") static let UPPERCASE_F = UInt8(ascii: "F") static let LOWERCASE_F = UInt8(ascii: "f") static let UPPERCASE_G = UInt8(ascii: "G") static let UPPERCASE_T = UInt8(ascii: "T") static let LOWERCASE_T = UInt8(ascii: "t") static let LOWERCASE_Y = UInt8(ascii: "y") static let LOWERCASE_Z = UInt8(ascii: "z") static let UPPERCASE_Z = UInt8(ascii: "Z") static let AMPERSAND = UInt8(ascii: "&") static let UNDERSCORE = UInt8(ascii: "_") static let DOLLARSIGN = UInt8(ascii: "$") static let ZERO = UInt8(ascii: "0") static let NINE = UInt8(ascii: "9") static func isEndOfWord(_ cur: UInt8, _ prev: UInt8) -> Bool { if cur == DOLLARSIGN || cur == NUL { return true } if !prev.isUpperLetter && cur.isUpperLetter { return true } return false } } extension UInt8 { var isLowerLetter: Bool { return self >= ManglingScalars.LOWERCASE_A && self <= ManglingScalars.LOWERCASE_Z } var isUpperLetter: Bool { return self >= ManglingScalars.UPPERCASE_A && self <= ManglingScalars.UPPERCASE_Z } var isDigit: Bool { return self >= ManglingScalars.ZERO && self <= ManglingScalars.NINE } var isLetter: Bool { return self.isLowerLetter || self.isUpperLetter } var isValidSymbol: Bool { return self < 0x80 } var isStartOfWord: Bool { return !(self.isDigit || self == ManglingScalars.DOLLARSIGN || self == ManglingScalars.NUL) } }
mit
6df009f6a559d4d53a96c71c86462559
23.109756
71
0.647446
3.284053
false
false
false
false
Tinkertanker/intro-coding-swift
7-1 Clinic Map/BMI Calculator/QuizTableViewController.swift
2
1966
// // QuizTableViewController.swift // // // Created by YJ Soon on 15/9/15. // // import UIKit class QuizTableViewController: UITableViewController { var data : NSArray? override func viewDidLoad() { super.viewDidLoad() let dataPath = NSBundle.mainBundle().pathForResource("Quiz", ofType: "plist") data = NSArray(contentsOfFile: dataPath!) title = "Healthy Quiz" } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } // MARK: - Table view data source override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return data!.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("reuseIdentifier", forIndexPath: indexPath) as! UITableViewCell // Configure the cell... let item : Dictionary = data!.objectAtIndex(indexPath.row) as! Dictionary<String, String> var question = item["question"] cell.textLabel!.text = question return cell } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == "segue" { let destination = segue.destinationViewController as? QuizViewController let row = tableView.indexPathForSelectedRow()?.row let item : Dictionary = data!.objectAtIndex(row!) as! Dictionary<String, String> var question = item["question"] destination!.question = question! destination!.option1 = item["option1"]! destination!.option2 = item["option2"]! destination!.option3 = item["option3"]! destination!.answer = item["answer"]! } } }
mit
fdd3bfc9a0ec7e42e2e3585f5ecdb9b0
30.709677
126
0.648525
5.284946
false
false
false
false
alessandrostone/Swift
CoreAnimationSample3/CoreAnimationSample3/ViewController.swift
27
3699
// // ViewController.swift // CoreAnimationSample3 // // Created by Carlos Butron on 02/12/14. // Copyright (c) 2015 Carlos Butron. All rights reserved. // // This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public // License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later // version. // This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied // warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. // You should have received a copy of the GNU General Public License along with this program. If not, see // http:/www.gnu.org/licenses/. // import UIKit class ViewController: UIViewController { var position = true @IBOutlet weak var image: UIImageView! @IBAction func animate(sender: UIButton) { if (position){ //SAMPLE2 var animation:CABasicAnimation! = CABasicAnimation(keyPath:"position") animation.toValue = NSValue(CGPoint:CGPointMake(160, 200)) //SAMPLE2 animation.fillMode = kCAFillModeForwards animation.removedOnCompletion = false var resizeAnimation:CABasicAnimation = CABasicAnimation(keyPath:"bounds.size") resizeAnimation.toValue = NSValue(CGSize:CGSizeMake(240, 60)) //SAMPLE2 resizeAnimation.fillMode = kCAFillModeForwards resizeAnimation.removedOnCompletion = false //SAMPLE3 UIView.animateWithDuration(5.0, animations:{ //PROPERTIES CHANGES TO ANIMATE self.image.alpha = 0.0 //alpha to zero in 5 seconds }, completion: {(value: Bool) in //when finished animation do this.. self.image.alpha = 1.0 self.image.layer.addAnimation(animation, forKey: "position") self.image.layer.addAnimation(resizeAnimation, forKey: "bounds.size") }) position = false } else{ var animation:CABasicAnimation! = CABasicAnimation(keyPath:"position") animation.fromValue = NSValue(CGPoint:CGPointMake(160, 200)) //SAMPLE2 animation.fillMode = kCAFillModeForwards animation.removedOnCompletion = false var resizeAnimation:CABasicAnimation = CABasicAnimation(keyPath:"bounds.size") resizeAnimation.fromValue = NSValue(CGSize:CGSizeMake(240, 60)) //SAMPLE2 resizeAnimation.fillMode = kCAFillModeForwards resizeAnimation.removedOnCompletion = false image.layer.addAnimation(animation, forKey: "position") image.layer.addAnimation(resizeAnimation, forKey: "bounds.size") position = true } } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
gpl-3.0
7b8a8b874952b168b6de5ae0e40f8f3c
32.324324
121
0.572587
5.899522
false
false
false
false
m7mdtareq/popular-movies-ios
Popular Movies/TMDBClient.swift
1
2770
// // TMDBClient.swift // Popular Movies // // Created by Mohamad Tarek on 28/6/17. // Copyright © 2017 Mohamad Tarek. All rights reserved. // import Foundation import Alamofire import AlamofireImage class TMDBClient: NSObject { // MARK: Initializers override init() { super.init() } // MARK: Functions func fetchMovies (completion: @escaping ([TMDBMovie]?) -> Void) { var parameters = [String:Any]() parameters [ParameterKeys.ApiKey] = Constants.ApiKey as Any Alamofire.request( tmdbURL(withPathExtension: Methods.GetPopular), method: .get, parameters: parameters) .validate() .responseJSON { (response) in guard response.result.isSuccess else { print("Error while fetching movies: \(String(describing: response.result.error))") completion(nil) return } guard let result = response.result.value as? [String: Any], let movies = result["results"] as? [[String: Any]] else { print("Malformed data received from fetchMovies service") completion(nil) return } let moviesArray = TMDBMovie.moviesFromResults(movies) completion(moviesArray) } } func fetchPoster (path: String, size: String, completion: @escaping (UIImage?) -> Void) { let baseURL: URL = URL(string: PosterConstants.secureBaseImageURLString)! let url = baseURL.appendingPathComponent(size).appendingPathComponent(path) Alamofire.request( url, method: .get) .responseImage { (response) in guard let image = response.result.value else { print("Error while fetching movies: \(String(describing: response.result.error))") completion(nil) return } completion(image) } } private func tmdbURL(withPathExtension: String? = nil) -> URL { var components = URLComponents() components.scheme = TMDBClient.Constants.ApiScheme components.host = TMDBClient.Constants.ApiHost components.path = TMDBClient.Constants.ApiPath + (withPathExtension ?? "") return components.url! } // MARK: Shared Instance class func sharedInstance() -> TMDBClient { struct Singleton { static var sharedInstance = TMDBClient() } return Singleton.sharedInstance } }
mit
72add72399bc815479f972bbd189fb61
30.11236
102
0.549296
5.274286
false
false
false
false
roecrew/AudioKit
AudioKit/Common/Playgrounds/Effects.playground/Pages/Costello Reverb.xcplaygroundpage/Contents.swift
1
2152
//: ## Sean Costello Reverb //: This is a great sounding reverb that we just love. import XCPlayground import AudioKit let file = try AKAudioFile(readFileName: processingPlaygroundFiles[0], baseDir: .Resources) let player = try AKAudioPlayer(file: file) player.looping = true var reverb = AKCostelloReverb(player) reverb.cutoffFrequency = 9900 // Hz reverb.feedback = 0.92 AudioKit.output = reverb AudioKit.start() player.play() //: User Interface Set up class PlaygroundView: AKPlaygroundView { var cutoffFrequencySlider: AKPropertySlider? var feedbackSlider: AKPropertySlider? override func setup() { addTitle("Sean Costello Reverb") addSubview(AKResourcesAudioFileLoaderView( player: player, filenames: processingPlaygroundFiles)) cutoffFrequencySlider = AKPropertySlider( property: "Cutoff Frequency", format: "%0.1f Hz", value: reverb.cutoffFrequency, maximum: 5000, color: AKColor.greenColor() ) { sliderValue in reverb.cutoffFrequency = sliderValue } addSubview(cutoffFrequencySlider!) feedbackSlider = AKPropertySlider( property: "Feedback", value: reverb.feedback, color: AKColor.redColor() ) { sliderValue in reverb.feedback = sliderValue } addSubview(feedbackSlider!) let presets = ["Short Tail", "Low Ringing Tail"] addSubview(AKPresetLoaderView(presets: presets) { preset in switch preset { case "Short Tail": reverb.presetShortTailCostelloReverb() case "Low Ringing Tail": reverb.presetLowRingingLongTailCostelloReverb() default: break } self.updateUI() } ) } func updateUI() { cutoffFrequencySlider?.value = reverb.cutoffFrequency feedbackSlider?.value = reverb.feedback } } XCPlaygroundPage.currentPage.needsIndefiniteExecution = true XCPlaygroundPage.currentPage.liveView = PlaygroundView()
mit
06fd7687b2b03c9951ea1d4a03e61176
26.948052
70
0.634758
5.185542
false
false
false
false
lyimin/iOS-Animation-Demo
iOS-Animation学习笔记/iOS-Animation学习笔记/ViewController.swift
1
3033
// // ViewController.swift // iOS-Animation学习笔记 // // Created by 梁亦明 on 15/12/22. // Copyright © 2015年 xiaoming. All rights reserved. // import UIKit class ViewController: UITableViewController { var titleArray : Array<String> = ["雪花粒子Demo","弹簧效果Demo","Twitter启动Demo","登陆动画Demo","引导页卡片Demo","扩大背景转场","SlidingPanels", "简书转场动画","进度条动画","音符加载动画"] var nameArray : Array<String> = Array() override func viewDidLoad() { super.viewDidLoad() self.view.backgroundColor = UIColor.white self.tableView.reloadData() } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.titleArray.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { var cell : UITableViewCell? = tableView.dequeueReusableCell(withIdentifier: "cellId") if cell == nil { cell = UITableViewCell(style: .default, reuseIdentifier: "cellId") } cell?.textLabel?.text = titleArray[indexPath.row] return cell! } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { var nextController : UIViewController! switch indexPath.row { case 0 : // 雪花demo nextController = EmitterViewController() case 1: // 弹簧Demo nextController = SpringAnimationViewController() case 2: // Twitter启动Demo nextController = SplashAnimiationController() case 3: // 登陆动画Demo nextController = LoginViewController() case 4: // 引导页卡片Demo nextController = TipFirstViewController() case 5: // 扩大背景转场 nextController = PingFirstController() case 6: // SlidingPanels nextController = RoomsViewController() nextController.view.backgroundColor = UIColor.orange nextController.title = titleArray[indexPath.row] self.present(nextController, animated: true, completion: nil) return case 7: // 简书转场动画 nextController = JSFirstViewController() case 8: // 进度条动画 nextController = ProgressAnimationController() case 9: // 音符加载 nextController = MusicIndicatorViewController() default: break; } nextController.view.backgroundColor = UIColor.orange nextController.title = titleArray[indexPath.row] self.navigationController?.pushViewController(nextController, animated: true) } }
mit
e7f52bf192502459f5b87d0c24890dbe
34.308642
151
0.584965
5.416667
false
false
false
false
frtlupsvn/Vietnam-To-Go
VietNamToGo/DPDUIView+Extension.swift
4
1411
// // UIView+Constraints.swift // DropDown // // Created by Kevin Hirsch on 28/07/15. // Copyright (c) 2015 Kevin Hirsch. All rights reserved. // import UIKit //MARK: - Constraints internal extension UIView { func addConstraints(format format: String, options: NSLayoutFormatOptions = [], metrics: [String: AnyObject]? = nil, views: [String: UIView]) { addConstraints(NSLayoutConstraint.constraintsWithVisualFormat(format, options: options, metrics: metrics, views: views)) } func addUniversalConstraints(format format: String, options: NSLayoutFormatOptions = [], metrics: [String: AnyObject]? = nil, views: [String: UIView]) { addConstraints(format: "H:\(format)", options: options, metrics: metrics, views: views) addConstraints(format: "V:\(format)", options: options, metrics: metrics, views: views) } } //MARK: - Bounds internal extension UIView { var windowFrame: CGRect? { return superview?.convertRect(frame, toView: nil) } } internal extension UIWindow { static func visibleWindow() -> UIWindow? { var currentWindow = UIApplication.sharedApplication().keyWindow if currentWindow == nil { let frontToBackWindows = Array(UIApplication.sharedApplication().windows.reverse()) for window in frontToBackWindows { if window.windowLevel == UIWindowLevelNormal { currentWindow = window break } } } return currentWindow } }
mit
5e2df0c5eed6a92fa20dca04dce7cad6
23.77193
153
0.712261
4.078035
false
false
false
false
pman215/ToastNotifications
ToastNotifications/NotificationView.swift
1
3814
// // NotificationView.swift // ToastNotifications // // Created by pman215 on 11/14/16. // Copyright © 2016 Erick Andrade. All rights reserved. // import Foundation import UIKit class NotificationView: UIView { fileprivate let notification: Notification fileprivate lazy var animator: SequenceViewAnimator = { let transition = self.notification.animation.transition let showAnimations = self.notification.animation.showAnimations.map { ViewAnimationTask(view: self, animation: $0) } let hideAnimations = self.notification.animation.hideAnimations.map { ViewAnimationTask(view: self, animation: $0) } var animator = SequenceViewAnimator(transition: transition, showAnimations: showAnimations, hideAnimations: hideAnimations) animator.delegate = self return animator }() init(notification: Notification) { self.notification = notification super.init(frame: .zero) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func configure(with superview: UIView) { buildContentView() buildStyle(with: superview) } func show() { animator.show() } func hide() { animator.hide() } } private extension NotificationView { func buildContentView() { let contentView = ToastNotifications.convert(content: notification.content) addSubview(contentView) translatesAutoresizingMaskIntoConstraints = false let width = NSLayoutConstraint(item: contentView, attribute: .width, relatedBy: .equal, toItem: self, attribute: .width, multiplier: 1.0, constant: 0) let height = NSLayoutConstraint(item: contentView, attribute: .height, relatedBy: .equal, toItem: self, attribute: .height, multiplier: 1.0, constant: 0.0) let centerX = NSLayoutConstraint(item: contentView, attribute: .centerX, relatedBy: .equal, toItem: self, attribute: .centerX, multiplier: 1.0, constant: 0.0) let centerY = NSLayoutConstraint(item: contentView, attribute: .centerY, relatedBy: .equal, toItem: self, attribute: .centerY, multiplier: 1.0, constant: 0.0) NSLayoutConstraint.activate([width,height,centerX,centerY]) } func buildStyle(with view: UIView) { isHidden = true view.addSubview(self) view.bringSubview(toFront: self) notification.appearance.configure(with: self) } } extension NotificationView: SequenceViewAnimatorDelegate { func willShow() { } func didShow() { } func willHide() { } func didHide() { removeFromSuperview() notification.didHide() } }
mit
1800697d779ef809cda56cf3f55a5ac9
28.55814
83
0.484395
6.2
false
false
false
false
invalidstream/cocoaconfrevengeofthe80s
DuranDuranFans/DuranDuranFans/Fan.swift
1
3423
// // Fan.swift // DuranDuranFans // // Created by Chris Adamson on 3/27/15. // Copyright (c) 2015 Subsequently & Furthermore, Inc. All rights reserved. // import Cocoa let FAN_UTI = "com.subfurther.cocoaconf.80s.fan" // needs NSPasteboardWriting, NSPasteboardReading class Fan : NSObject, NSCoding, NSPasteboardWriting, NSPasteboardReading { var firstName: String? var lastName: String? var favoriteSong: String? init (firstName: String?, lastName: String?, favoriteSong: String?) { self.firstName = firstName self.lastName = lastName self.favoriteSong = favoriteSong } func fullName() -> String { let first = firstName != nil ? firstName! : "" let last = lastName != nil ? lastName! : "" return "\(first) \(last)" } // MARK - NSCoding func encodeWithCoder(aCoder: NSCoder) { aCoder.encodeObject(firstName, forKey: "firstName") aCoder.encodeObject(lastName, forKey: "lastName") aCoder.encodeObject(favoriteSong, forKey: "favoriteSong") } required init(coder aDecoder: NSCoder) { firstName = aDecoder.decodeObjectForKey("firstName") as String? lastName = aDecoder.decodeObjectForKey("lastName") as String? favoriteSong = aDecoder.decodeObjectForKey("favoriteSong") as String? } // MARK - NSPasteboardWriting func writableTypesForPasteboard(pasteboard: NSPasteboard!) -> [AnyObject]! { return [FAN_UTI, NSPasteboardTypeString] } func pasteboardPropertyListForType(type: String!) -> AnyObject! { switch type { case NSPasteboardTypeString: return fullName() case FAN_UTI: let data = NSMutableData() let archiver = NSKeyedArchiver(forWritingWithMutableData: data) archiver.encodeObject(firstName, forKey: "firstName") archiver.encodeObject(lastName, forKey: "lastName") archiver.encodeObject(favoriteSong, forKey: "favoriteSong") archiver.finishEncoding() return data default: return nil } } // MARK - NSPasteboardReading class func readableTypesForPasteboard(pasteboard: NSPasteboard!) -> [AnyObject]! { return [FAN_UTI] } required init?(pasteboardPropertyList propertyList: AnyObject!, ofType type: String!) { super.init() // fixes "all stored properties of a class instance must be initialized before returning nil from an initializer" switch type { case NSPasteboardTypeString: return nil case FAN_UTI: if let data = propertyList as? NSData { let unarchiver = NSKeyedUnarchiver(forReadingWithData: data) self.firstName = unarchiver.decodeObjectForKey("firstName") as String? self.lastName = unarchiver.decodeObjectForKey("lastName") as String? self.favoriteSong = unarchiver.decodeObjectForKey("favoriteSong") as String? } default: return nil // die } } // MARK - helpers func description() -> String { if firstName != nil && lastName != nil && favoriteSong != nil { return "\(firstName!) \(lastName!), likes \(favoriteSong!)" } else { return "\(firstName) \(lastName), \(favoriteSong)" } } }
cc0-1.0
a492fe745091d0efe973ca62c358d0e1
33.928571
134
0.624306
5.033824
false
false
false
false
treasure-data/td-ios-sdk
TreasureDataExampleSwift/TreasureDataExampleSwift/AppDelegate.swift
1
3810
// // AppDelegate.swift // TreasureDataExampleSwift // // Created by Mitsunori Komatsu on 1/2/16. // Copyright © 2016 Treasure Data. All rights reserved. // import UIKit import TreasureData_iOS_SDK @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool { TreasureData.enableLogging() // TreasureData.initializeApiEndpoint("https://in.ybi.idcfcloud.net") TreasureData.initializeEncryptionKey("hello world") TreasureData.initialize(withApiKey: "your_api_key") TreasureData.sharedInstance().defaultDatabase = "testdb" TreasureData.sharedInstance().enableAutoAppendUniqId() TreasureData.sharedInstance().enableAutoAppendModelInformation() TreasureData.sharedInstance().disableRetryUploading() TreasureData.sharedInstance().startSession("demotbl") TreasureData.sharedInstance().enableAppLifecycleEvent() if (TreasureData.sharedInstance().isFirstRun()) { TreasureData.sharedInstance().addEvent( withCallback: ["event": "installed"], database: "testdb", table: "demotbl", onSuccess:{()-> Void in TreasureData.sharedInstance().clearFirstRun() }, onError:{(errorCode, message) -> Void in print("addEvent: error. errorCode=%@, message=%@", errorCode, message ?? "") }) } 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) { TreasureData.sharedInstance().endSession("demotbl") let application = UIApplication.shared var bgTask : UIBackgroundTaskIdentifier = UIBackgroundTaskIdentifier(rawValue: 0) bgTask = application.beginBackgroundTask(expirationHandler: { application.endBackgroundTask(bgTask) bgTask = UIBackgroundTaskIdentifier.invalid }) TreasureData.sharedInstance().uploadEvents(callback: { application.endBackgroundTask(bgTask) bgTask = UIBackgroundTaskIdentifier.invalid }, onError: {(errorCode, message) -> Void in print("uploadEvents: error. errorCode=%@, message=%@", errorCode, message ?? "") application.endBackgroundTask(bgTask) bgTask = UIBackgroundTaskIdentifier.invalid }) } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
apache-2.0
7bdf20f1dcaae023a58264ca5b601f9c
46.6125
285
0.685219
5.544396
false
false
false
false
p-rothen/PRViews
PRViews/PRTextField.swift
1
1581
// // PRTextField.swift // Doctor Cloud // // Created by Pedro on 14-12-16. // Copyright © 2016 IQS. All rights reserved. // import UIKit public class PRTextField: UITextField { let padding = UIEdgeInsets(top: 0, left: 8, bottom: 0, right: 8); let customBackgroundColor = UIColor(red:0.96, green:0.96, blue:0.98, alpha:1.0) let customTextColor = UIColor(red:0.29, green:0.29, blue:0.29, alpha:1.0) public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) //self.borderStyle = .None self.layer.borderWidth = 2 self.layer.cornerRadius = 3; self.layer.borderColor = self.customBackgroundColor.CGColor self.backgroundColor = self.customBackgroundColor self.textColor = customTextColor self.tintColor = customTextColor ViewUtils.addLightShadow(self) let constraintHeight = NSLayoutConstraint(item: self, attribute: .Height, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, multiplier: 1, constant: 50) constraintHeight.priority = 999 constraintHeight.active = true } public override func textRectForBounds(bounds: CGRect) -> CGRect { return UIEdgeInsetsInsetRect(bounds, self.padding) } public override func placeholderRectForBounds(bounds: CGRect) -> CGRect { return UIEdgeInsetsInsetRect(bounds, self.padding) } public override func editingRectForBounds(bounds: CGRect) -> CGRect { return UIEdgeInsetsInsetRect(bounds, self.padding) } }
mit
0d489edfda9820f5534e8c53431a9e18
34.111111
170
0.673418
4.340659
false
false
false
false
huonw/swift
test/SILGen/if_while_binding.swift
3
16183
// RUN: %target-swift-emit-silgen -module-name if_while_binding -Xllvm -sil-full-demangle -enable-sil-ownership %s | %FileCheck %s func foo() -> String? { return "" } func bar() -> String? { return "" } func a(_ x: String) {} func b(_ x: String) {} func c(_ x: String) {} func marker_1() {} func marker_2() {} func marker_3() {} // CHECK-LABEL: sil hidden @$S16if_while_binding0A8_no_else{{[_0-9a-zA-Z]*}}F func if_no_else() { // CHECK: [[FOO:%.*]] = function_ref @$S16if_while_binding3fooSSSgyF // CHECK: [[OPT_RES:%.*]] = apply [[FOO]]() // CHECK: switch_enum [[OPT_RES]] : $Optional<String>, case #Optional.some!enumelt.1: [[YES:bb[0-9]+]], case #Optional.none!enumelt: [[NO:bb[0-9]+]] // // CHECK: [[NO]]: // CHECK: br [[CONT:bb[0-9]+]] if let x = foo() { // CHECK: [[YES]]([[VAL:%[0-9]+]] : @owned $String): // CHECK: [[BORROWED_VAL:%.*]] = begin_borrow [[VAL]] // CHECK: [[A:%.*]] = function_ref @$S16if_while_binding1a // CHECK: apply [[A]]([[BORROWED_VAL]]) // CHECK: end_borrow [[BORROWED_VAL]] from [[VAL]] // CHECK: destroy_value [[VAL]] // CHECK: br [[CONT]] a(x) } // CHECK: [[CONT]]: // CHECK-NEXT: tuple () } // CHECK: } // end sil function '$S16if_while_binding0A8_no_else{{[_0-9a-zA-Z]*}}F' // CHECK-LABEL: sil hidden @$S16if_while_binding0A11_else_chainyyF : $@convention(thin) () -> () { func if_else_chain() { // CHECK: [[FOO:%.*]] = function_ref @$S16if_while_binding3foo{{[_0-9a-zA-Z]*}}F // CHECK-NEXT: [[OPT_RES:%.*]] = apply [[FOO]]() // CHECK-NEXT: switch_enum [[OPT_RES]] : $Optional<String>, case #Optional.some!enumelt.1: [[YESX:bb[0-9]+]], case #Optional.none!enumelt: [[NOX:bb[0-9]+]] if let x = foo() { // CHECK: [[NOX]]: // CHECK: br [[FAILURE_DESTX:bb[0-9]+]] // // CHECK: [[YESX]]([[VAL:%[0-9]+]] : @owned $String): // CHECK: debug_value [[VAL]] : $String, let, name "x" // CHECK: [[BORROWED_VAL:%.*]] = begin_borrow [[VAL]] // CHECK: [[A:%.*]] = function_ref @$S16if_while_binding1a // CHECK: apply [[A]]([[BORROWED_VAL]]) // CHECK: end_borrow [[BORROWED_VAL]] from [[VAL]] // CHECK: destroy_value [[VAL]] // CHECK: br [[CONT_X:bb[0-9]+]] a(x) // // CHECK: [[FAILURE_DESTX]]: // CHECK: alloc_box ${ var String }, var, name "y" // CHECK: switch_enum {{.*}} : $Optional<String>, case #Optional.some!enumelt.1: [[YESY:bb[0-9]+]], case #Optional.none!enumelt: [[ELSE1:bb[0-9]+]] // CHECK: [[ELSE1]]: // CHECK: dealloc_box {{.*}} ${ var String } // CHECK: br [[ELSE:bb[0-9]+]] } else if var y = bar() { // CHECK: [[YESY]]([[VAL:%[0-9]+]] : @owned $String): // CHECK: br [[CONT_Y:bb[0-9]+]] // CHECK: [[CONT_Y]]: // CHECK: br [[CONT_Y2:bb[0-9]+]] b(y) } else { // CHECK: [[ELSE]]: // CHECK: function_ref if_while_binding.c c("") // CHECK: br [[CONT_Y2]] } // CHECK: [[CONT_Y2]]: // br [[CONT_X]] // CHECK: [[CONT_X]]: } // CHECK-LABEL: sil hidden @$S16if_while_binding0B5_loopyyF : $@convention(thin) () -> () { func while_loop() { // CHECK: br [[LOOP_ENTRY:bb[0-9]+]] // // CHECK: [[LOOP_ENTRY]]: // CHECK: switch_enum {{.*}} : $Optional<String>, case #Optional.some!enumelt.1: [[LOOP_BODY:bb[0-9]+]], case #Optional.none!enumelt: [[NO_TRAMPOLINE:bb[0-9]+]] // // CHECK: [[NO_TRAMPOLINE]]: // CHECK: br [[LOOP_EXIT:bb[0-9]+]] while let x = foo() { // CHECK: [[LOOP_BODY]]([[X:%[0-9]+]] : @owned $String): // CHECK: switch_enum {{.*}} : $Optional<String>, case #Optional.some!enumelt.1: [[YES:bb[0-9]+]], case #Optional.none!enumelt: [[NO_TRAMPOLINE_2:bb[0-9]+]] // // CHECK: [[NO_TRAMPOLINE_2]]: // CHECK: br [[FAILURE_DEST_2:bb[0-9]+]] if let y = bar() { // CHECK: [[YES]]([[Y:%[0-9]+]] : @owned $String): a(y) break // CHECK: destroy_value [[Y]] // CHECK: destroy_value [[X]] // CHECK: br [[LOOP_EXIT]] } // CHECK: [[FAILURE_DEST_2]]: // CHECK: destroy_value [[X]] // CHECK: br [[LOOP_ENTRY]] } // CHECK: [[LOOP_EXIT]]: // CHECK-NEXT: tuple () // CHECK-NEXT: return } // Don't leak alloc_stacks for address-only conditional bindings in 'while'. // <rdar://problem/16202294> // CHECK-LABEL: sil hidden @$S16if_while_binding0B13_loop_generic{{[_0-9a-zA-Z]*}}F // CHECK: br [[COND:bb[0-9]+]] // CHECK: [[COND]]: // CHECK: [[X:%.*]] = alloc_stack $T, let, name "x" // CHECK: [[OPTBUF:%[0-9]+]] = alloc_stack $Optional<T> // CHECK: switch_enum_addr {{.*}}, case #Optional.some!enumelt.1: [[LOOPBODY:bb.*]], case #Optional.none!enumelt: [[OUT:bb[0-9]+]] // CHECK: [[OUT]]: // CHECK: dealloc_stack [[OPTBUF]] // CHECK: dealloc_stack [[X]] // CHECK: br [[DONE:bb[0-9]+]] // CHECK: [[LOOPBODY]]: // CHECK: [[ENUMVAL:%.*]] = unchecked_take_enum_data_addr // CHECK: copy_addr [take] [[ENUMVAL]] to [initialization] [[X]] // CHECK: destroy_addr [[X]] // CHECK: dealloc_stack [[X]] // CHECK: br [[COND]] // CHECK: [[DONE]]: // CHECK: return // CHECK: } // end sil function '$S16if_while_binding0B13_loop_generic{{[_0-9a-zA-Z]*}}F' func while_loop_generic<T>(_ source: () -> T?) { while let x = source() { } } // <rdar://problem/19382942> Improve 'if let' to avoid optional pyramid of doom // CHECK-LABEL: sil hidden @$S16if_while_binding0B11_loop_multiyyF func while_loop_multi() { // CHECK: br [[LOOP_ENTRY:bb[0-9]+]] // CHECK: [[LOOP_ENTRY]]: // CHECK: switch_enum {{.*}}, case #Optional.some!enumelt.1: [[CHECKBUF2:bb.*]], case #Optional.none!enumelt: [[NONE_TRAMPOLINE:bb[0-9]+]] // // CHECK: [[NONE_TRAMPOLINE]]: // CHECK: br [[LOOP_EXIT0:bb[0-9]+]] // CHECK: [[CHECKBUF2]]([[A:%[0-9]+]] : @owned $String): // CHECK: debug_value [[A]] : $String, let, name "a" // CHECK: switch_enum {{.*}}, case #Optional.some!enumelt.1: [[LOOP_BODY:bb.*]], case #Optional.none!enumelt: [[LOOP_EXIT2a:bb[0-9]+]] // CHECK: [[LOOP_EXIT2a]]: // CHECK: destroy_value [[A]] // CHECK: br [[LOOP_EXIT0]] // CHECK: [[LOOP_BODY]]([[B:%[0-9]+]] : @owned $String): while let a = foo(), let b = bar() { // CHECK: debug_value [[B]] : $String, let, name "b" // CHECK: [[BORROWED_A:%.*]] = begin_borrow [[A]] // CHECK: [[A_COPY:%.*]] = copy_value [[BORROWED_A]] // CHECK: debug_value [[A_COPY]] : $String, let, name "c" // CHECK: end_borrow [[BORROWED_A]] from [[A]] // CHECK: destroy_value [[A_COPY]] // CHECK: destroy_value [[B]] // CHECK: destroy_value [[A]] // CHECK: br [[LOOP_ENTRY]] let c = a } // CHECK: [[LOOP_EXIT0]]: // CHECK-NEXT: tuple () // CHECK-NEXT: return } // CHECK-LABEL: sil hidden @$S16if_while_binding0A6_multiyyF func if_multi() { // CHECK: switch_enum {{.*}}, case #Optional.some!enumelt.1: [[CHECKBUF2:bb.*]], case #Optional.none!enumelt: [[NONE_TRAMPOLINE:bb[0-9]+]] // // CHECK: [[NONE_TRAMPOLINE]]: // CHECK: br [[IF_DONE:bb[0-9]+]] // CHECK: [[CHECKBUF2]]([[A:%[0-9]+]] : @owned $String): // CHECK: debug_value [[A]] : $String, let, name "a" // CHECK: [[B:%[0-9]+]] = alloc_box ${ var String }, var, name "b" // CHECK: [[PB:%[0-9]+]] = project_box [[B]] // CHECK: switch_enum {{.*}}, case #Optional.some!enumelt.1: [[IF_BODY:bb.*]], case #Optional.none!enumelt: [[IF_EXIT1a:bb[0-9]+]] // CHECK: [[IF_EXIT1a]]: // CHECK: dealloc_box {{.*}} ${ var String } // CHECK: destroy_value [[A]] // CHECK: br [[IF_DONE]] // CHECK: [[IF_BODY]]([[BVAL:%[0-9]+]] : @owned $String): if let a = foo(), var b = bar() { // CHECK: store [[BVAL]] to [init] [[PB]] : $*String // CHECK: debug_value {{.*}} : $String, let, name "c" // CHECK: destroy_value [[B]] // CHECK: destroy_value [[A]] // CHECK: br [[IF_DONE]] let c = a } // CHECK: [[IF_DONE]]: // CHECK-NEXT: tuple () // CHECK-NEXT: return } // CHECK-LABEL: sil hidden @$S16if_while_binding0A11_multi_elseyyF func if_multi_else() { // CHECK: switch_enum {{.*}}, case #Optional.some!enumelt.1: [[CHECKBUF2:bb.*]], case #Optional.none!enumelt: [[NONE_TRAMPOLINE:bb[0-9]+]] // // CHECK: [[NONE_TRAMPOLINE]]: // CHECK: br [[ELSE:bb[0-9]+]] // CHECK: [[CHECKBUF2]]([[A:%[0-9]+]] : @owned $String): // CHECK: debug_value [[A]] : $String, let, name "a" // CHECK: [[B:%[0-9]+]] = alloc_box ${ var String }, var, name "b" // CHECK: [[PB:%[0-9]+]] = project_box [[B]] // CHECK: switch_enum {{.*}}, case #Optional.some!enumelt.1: [[IF_BODY:bb.*]], case #Optional.none!enumelt: [[IF_EXIT1a:bb[0-9]+]] // CHECK: [[IF_EXIT1a]]: // CHECK: dealloc_box {{.*}} ${ var String } // CHECK: destroy_value [[A]] // CHECK: br [[ELSE]] // CHECK: [[IF_BODY]]([[BVAL:%[0-9]+]] : @owned $String): if let a = foo(), var b = bar() { // CHECK: store [[BVAL]] to [init] [[PB]] : $*String // CHECK: debug_value {{.*}} : $String, let, name "c" // CHECK: destroy_value [[B]] // CHECK: destroy_value [[A]] // CHECK: br [[IF_DONE:bb[0-9]+]] let c = a } else { let d = 0 // CHECK: [[ELSE]]: // CHECK: debug_value {{.*}} : $Int, let, name "d" // CHECK: br [[IF_DONE]] } // CHECK: [[IF_DONE]]: // CHECK-NEXT: tuple () // CHECK-NEXT: return } // CHECK-LABEL: sil hidden @$S16if_while_binding0A12_multi_whereyyF func if_multi_where() { // CHECK: switch_enum {{.*}}, case #Optional.some!enumelt.1: [[CHECKBUF2:bb.*]], case #Optional.none!enumelt: [[NONE_TRAMPOLINE:bb[0-9]+]] // // CHECK: [[NONE_TRAMPOLINE]]: // CHECK: br [[ELSE:bb[0-9]+]] // CHECK: [[CHECKBUF2]]([[A:%[0-9]+]] : @owned $String): // CHECK: debug_value [[A]] : $String, let, name "a" // CHECK: [[BBOX:%[0-9]+]] = alloc_box ${ var String }, var, name "b" // CHECK: [[PB:%[0-9]+]] = project_box [[BBOX]] // CHECK: switch_enum {{.*}}, case #Optional.some!enumelt.1: [[CHECK_WHERE:bb.*]], case #Optional.none!enumelt: [[IF_EXIT1a:bb[0-9]+]] // CHECK: [[IF_EXIT1a]]: // CHECK: dealloc_box {{.*}} ${ var String } // CHECK: destroy_value [[A]] // CHECK: br [[ELSE]] // CHECK: [[CHECK_WHERE]]([[B:%[0-9]+]] : @owned $String): // CHECK: function_ref Swift.Bool._getBuiltinLogicValue() -> Builtin.Int1 // CHECK: cond_br {{.*}}, [[IF_BODY:bb[0-9]+]], [[IF_EXIT3:bb[0-9]+]] // CHECK: [[IF_EXIT3]]: // CHECK: destroy_value [[BBOX]] // CHECK: destroy_value [[A]] // CHECK: br [[IF_DONE:bb[0-9]+]] if let a = foo(), var b = bar(), a == b { // CHECK: [[IF_BODY]]: // CHECK: destroy_value [[BBOX]] // CHECK: destroy_value [[A]] // CHECK: br [[IF_DONE]] let c = a } // CHECK: [[IF_DONE]]: // CHECK-NEXT: tuple () // CHECK-NEXT: return } // <rdar://problem/19797158> Swift 1.2's "if" has 2 behaviors. They could be unified. // CHECK-LABEL: sil hidden @$S16if_while_binding0A16_leading_booleanyySiF func if_leading_boolean(_ a : Int) { // Test the boolean condition. // CHECK: debug_value %0 : $Int, let, name "a" // CHECK: [[EQRESULT:%[0-9]+]] = apply {{.*}}(%0, %0{{.*}}) : $@convention({{.*}}) (Int, Int{{.*}}) -> Bool // CHECK: [[FN:%.*]] = function_ref {{.*}} // CHECK-NEXT: [[EQRESULTI1:%[0-9]+]] = apply [[FN:%.*]]([[EQRESULT]]) : $@convention(method) (Bool) -> Builtin.Int1 // CHECK-NEXT: cond_br [[EQRESULTI1]], [[CHECKFOO:bb[0-9]+]], [[IFDONE:bb[0-9]+]] // Call Foo and test for the optional being present. // CHECK: [[CHECKFOO]]: // CHECK: [[OPTRESULT:%[0-9]+]] = apply {{.*}}() : $@convention(thin) () -> @owned Optional<String> // CHECK: switch_enum [[OPTRESULT]] : $Optional<String>, case #Optional.some!enumelt.1: [[SUCCESS:bb.*]], case #Optional.none!enumelt: [[IF_DONE:bb[0-9]+]] // CHECK: [[SUCCESS]]([[B:%[0-9]+]] : @owned $String): // CHECK: debug_value [[B]] : $String, let, name "b" // CHECK: [[BORROWED_B:%.*]] = begin_borrow [[B]] // CHECK: [[B_COPY:%.*]] = copy_value [[BORROWED_B]] // CHECK: debug_value [[B_COPY]] : $String, let, name "c" // CHECK: end_borrow [[BORROWED_B]] from [[B]] // CHECK: destroy_value [[B_COPY]] // CHECK: destroy_value [[B]] // CHECK: br [[IFDONE]] if a == a, let b = foo() { let c = b } // CHECK: [[IFDONE]]: // CHECK-NEXT: tuple () } /// <rdar://problem/20364869> Assertion failure when using 'as' pattern in 'if let' class BaseClass {} class DerivedClass : BaseClass {} // CHECK-LABEL: sil hidden @$S16if_while_binding20testAsPatternInIfLetyyAA9BaseClassCSgF func testAsPatternInIfLet(_ a : BaseClass?) { // CHECK: bb0([[ARG:%.*]] : @guaranteed $Optional<BaseClass>): // CHECK: debug_value [[ARG]] : $Optional<BaseClass>, let, name "a" // CHECK: [[ARG_COPY:%.*]] = copy_value [[ARG]] : $Optional<BaseClass> // CHECK: switch_enum [[ARG_COPY]] : $Optional<BaseClass>, case #Optional.some!enumelt.1: [[OPTPRESENTBB:bb[0-9]+]], case #Optional.none!enumelt: [[NILBB:bb[0-9]+]] // CHECK: [[NILBB]]: // CHECK: br [[EXITBB:bb[0-9]+]] // CHECK: [[OPTPRESENTBB]]([[CLS:%.*]] : @owned $BaseClass): // CHECK: checked_cast_br [[CLS]] : $BaseClass to $DerivedClass, [[ISDERIVEDBB:bb[0-9]+]], [[ISBASEBB:bb[0-9]+]] // CHECK: [[ISDERIVEDBB]]([[DERIVED_CLS:%.*]] : @owned $DerivedClass): // CHECK: [[DERIVED_CLS_SOME:%.*]] = enum $Optional<DerivedClass>, #Optional.some!enumelt.1, [[DERIVED_CLS]] : $DerivedClass // CHECK: br [[MERGE:bb[0-9]+]]([[DERIVED_CLS_SOME]] : $Optional<DerivedClass>) // CHECK: [[ISBASEBB]]([[BASECLASS:%.*]] : @owned $BaseClass): // CHECK: destroy_value [[BASECLASS]] : $BaseClass // CHECK: = enum $Optional<DerivedClass>, #Optional.none!enumelt // CHECK: br [[MERGE]]( // CHECK: [[MERGE]]([[OPTVAL:%[0-9]+]] : @owned $Optional<DerivedClass>): // CHECK: switch_enum [[OPTVAL]] : $Optional<DerivedClass>, case #Optional.some!enumelt.1: [[ISDERIVEDBB:bb[0-9]+]], case #Optional.none!enumelt: [[NILBB:bb[0-9]+]] // CHECK: [[ISDERIVEDBB]]([[DERIVEDVAL:%[0-9]+]] : @owned $DerivedClass): // CHECK: debug_value [[DERIVEDVAL]] : $DerivedClass // => SEMANTIC SIL TODO: This is benign, but scoping wise, this end borrow should be after derived val. // CHECK: destroy_value [[DERIVEDVAL]] : $DerivedClass // CHECK: br [[EXITBB]] // CHECK: [[EXITBB]]: // CHECK: tuple () // CHECK: return if case let b as DerivedClass = a { } } // <rdar://problem/22312114> if case crashes swift - bools not supported in let/else yet // CHECK-LABEL: sil hidden @$S16if_while_binding12testCaseBoolyySbSgF func testCaseBool(_ value : Bool?) { // CHECK: bb0([[ARG:%.*]] : @trivial $Optional<Bool>): // CHECK: switch_enum [[ARG]] : $Optional<Bool>, case #Optional.some!enumelt.1: [[SOME_BB:bb[0-9]+]], case #Optional.none!enumelt: [[NONE_TRAMPOLINE:bb[0-9]+]] // // CHECK: [[NONE_TRAMPOLINE]]: // CHECK: br [[CONT_BB:bb[0-9]+]] // // CHECK: [[SOME_BB]]([[PAYLOAD:%.*]] : @trivial $Bool): // CHECK: [[ISTRUE:%[0-9]+]] = struct_extract [[PAYLOAD]] : $Bool, #Bool._value // CHECK: cond_br [[ISTRUE]], [[TRUE_TRAMPOLINE_BB:bb[0-9]+]], [[CONT_BB]] // // CHECK: [[TRUE_TRAMPOLINE_BB:bb[0-9]+]] // CHECK: br [[TRUE_BB:bb[0-9]+]] // // CHECK: [[TRUE_BB]]: // CHECK: function_ref @$S16if_while_binding8marker_1yyF // CHECK: br [[CONT_BB]] if case true? = value { marker_1() } // CHECK: [[CONT_BB]]: // CHECK: switch_enum [[ARG]] : $Optional<Bool>, case #Optional.some!enumelt.1: [[SUCC_BB_2:bb[0-9]+]], case #Optional.none!enumelt: [[NO_TRAMPOLINE_2:bb[0-9]+]] // CHECK: [[NO_TRAMPOLINE_2]]: // CHECK: br [[EPILOG_BB:bb[0-9]+]] // CHECK: [[SUCC_BB_2]]([[PAYLOAD2:%.*]] : @trivial $Bool): // CHECK: [[ISTRUE:%[0-9]+]] = struct_extract [[PAYLOAD2]] : $Bool, #Bool._value // CHECK: cond_br [[ISTRUE]], [[EPILOG_BB]], [[FALSE2_TRAMPOLINE_BB:bb[0-9]+]] // CHECK: [[FALSE2_TRAMPOLINE_BB]]: // CHECK: br [[FALSE2_BB:bb[0-9]+]] // // CHECK: [[FALSE2_BB]]: // CHECK: function_ref @$S16if_while_binding8marker_2yyF // CHECK: br [[EPILOG_BB]] // CHECK: [[EPILOG_BB]]: // CHECK: return if case false? = value { marker_2() } }
apache-2.0
f10cc5265f9771b38a0b0f84172c9a0b
38.958025
169
0.549218
2.983041
false
false
false
false
sebastiangrail/Mars-Orbiter
MarsOrbiter/Mass.swift
1
1780
// // Mass.swift // MarsOrbiter // // Created by Sebastian Grail on 20/02/2016. // Copyright © 2016 Sebastian Grail. All rights reserved. // public typealias Gram = Unit<GramTrait> public typealias Grams = Gram public struct GramTrait: UnitTrait { public typealias BaseTrait = GramTrait public static func toBaseUnit () -> Double { return 1 } public static func abbreviation() -> String { return "g" } } public typealias Kilogram = Unit<KilogramTrait> public typealias Kilograms = Kilogram public struct KilogramTrait: UnitTrait { public typealias BaseTrait = GramTrait public static func toBaseUnit () -> Double { return 1000 } public static func abbreviation() -> String { return "kg" } } public typealias Milligram = Unit<MilligramTrait> public typealias Milligrams = Milligram public struct MilligramTrait: UnitTrait { public typealias BaseTrait = GramTrait public static func toBaseUnit () -> Double { return 1/1000 } public static func abbreviation() -> String { return "mg" } } public typealias Tonne = Unit<TonneTrait> public typealias Tonnes = Tonne public typealias Ton = Tonne public struct TonneTrait: UnitTrait { public typealias BaseTrait = GramTrait public static func toBaseUnit () -> Double { return 1000*1000 } public static func abbreviation() -> String { return "t" } } public typealias Pound = Unit<PoundTrait> public typealias Pounds = Pound public struct PoundTrait: UnitTrait { public typealias BaseTrait = GramTrait public static func toBaseUnit () -> Double { return 453.592 } public static func abbreviation() -> String { return "lb" } }
mit
4e9fab2167f64f7fe9e034d7ce69df1b
23.369863
58
0.670039
4.297101
false
false
false
false
ripventura/VCHTTPConnect
VCHTTPConnect/Classes/VCHTTPConnect.swift
1
7740
// // VCHTTPConnect.swift // TimeClockBadge // // Created by Vitor Cesco on 8/25/16. // Copyright © 2016 Rolfson Oil. All rights reserved. // import Foundation import Alamofire open class VCHTTPConnect { // Object used to represent a response from an HTTP call public struct HTTPResponse { // Status code of the connections public let statusCode : Int? // Error occurred on the connection public let error : Error? // Headers returned on the connection public let headers : [String:String]? // URL returned on the connection public let url : URL? // Data returned on the connection public let data : Data? // Description of the HTTP call public let description: String? /** Initializes this HTTPResponse with an Alamofire Response object. */ public init(response: DataResponse<Data>) { self.statusCode = response.response?.statusCode self.error = response.error self.headers = response.response?.allHeaderFields as? [String : String] self.url = response.response?.url self.data = response.data self.description = response.description } public init(response: DataResponse<Any>) { self.statusCode = response.response?.statusCode self.error = response.error self.headers = response.response?.allHeaderFields as? [String : String] self.url = response.response?.url self.data = response.data self.description = response.description } } // URL string used on the call public var url : String /** Parameters to be used on the request. */ public var parameters : [String:Any] /** HTTP Headers used on the request. */ public var headers : [String:String] /** How the parameters are attatched to the request. Default is methodDependent. Default config: POST + PUT: json on body. GET + DELETE: urlEncoded encoded on the URL and must be on [String:String] format. */ public var parametersEncoding : URLEncoding.Destination = .methodDependent /** Wheter the last request was canceled by the user. */ public var canceledRequest: Bool = false /** The request object. */ public var request : Request? let sessionManager = Alamofire.SessionManager.default public init (url : String, parameters : [String:Any] = [:], headers : [String:String] = [:]) { // Converts to urlQueryAllowed just in case self.url = url.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)! self.parameters = parameters self.headers = headers self.request = nil self.sessionManager.startRequestsImmediately = false } /** Starts a POST connection on the given Path */ public func post(path : String, handler : @escaping (Bool, HTTPResponse) -> Void) { self.startRESTRequest(url: self.url + path, method: .post, handler: handler) } /** Starts a PUT connection on the given Path */ public func put(path : String, handler : @escaping (Bool, HTTPResponse) -> Void) { self.startRESTRequest(url: self.url + path, method: .put, handler: handler) } /** Starts a GET connection on the given Path */ public func get(path : String, handler : @escaping (Bool, HTTPResponse) -> Void) { self.startRESTRequest(url: self.url + path, method: .get, handler: handler) } /** Starts a DELETE connection on the given Path */ public func delete(path : String, handler : @escaping (Bool, HTTPResponse) -> Void) { self.startRESTRequest(url: self.url + path, method: .delete, handler: handler) } /** Cancels the current request **/ public func cancelRequest() { self.canceledRequest = true self.request?.cancel() } /** Downloads a file on the given path */ public func download(path : String, progressHandler : ((Double) -> Void)?, handler : @escaping (Bool, HTTPResponse) -> Void) { self.startDownloadRequest(url: self.url + path, progressHandler: progressHandler, handler: handler) } private func startRESTRequest(url: String, method : HTTPMethod, handler : @escaping (Bool, HTTPResponse) -> Void) { UIApplication.shared.isNetworkActivityIndicatorVisible = true func handleResponse(response: DataResponse<Any>) { UIApplication.shared.isNetworkActivityIndicatorVisible = false self.request = nil let httpResponse = HTTPResponse(response: response) handler(response.result.isSuccess, httpResponse) } if method == .get || method == .delete { self.request = Alamofire.request(url, method: method, parameters: self.parameters as! [String:String], encoding: URLEncoding(destination: .methodDependent), headers: self.headers).validate().debugLog().responseJSON { response in handleResponse(response: response) } } else { self.request = Alamofire.request(url, method: method, parameters: self.parameters, encoding: JSONEncoding(options: .prettyPrinted), headers: self.headers).validate().debugLog().responseJSON {response in handleResponse(response: response) } } self.canceledRequest = false self.request?.resume() } private func startDownloadRequest(url: String, progressHandler : ((Double) -> Void)?, handler : @escaping (Bool, HTTPResponse) -> Void) { UIApplication.shared.isNetworkActivityIndicatorVisible = true self.request = Alamofire.request(url, method: .get, parameters: self.parameters as! [String:String], encoding: URLEncoding(destination: .methodDependent), headers: self.headers).downloadProgress { progress in progressHandler?(progress.fractionCompleted) }.validate().responseData { response in UIApplication.shared.isNetworkActivityIndicatorVisible = false self.request = nil let httpResponse = HTTPResponse(response: response) handler(response.result.isSuccess, httpResponse) } self.canceledRequest = false self.request?.resume() } } extension Request { public func debugLog() -> Self { #if DEBUG debugPrint("=======================================") debugPrint(self) debugPrint("=======================================") #endif return self } }
mit
7bbbce7f99b15fca7ce67af7a571755a
39.098446
141
0.54374
5.677916
false
false
false
false
linkedin/LayoutKit
LayoutKitSampleApp/Benchmarks/FeedItemLayoutKitView.swift
2
2441
// Copyright 2016 LinkedIn Corp. // Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. // You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. import UIKit import ExampleLayouts /// A LinkedIn feed item that is implemented with LayoutKit. class FeedItemLayoutKitView: UIView, DataBinder { private var layout: FeedItemLayout? = nil private lazy var heightConstraint: NSLayoutConstraint = { let constraint = NSLayoutConstraint( item: self, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: self.bounds.height) constraint.isActive = true return constraint }() func setData(_ data: FeedItemData) { let posterProfile = ProfileCardLayout( name: data.posterName, connectionDegree: "2nd", headline: data.posterHeadline, timestamp: data.posterTimestamp, profileImageName: "50x50.png") let content = ContentLayout(title: data.contentTitle, domain: data.contentDomain) layout = FeedItemLayout( actionText: data.actionText, posterProfile: posterProfile, posterComment: data.posterComment, contentLayout: content, actorComment: data.actorComment) // Assure that `layoutSubviews` is called setNeedsLayout() // Only calculate height for valid width if bounds.width > 0 { heightConstraint.constant = sizeThatFits(CGSize(width: bounds.width, height: .greatestFiniteMagnitude)).height } } override func sizeThatFits(_ size: CGSize) -> CGSize { return layout?.measurement(within: size).size ?? .zero } override var intrinsicContentSize: CGSize { return sizeThatFits(CGSize(width: CGFloat.greatestFiniteMagnitude, height: CGFloat.greatestFiniteMagnitude)) } override func layoutSubviews() { layout?.measurement(within: bounds.size).arrangement(within: bounds).makeViews(in: self) } }
apache-2.0
c03f7c8862697f63645c0e08546f0157
36.553846
131
0.662024
4.99182
false
false
false
false
JohnnyDevMode/Hoard
Hoard/Entry.swift
1
771
// // Entry.swift // Hoard // // Created by John Bailey on 4/10/17. // Copyright © 2017 DevMode Studios. All rights reserved. // import Foundation let ROT_THRESHOLD = 0.5 class Entry { let value : Any fileprivate let created = Date() var accessed = Date() func isValid(expiry: Double) -> Bool { return Date().timeIntervalSince(created) < expiry } var drift : Double { return Date().timeIntervalSince(accessed) } func rot(expiry: Double) -> Double { guard expiry > 0 else { return 1 } return drift / expiry } func isRotten(expiry: Double) -> Bool { return rot(expiry: expiry) > ROT_THRESHOLD } init(value: Any) { self.value = value } func access() { accessed = Date() } }
mit
357b345a81d4f6ec40f1be14a343dc9a
15.041667
58
0.609091
3.701923
false
false
false
false
colourful987/My-Name-Is-Demo
DO_SliderTabBarController/DO_SliderTabBarController/TabBarController.swift
1
2406
// // TabBarController.swift // DO_SliderTabBarController // // Created by pmst on 15/12/4. // Copyright © 2015年 pmst. All rights reserved. // import UIKit class TabBarController: UITabBarController { // MARK: - Properties var ptAnimation = PTAnimationController() var rightEdger :UIScreenEdgePanGestureRecognizer! var leftEdger:UIScreenEdgePanGestureRecognizer! override func viewDidLoad() { super.viewDidLoad() // Notice 这里有个循环引用 self.delegate = ptAnimation ptAnimation.tbc = self // 添加手势 let sep = UIScreenEdgePanGestureRecognizer(target: self, action: "pan:") sep.edges = UIRectEdge.Right self.view.addGestureRecognizer(sep) sep.delegate = self self.rightEdger = sep let sep2 = UIScreenEdgePanGestureRecognizer(target: self, action: "pan:") sep2.edges = UIRectEdge.Left self.view.addGestureRecognizer(sep2) sep2.delegate = self self.leftEdger = sep2 } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } } extension TabBarController:UIGestureRecognizerDelegate{ // 是否执行手势 func gestureRecognizerShouldBegin(gestureRecognizer: UIGestureRecognizer) -> Bool { var result = false // selected Index 值改变会触发动画 if gestureRecognizer == self.rightEdger{ result = (self.selectedIndex < self.viewControllers!.count - 1) }else{ result = (self.selectedIndex > 0) } return result } func pan(g:UIScreenEdgePanGestureRecognizer){ let v = g.view! let delta = g.translationInView(v) // 获得滑动了距离 let percent = fabs(delta.x/v.bounds.size.width) switch g.state{ case .Began: ptAnimation.inter = UIPercentDrivenInteractiveTransition() ptAnimation.interacting = true // 右侧手势 if g == self.rightEdger{ // 更改selectedIndex 会触发页面切换动画 self.selectedIndex = self.selectedIndex + 1 }else{ self.selectedIndex = self.selectedIndex - 1 } case .Changed: ptAnimation.inter.updateInteractiveTransition(percent) case .Ended: if percent > 0.5{ ptAnimation.inter.finishInteractiveTransition() } else{ ptAnimation.inter.cancelInteractiveTransition() } ptAnimation.interacting = false default: break } } }
mit
5ebebee861bbafabe94d94724e32b633
24.351648
85
0.680971
4.453668
false
false
false
false
playbasis/native-sdk-ios
PlaybasisSDK/Classes/PBModel/PBGameStageSetting.swift
1
965
// // PBGameStageSetting.swift // Pods // // Created by Mederic PETIT on 11/14/16. // // import UIKit import ObjectMapper public class PBGameStageSetting: PBModel { public var stageName:String! = "" public var stageLevel:Int! = 1 public var image:String! = "" public var rangeLow:Int! = 0 public var rangeHigh:Int! = 0 public override init() { super.init() } required public init?(_ map: Map) { super.init(map) } override public func mapping(map: Map) { super.mapping(map) stageName <- map["stage_name"] stageLevel <- map["stage_level"] image <- map["image"] rangeLow <- map["range_low"] rangeHigh <- map["range_high"] } class func pbGameStageSettingsFromApiResponse(apiResponse:PBApiResponse) -> [PBGameStageSetting] { return Mapper<PBGameStageSetting>().mapArray(apiResponse.parsedJson!) ?? [] } }
mit
3508bc90cf07718e3dc641b5bfab00fe
21.44186
102
0.602073
3.954918
false
false
false
false
tmarkovski/BridgeCommander
BridgeCommander/BridgeCommander.swift
1
3590
// // SwiftBridgeCommander.swift // SwiftBridgeCommander // // Created by Markovski, Tomislav on 12/1/16. // Copyright © 2016 Blue Metal. All rights reserved. // import Foundation import WebKit public class BridgeCommander : NSObject, WKScriptMessageHandler { let messageHandlerName = "__SWIFT_BRIDGE_COMMANDER" let bridgeScriptObject = "BridgeCommander" let webView: WKWebView var commands = [String: CommandHandler]() public init(_ webView: WKWebView) { self.webView = webView super.init() if let filepath = Bundle(for: type(of: self)).path(forResource: "BridgeCommander", ofType: "js") { do { let contents = try String(contentsOfFile: filepath) self.webView.configuration.userContentController.addUserScript(WKUserScript(source: contents, injectionTime: .atDocumentEnd, forMainFrameOnly: false)) self.webView.configuration.userContentController.add(self, name: messageHandlerName) } catch { print("Error occured") } } else { print("Error script not found") } } public func add(_ name: String, handler: @escaping CommandHandler){ commands[name] = handler } public func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) { print("Message rceived: \(message.name) Body: \(message.body)") guard let msg = parse(message.body) else { print("Cannot parse message"); return } guard let handler = commands[msg.command!] else { let error = "Command not registered: \(msg.command!)" BridgeCommand(msg, commander: self) .error(args: error) print(error) return } handler(BridgeCommand(msg, commander: self)) } func parse(_ body: Any) -> BridgeMessage? { do { var message = BridgeMessage() let data = (body as! String).data(using: .utf8) let parsedData = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as! [String:Any] message.id = parsedData["id"] as? String message.command = parsedData["command"] as? String message.args = parsedData["args"] as? String return message } catch let error as NSError { print(error) return nil } } func send(args: String, id: String) { webView.evaluateJavaScript("window['\(bridgeScriptObject)'].response({'id':'\(id)', 'payload':'\(args)'})", completionHandler: nil) } func error(args: String, id: String) { webView.evaluateJavaScript("window['\(bridgeScriptObject)'].error({'id':'\(id)', 'payload':'\(args)'})", completionHandler: nil) } } struct BridgeMessage { var id, command, args: String? } public typealias CommandHandler = (_ command: BridgeCommand) -> Void public class BridgeCommand { private let message: BridgeMessage private let commander: BridgeCommander public let args: String init(_ message: BridgeMessage, commander: BridgeCommander) { self.message = message self.commander = commander self.args = message.args! } public func send(args: String) { commander.send(args: args, id: self.message.id!) } public func error(args: String) { commander.error(args: args, id: self.message.id!) } }
mit
80940708da748d114e727c67c7a35dc4
32.542056
166
0.610476
4.595391
false
false
false
false
snownothing/RefreshControl-Swift
RefreshControl-Swift/RefreshControl-Swift/Arrow.swift
1
3599
// // Arrow.swift // RefreshControl-Swift // // Created by Moch on 10/13/14. // Copyright (c) 2014 Moch. All rights reserved. // let kArrowPointCount = 7 import UIKit public class Arrow: UIView { var color: UIColor? required public init(coder aDecoder: NSCoder) { self.color = UIColor.lightGrayColor() super.init(coder: aDecoder) self.backgroundColor = UIColor.clearColor() } override init(frame: CGRect) { self.color = UIColor.lightGrayColor() super.init(frame: frame) self.backgroundColor = UIColor.clearColor() } override public func drawRect(rect: CGRect) { let startPoint = CGPointMake(CGRectGetMidX(self.bounds), CGRectGetMaxY(self.bounds)); let endPoint = CGPointMake(CGRectGetMidX(self.bounds), CGRectGetMinY(self.bounds)); let tailWidth = CGRectGetWidth(self.bounds) / 3; let headWidth = CGRectGetWidth(self.bounds) * 0.7; let headLength = CGRectGetHeight(self.bounds) / 2; let bezierPath = UIBezierPath.bezierPathWithArrowFromPointStartPoint(startPoint, toPoint: endPoint, tailWidth: tailWidth, headWidth: headWidth, headLength: headLength) self.color?.setFill() bezierPath.fill() } // MARK: - public methods public func rotation() { UIView.animateWithDuration(0.2, animations: { self.transform = CGAffineTransformMakeRotation(CGFloat(M_PI)) }) } public func identity() { UIView.animateWithDuration(0.2, animations: { self.transform = CGAffineTransformIdentity }) } } // MARK: - UIBezierPath extension public extension UIBezierPath { public class func bezierPathWithArrowFromPointStartPoint(startPoint: CGPoint, toPoint endPoint: CGPoint, tailWidth: CGFloat, headWidth: CGFloat, headLength: CGFloat) -> UIBezierPath { let xDiff = Float(endPoint.x - startPoint.x) let yDiff = Float(endPoint.y - startPoint.y) let length = CGFloat(hypotf(xDiff, yDiff)) var points = [CGPoint](count: Int(kArrowPointCount), repeatedValue: CGPointZero) self.axisAlignedArrowPoints(&points, forLength: length, tailWidth: tailWidth, headWidth: headWidth, headLength: headLength) var transform: CGAffineTransform = self.transformForStartPoint(startPoint, endPoint: endPoint, length: length) var cgPath: CGMutablePathRef = CGPathCreateMutable() CGPathAddLines(cgPath, &transform, points, 7) CGPathCloseSubpath(cgPath) var uiPath: UIBezierPath = UIBezierPath(CGPath: cgPath) return uiPath } private class func axisAlignedArrowPoints(inout points: [CGPoint], forLength length: CGFloat, tailWidth: CGFloat, headWidth: CGFloat, headLength: CGFloat) { let tailLength = length - headLength points[0] = CGPointMake(0, tailWidth / 2) points[1] = CGPointMake(tailLength, tailWidth / 2) points[2] = CGPointMake(tailLength, headWidth / 2) points[3] = CGPointMake(length, 0) points[4] = CGPointMake(tailLength, -headWidth / 2) points[5] = CGPointMake(tailLength, -tailWidth / 2) points[6] = CGPointMake(0, -tailWidth / 2) } private class func transformForStartPoint(startPoint: CGPoint, endPoint: CGPoint, length: CGFloat) -> CGAffineTransform { let cosine = (endPoint.x - startPoint.x) / length let sine = (endPoint.y - startPoint.y) / length return CGAffineTransformMake(cosine, sine, -sine, cosine, startPoint.x, startPoint.y) } }
mit
a604faf86ef0f109ceaad61124e2af75
38.988889
187
0.671853
4.421376
false
false
false
false
FraDeliro/ISaMaterialLogIn
ISaMaterialLogIn/Classes/ISaModelViewController.swift
1
6338
// // ISaModelViewController.swift // Pods // // Created by Francesco on 20/12/16. // // import UIKit import Material open class ISaModelViewController: UIViewController { //MARK: - Outlets & Variables //Commons var transition: ISaMaterialTransition = ISaMaterialTransition(viewAnimated: UIView()) public var isaCircleView: ISaCircleLoader? public var dynamicViewsHeightAnchor: CGFloat = 0 public var dynamicViewsWidthAnchor: CGFloat = 0 public var dismissKeyboardOnTap: Bool = false public var viewTitleHeightAnchor: CGFloat = 0 public var viewTitleWidthAnchor: CGFloat = 0 public var viewTitleTopAnchor: CGFloat = 0 @IBOutlet var widthButtonConstraint: NSLayoutConstraint! @IBOutlet weak public var isaScrollView : UIScrollView! // Login @IBOutlet public var isaBottomLoginButtonConstraint: NSLayoutConstraint! @IBOutlet weak public var isaLoginButton : UIButton! @IBOutlet weak public var showSignUpButton : UIButton! public var loginButtonTitle: String = "Login" //Sign Up @IBOutlet public var isaBottomSignUpButtonConstraint: NSLayoutConstraint! @IBOutlet weak public var isaSignUpButton : UIButton! @IBOutlet weak public var isaDismissSignUpButton : UIButton! public var signUpButtonTitle: String = "Signup" //MARK: - Page lifecycle open override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } open override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() if self.dismissKeyboardOnTap { let gestureRecognizer : UITapGestureRecognizer = UITapGestureRecognizer.init(target: self, action: #selector(ISaModelViewController.dismissKeyboard)) self.view.addGestureRecognizer(gestureRecognizer) } } //MARK: - Custom Accessors public func loadViewFromNib(_ NibName: String, controllerClass: AnyClass) { self.view = Bundle.init(for: controllerClass).loadNibNamed(NibName, owner: self, options: nil)?[0] as? UIView } @available(iOS 9.0, *) public func setLoginSignUpViews(views: [UIView], inStackView stackView: UIStackView) { for view in views { view.heightAnchor.constraint(equalToConstant: dynamicViewsHeightAnchor).isActive = true view.widthAnchor.constraint(equalToConstant: dynamicViewsWidthAnchor).isActive = true stackView.addArrangedSubview(view) } stackView.backgroundColor = UIColor.white stackView.translatesAutoresizingMaskIntoConstraints = false if let scrollView = self.scrollView { scrollView.addSubview(stackView) } else { self.view.addSubview(stackView) } //Constraints stackView.centerXAnchor.constraint(equalTo: self.view.centerXAnchor).isActive = true stackView.centerYAnchor.constraint(equalTo: self.view.centerYAnchor).isActive = true } @available(iOS 9.0, *) public func setLoginSignUpViewControllerTitle(views: [UIView], inStackView stackView: UIStackView) { for view in views { view.heightAnchor.constraint(equalToConstant: viewTitleHeightAnchor).isActive = true view.widthAnchor.constraint(equalToConstant: viewTitleWidthAnchor).isActive = true stackView.addArrangedSubview(view) } stackView.backgroundColor = UIColor.white stackView.translatesAutoresizingMaskIntoConstraints = false if let scrollView = self.scrollView { scrollView.addSubview(stackView) } else { self.view.addSubview(stackView) } //Constraints stackView.topAnchor.constraint(equalTo: self.view.topAnchor, constant: viewTitleTopAnchor).isActive = true stackView.centerXAnchor.constraint(equalTo: self.view.centerXAnchor).isActive = true } public func addAnimatedButton(_ animatedView: UIButton) { self.view.addSubview(animatedView) transition = ISaMaterialTransition(viewAnimated: animatedView) } // MARK: - Actions @objc private func dismissKeyboard() { self.view.endEditing(true) } public func isaStartLoginSignUpAnimation(_ sender: UIButton) { let condition:Bool = (self.isaCircleView != nil) precondition(condition, "#To call this function directly you need to implement the isaCircleView!") UIView.animate(withDuration: 0.1, delay: 0.5, options: [.curveLinear], animations: { sender.setTitle("", for: .normal) sender.transform = .init(scaleX: 0.1, y: 1.0) }) { (completion) in //start loading view sender.alpha = 0.0 if let circleView = self.isaCircleView { self.view.addSubview(circleView) } } } public func checkEmptyData(fields: [ErrorTextField], error: NSError) throws { fields.forEach { (field) in field.isErrorRevealed = true field.detail = field.errorMessage } for field in fields { guard field.text?.isEmpty == true else { field.isErrorRevealed = false field.detail = "" continue } throw error } } public func isaLoginSignUpSuccessfully(showNew controller: UIViewController) { controller.modalPresentationStyle = .custom controller.transitioningDelegate = transition self.present(controller, animated: true, completion: nil) } public func isaLoginSignUpError(_ sender: UIButton, oldTitle: String) { UIView.animate(withDuration: 0.2, delay: 0.0, options: [.curveLinear], animations: { self.isaCircleView?.removeFromSuperview() self.isaCircleView = nil }) { (completion) in sender.transform = .identity sender.alpha = 1.0 sender.setTitle(oldTitle, for: .normal) } } public func showSignUp(controller: UIViewController) { controller.modalPresentationStyle = .custom controller.transitioningDelegate = transition self.present(controller, animated: true, completion: nil) } }
mit
b3151b66ffcf07c6f8508f7db86ae515
37.646341
161
0.663774
5.165444
false
false
false
false
CatchChat/Yep
YepPreview/PhotoViewController.swift
1
4447
// // PhotoViewController.swift // Yep // // Created by NIX on 16/6/17. // Copyright © 2016年 Catch Inc. All rights reserved. // import UIKit class PhotoViewController: UIViewController { let photo: Photo lazy var scalingImageView: ScalingImageView = { let view = ScalingImageView(frame: self.view.bounds) view.delegate = self return view }() private lazy var loadingView: UIActivityIndicatorView = { let view = UIActivityIndicatorView(activityIndicatorStyle: .White) view.hidesWhenStopped = true return view }() lazy var doubleTapGestureRecognizer: UITapGestureRecognizer = { let tap = UITapGestureRecognizer() tap.addTarget(self, action: #selector(PhotoViewController.didDoubleTap(_:))) tap.numberOfTapsRequired = 2 return tap }() private lazy var longPressGestureRecognizer: UILongPressGestureRecognizer = { let longPress = UILongPressGestureRecognizer() longPress.addTarget(self, action: #selector(PhotoViewController.didLongPress(_:))) return longPress }() deinit { scalingImageView.delegate = nil NSNotificationCenter.defaultCenter().removeObserver(self) } // MARK: Init init(photo: Photo) { self.photo = photo super.init(nibName: nil, bundle: nil) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: Life Circle override func viewDidLoad() { super.viewDidLoad() scalingImageView.frame = view.bounds scalingImageView.image = photo.image view.addSubview(scalingImageView) photo.updatedImage = { [weak self] image in self?.scalingImageView.image = image if image != nil { self?.loadingView.stopAnimating() } } if photo.image == nil { loadingView.startAnimating() } view.addSubview(loadingView) view.addGestureRecognizer(doubleTapGestureRecognizer) view.addGestureRecognizer(longPressGestureRecognizer) } override func viewWillLayoutSubviews() { super.viewWillLayoutSubviews() scalingImageView.frame = view.bounds loadingView.center = CGPoint(x: view.bounds.midX, y: view.bounds.midY) } // MARK: Selectors @objc private func didDoubleTap(sender: UITapGestureRecognizer) { let scrollViewSize = scalingImageView.bounds.size var pointInView = sender.locationInView(scalingImageView.imageView) var newZoomScale = min(scalingImageView.maximumZoomScale, scalingImageView.minimumZoomScale * 2) if let imageSize = scalingImageView.imageView.image?.size where (imageSize.height / imageSize.width) > (scrollViewSize.height / scrollViewSize.width) { pointInView.x = scalingImageView.imageView.bounds.width / 2 let widthScale = scrollViewSize.width / imageSize.width newZoomScale = widthScale } let isZoomIn = (scalingImageView.zoomScale >= newZoomScale) || (abs(scalingImageView.zoomScale - newZoomScale) <= 0.01) if isZoomIn { newZoomScale = scalingImageView.minimumZoomScale } scalingImageView.directionalLockEnabled = !isZoomIn let width = scrollViewSize.width / newZoomScale let height = scrollViewSize.height / newZoomScale let originX = pointInView.x - (width / 2) let originY = pointInView.y - (height / 2) let rectToZoomTo = CGRect(x: originX, y: originY, width: width, height: height) scalingImageView.zoomToRect(rectToZoomTo, animated: true) } @objc private func didLongPress(sender: UILongPressGestureRecognizer) { // TODO: didLongPress } } // MARK: - UIScrollViewDelegate extension PhotoViewController: UIScrollViewDelegate { func viewForZoomingInScrollView(scrollView: UIScrollView) -> UIView? { return scalingImageView.imageView } func scrollViewWillBeginZooming(scrollView: UIScrollView, withView view: UIView?) { scrollView.panGestureRecognizer.enabled = true } func scrollViewDidEndZooming(scrollView: UIScrollView, withView view: UIView?) { if scrollView.zoomScale == scrollView.minimumZoomScale { scrollView.panGestureRecognizer.enabled = false } } }
mit
33588cfb4a8e6a1a887fcc38f24d9a53
26.949686
159
0.668542
5.452761
false
false
false
false
CartoDB/mobile-ios-samples
AdvancedMap.Swift/Feature Demo/ClusteringController.swift
1
2655
// // ClusteringController.swift // AdvancedMap.Swift // // Created by Aare Undo on 28/06/2017. // Copyright © 2017 CARTO. All rights reserved. // import Foundation import UIKit import CartoMobileSDK class ClusteringController : BaseController { var contentView: ClusteringView! override func viewDidLoad() { super.viewDidLoad() contentView = ClusteringView() view = contentView let cBuilder = ClusterBuilder() cBuilder?.image = UIImage(named: "marker_black.png") cBuilder?.elements = [Int: NTMarkerStyle]() contentView.initializeClusterLayer(builder: cBuilder!) DispatchQueue.global().async { let path = Bundle.main.path(forResource: "cities15000", ofType: "geojson") guard let json = try? NSString(contentsOfFile: path!, encoding: String.Encoding.utf8.rawValue) else { return } // This is the style of a non-cluster element // This element will be displayed when clustering animation completes and it's no longer a cluster let mBuilder = NTMarkerStyleBuilder() mBuilder?.setBitmap(NTBitmapUtils.createBitmap(from: cBuilder?.image)) mBuilder?.setSize(30) let style = mBuilder?.buildStyle() // Read GeoJSON, parse it using SDK GeoJSON parser let reader = NTGeoJSONGeometryReader() reader?.setTargetProjection(self.contentView.map.getOptions().getBaseProjection()) let features = reader?.readFeatureCollection(json as String) let elements = NTVectorElementVector() let total = Int((features?.getFeatureCount())!) for i in stride(from: 0, to: total, by: 1) { // This data set features point geometry, however, it can also be LineGeometry or PolygonGeometry let geometry = features?.getFeature(Int32(i)).getGeometry() as? NTPointGeometry elements?.add(NTMarker(geometry: geometry, style: style)) } DispatchQueue.main.async(execute: { self.contentView.addClusters(elements: elements!) }) } } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) contentView.addRecognizers() } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) contentView.removeRecognizers() } }
bsd-2-clause
a33a5e186c589f56e724f61aa81f0918
32.594937
113
0.596458
5.11368
false
false
false
false