repo_name
stringlengths
7
91
path
stringlengths
8
658
copies
stringclasses
125 values
size
stringlengths
3
6
content
stringlengths
118
674k
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
6.09
99.2
line_max
int64
17
995
alpha_frac
float64
0.3
0.9
ratio
float64
2
9.18
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
AdaptiveMe/adaptive-arp-api-lib-darwin
Pod/Classes/Sources.Api/ContactSocial.swift
1
4960
/** --| ADAPTIVE RUNTIME PLATFORM |---------------------------------------------------------------------------------------- (C) Copyright 2013-2015 Carlos Lozano Diez t/a Adaptive.me <http://adaptive.me>. 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 appli- -cable 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. Original author: * Carlos Lozano Diez <http://github.com/carloslozano> <http://twitter.com/adaptivecoder> <mailto:[email protected]> Contributors: * Ferran Vila Conesa <http://github.com/fnva> <http://twitter.com/ferran_vila> <mailto:[email protected]> * See source code files for contributors. Release: * @version v2.2.15 -------------------------------------------| aut inveniam viam aut faciam |-------------------------------------------- */ import Foundation /** Structure representing the social data elements of a contact. @author Francisco Javier Martin Bueno @since v2.0 @version 1.0 */ public class ContactSocial : APIBean { /** The social network */ var socialNetwork : ContactSocialNetwork? /** The profileUrl */ var profileUrl : String? /** Default constructor @since v2.0 */ public override init() { super.init() } /** Constructor used by the implementation @param socialNetwork of the profile @param profileUrl of the user @since v2.0 */ public init(socialNetwork: ContactSocialNetwork, profileUrl: String) { super.init() self.socialNetwork = socialNetwork self.profileUrl = profileUrl } /** Returns the social network @return socialNetwork @since v2.0 */ public func getSocialNetwork() -> ContactSocialNetwork? { return self.socialNetwork } /** Set the social network @param socialNetwork of the profile @since v2.0 */ public func setSocialNetwork(socialNetwork: ContactSocialNetwork) { self.socialNetwork = socialNetwork } /** Returns the profile url of the user @return profileUrl @since v2.0 */ public func getProfileUrl() -> String? { return self.profileUrl } /** Set the profile url of the iser @param profileUrl of the user @since v2.0 */ public func setProfileUrl(profileUrl: String) { self.profileUrl = profileUrl } /** JSON Serialization and deserialization support. */ public struct Serializer { public static func fromJSON(json : String) -> ContactSocial { let data:NSData = json.dataUsingEncoding(NSUTF8StringEncoding)! let dict = try? NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers) as! NSDictionary return fromDictionary(dict!) } static func fromDictionary(dict : NSDictionary) -> ContactSocial { let resultObject : ContactSocial = ContactSocial() if let value : AnyObject = dict.objectForKey("profileUrl") { if "\(value)" as NSString != "<null>" { resultObject.profileUrl = (value as! String) } } if let value : AnyObject = dict.objectForKey("socialNetwork") { if "\(value)" as NSString != "<null>" { resultObject.socialNetwork = ContactSocialNetwork.toEnum(((value as! NSDictionary)["value"]) as? String) } } return resultObject } public static func toJSON(object: ContactSocial) -> String { let jsonString : NSMutableString = NSMutableString() // Start Object to JSON jsonString.appendString("{ ") // Fields. object.profileUrl != nil ? jsonString.appendString("\"profileUrl\": \"\(JSONUtil.escapeString(object.profileUrl!))\", ") : jsonString.appendString("\"profileUrl\": null, ") object.socialNetwork != nil ? jsonString.appendString("\"socialNetwork\": { \"value\": \"\(object.socialNetwork!.toString())\"}") : jsonString.appendString("\"socialNetwork\": null") // End Object to JSON jsonString.appendString(" }") return jsonString as String } } } /** ------------------------------------| Engineered with ♥ in Barcelona, Catalonia |-------------------------------------- */
apache-2.0
fd405f64845c33a1d1a937e363df0df2
29.231707
194
0.587334
5.003027
false
false
false
false
huangboju/Moots
Examples/SwiftUI/SwiftUI-Apple/WorkingWithUIControls/StartingPoint/Landmarks/Landmarks/Supporting Views/BadgeBackground.swift
8
2227
/* See LICENSE folder for this sample’s licensing information. Abstract: A view that displays the background of a badge. */ import SwiftUI struct BadgeBackground: View { var body: some View { GeometryReader { geometry in Path { path in var width: CGFloat = min(geometry.size.width, geometry.size.height) let height = width let xScale: CGFloat = 0.832 let xOffset = (width * (1.0 - xScale)) / 2.0 width *= xScale path.move( to: CGPoint( x: xOffset + width * 0.95, y: height * (0.20 + HexagonParameters.adjustment) ) ) HexagonParameters.points.forEach { path.addLine( to: .init( x: xOffset + width * $0.useWidth.0 * $0.xFactors.0, y: height * $0.useHeight.0 * $0.yFactors.0 ) ) path.addQuadCurve( to: .init( x: xOffset + width * $0.useWidth.1 * $0.xFactors.1, y: height * $0.useHeight.1 * $0.yFactors.1 ), control: .init( x: xOffset + width * $0.useWidth.2 * $0.xFactors.2, y: height * $0.useHeight.2 * $0.yFactors.2 ) ) } } .fill(LinearGradient( gradient: .init(colors: [Self.gradientStart, Self.gradientEnd]), startPoint: .init(x: 0.5, y: 0), endPoint: .init(x: 0.5, y: 0.6) )) .aspectRatio(1, contentMode: .fit) } } static let gradientStart = Color(red: 239.0 / 255, green: 120.0 / 255, blue: 221.0 / 255) static let gradientEnd = Color(red: 239.0 / 255, green: 172.0 / 255, blue: 120.0 / 255) } struct BadgeBackground_Previews: PreviewProvider { static var previews: some View { BadgeBackground() } }
mit
ecc328470c205ce7413f01cfb5a10092
34.887097
93
0.436854
4.405941
false
false
false
false
huangboju/Moots
Examples/QuartzDemo/QuartzDemo/Views/QuartzGradientView.swift
2
5472
// // QuartzGradientView.swift // QuartzDemo // // Created by 伯驹 黄 on 2017/4/8. // Copyright © 2017年 伯驹 黄. All rights reserved. // enum GradientType: Int { case linear = 0 case radial = 1 } class QuartzGradientView: QuartzView { public var type: GradientType = .linear { didSet { if type != oldValue { setNeedsDisplay() } } } public var extendsPastStart = false { didSet { if extendsPastStart != oldValue { setNeedsDisplay() } } } public var extendsPastEnd = false { didSet { if extendsPastEnd != oldValue { setNeedsDisplay() } } } private var _gradient: CGGradient? var gradient: CGGradient { if _gradient == nil { let rgb = CGColorSpaceCreateDeviceRGB() let colors = [ UIColor(red: 204.0 / 255.0, green: 224.0 / 255.0, blue: 244.0 / 255.0, alpha: 1).cgColor, UIColor(red: 29.0 / 255.0, green: 156.0 / 255.0, blue: 215.0 / 255.0, alpha: 1).cgColor, UIColor(red: 0, green: 50.0 / 255.0, blue: 126.0 / 255.0, alpha: 1).cgColor ] as CFArray _gradient = CGGradient(colorsSpace: rgb, colors: colors, locations: nil) } return _gradient! } var drawingOptions: CGGradientDrawingOptions { var options: UInt32 = 0 if extendsPastStart { options |= CGGradientDrawingOptions.drawsBeforeStartLocation.rawValue } if extendsPastEnd { options |= CGGradientDrawingOptions.drawsAfterEndLocation.rawValue } return CGGradientDrawingOptions(rawValue: options) } override func draw(in context: CGContext) { // Use the clip bounding box, sans a generous border let clip = context.boundingBoxOfClipPath.insetBy(dx: 20.0, dy: 20.0) var start = CGPoint() var end = CGPoint() var startRadius: CGFloat = 0 var endRadius: CGFloat = 0 // Clip to area to draw the gradient, and draw it. Since we are clipping, we save the graphics state // so that we can revert to the previous larger area. context.saveGState() context.clip(to: clip) let options = drawingOptions switch type { case .linear: // A linear gradient requires only a starting & ending point. // The colors of the gradient are linearly interpolated along the line segment connecting these two points // A gradient location of 0.0 means that color is expressed fully at the 'start' point // a location of 1.0 means that color is expressed fully at the 'end' point. // The gradient fills outwards perpendicular to the line segment connectiong start & end points // (which is why we need to clip the context, or the gradient would fill beyond where we want it to). // The gradient options (last) parameter determines what how to fill the clip area that is "before" and "after" // the line segment connecting start & end. start = clip.demoLGStart end = clip.demoLGEnd context.drawLinearGradient(gradient, start: start, end: end, options: options) context.restoreGState() case .radial: // A radial gradient requires a start & end point as well as a start & end radius. // Logically a radial gradient is created by linearly interpolating the center, radius and color of each // circle using the start and end point for the center, start and end radius for the radius, and the color ramp // inherant to the gradient to create a set of stroked circles that fill the area completely. // The gradient options specify if this interpolation continues past the start or end points as it does with // linear gradients. start = clip.demoRGCenter end = start startRadius = clip.demoRGInnerRadius endRadius = clip.demoRGOuterRadius context.drawRadialGradient(gradient, startCenter: start, startRadius: startRadius, endCenter: end, endRadius: endRadius, options: options) context.restoreGState() } // Show the clip rect context.setStrokeColor(red: 1.0, green: 0.0, blue: 0.0, alpha: 1.0) context.stroke(clip, width: 2.0) } } extension CGRect { // Returns an appropriate starting point for the demonstration of a linear gradient var demoLGStart: CGPoint { return CGPoint(minX, minY + height * 0.25) } // Returns an appropriate ending point for the demonstration of a linear gradient var demoLGEnd: CGPoint { return CGPoint(minX, minY + height * 0.75) } // Returns the center point for for the demonstration of the radial gradient var demoRGCenter: CGPoint { return CGPoint(midX, midY) } // Returns an appropriate inner radius for the demonstration of the radial gradient var demoRGInnerRadius: CGFloat { return min(width, height) * 0.125 } // Returns an appropriate outer radius for the demonstration of the radial gradient var demoRGOuterRadius: CGFloat { return min(width, height) * 0.5 } }
mit
737513f6fd26797ab69c123fb6d4eee2
37.702128
150
0.611691
4.716508
false
false
false
false
huangboju/Moots
UICollectionViewLayout/CollectionKit-master/Examples/PresenterExample/PresenterExampleViewController.swift
1
2855
// // PresenterExampleViewController.swift // CollectionKitExample // // Created by Luke Zhao on 2017-09-04. // Copyright © 2017 lkzhao. All rights reserved. // import UIKit import CollectionKit class PresenterExampleViewController: CollectionViewController { override func viewDidLoad() { super.viewDidLoad() let presenters = [ ("Default", CollectionPresenter()), ("Wobble", WobblePresenter()), ("Edge Shrink", EdgeShrinkPresenter()), ("Zoom", ZoomPresenter()), ] let imagesCollectionView = CollectionView() let imageProvider = CollectionProvider( data: testImages, viewUpdater: { (view: UIImageView, data: UIImage, at: Int) in view.image = data view.layer.cornerRadius = 5 view.clipsToBounds = true } ) imageProvider.layout = WaterfallLayout(columns:2).transposed().inset(by: bodyInset) imageProvider.sizeProvider = imageSizeProvider imageProvider.presenter = presenters[0].1 imagesCollectionView.provider = imageProvider imagesCollectionView.activeFrameInset = UIEdgeInsets(top: 0, left: -100, bottom: 0, right: -100) let buttonsCollectionView = CollectionView() buttonsCollectionView.showsHorizontalScrollIndicator = false let buttonsProvider = CollectionProvider( data: presenters, viewUpdater: { (view: SelectionButton, data: (String, CollectionPresenter), at: Int) in view.label.text = data.0 view.label.textColor = imageProvider.presenter === data.1 ? .white : .black view.backgroundColor = imageProvider.presenter === data.1 ? .lightGray : .white } ) buttonsProvider.layout = FlowLayout(lineSpacing: 10).transposed().inset(by: UIEdgeInsets(top: 10, left: 16, bottom: 0, right: 16)) buttonsProvider.sizeProvider = { _, data, maxSize in return CGSize(width: data.0.width(withConstraintedHeight: maxSize.height, font: UIFont.systemFont(ofSize:18)) + 20, height: maxSize.height) } buttonsProvider.presenter = WobblePresenter() buttonsProvider.tapHandler = { _, index, dataProvider in imageProvider.presenter = dataProvider.data(at: index).1 // clear previous styles for cell in imagesCollectionView.visibleCells { cell.alpha = 1 cell.transform = .identity } dataProvider.reloadData() } buttonsCollectionView.provider = buttonsProvider let buttonsCollectionViewProvider = ViewCollectionProvider(buttonsCollectionView, sizeStrategy: (.fill, .absolute(44))) let providerCollectionViewProvider = ViewCollectionProvider(identifier: "providerContent", imagesCollectionView, sizeStrategy: (.fill, .fill)) provider = CollectionComposer( layout: RowLayout("providerContent").transposed(), buttonsCollectionViewProvider, providerCollectionViewProvider ) } }
mit
89f4e462e056452eefa942954f9d526a
37.053333
146
0.707779
4.709571
false
false
false
false
marekhac/WczasyNadBialym-iOS
WczasyNadBialym/WczasyNadBialym/ViewControllers/Service/ServiceDetails/ServiceDetailsViewController.swift
1
5663
// // ServiceDetailsViewController.swift // WczasyNadBialym // // Created by Marek Hać on 05.05.2017. // Copyright © 2017 Marek Hać. All rights reserved. // import UIKit import MapKit import SVProgressHUD import GoogleMobileAds import WebKit class ServiceDetailsViewController: UIViewController { var adHandler : AdvertisementHandler? let backgroundImageName = "background_gradient2" var backgroundImage : UIImage? var selectedServiceId: String = "" var selectedServiceType: String = "" let mapType = MKMapType.standard var gpsLat: Double = 0.0 var gpsLng: Double = 0.0 var pinTitle: String = "" var pinSubtitle: String = "" @IBOutlet weak var backgroundView: UIView! @IBOutlet weak var bannerView: GADBannerView! @IBOutlet weak var bannerViewHeightConstraint: NSLayoutConstraint! @IBOutlet weak var backgroundImageView: UIImageView! @IBOutlet weak var imageView: UIImageView! @IBOutlet weak var nameLabel: UILabel! @IBOutlet weak var addressLabel: UILabel! @IBOutlet weak var cityLabel: UILabel! @IBOutlet weak var phoneTextView: UITextView! @IBOutlet weak var descriptionTextView: UITextView! lazy var viewModel: ServiceDetailsViewModel = { return ServiceDetailsViewModel() }() // init view model func initViewModel () { viewModel.updateViewClosure = { DispatchQueue.main.async { let serviceDetailsModel = self.viewModel.getServiceDetailsModel() if let serviceDetailsModel = serviceDetailsModel { self.gpsLat = serviceDetailsModel.gpsLat self.gpsLng = serviceDetailsModel.gpsLng self.pinTitle = serviceDetailsModel.name self.pinSubtitle = serviceDetailsModel.phone // update ui self.nameLabel.text = serviceDetailsModel.name // create address by join street and city var address = serviceDetailsModel.street if (!address.isEmpty) { address = address + ", " } address = address + serviceDetailsModel.city self.addressLabel.text = address var phoneNumber = serviceDetailsModel.phone // add "tel." prefix to phone number (if it's not already present) if (!phoneNumber.isEmpty) { if (!phoneNumber.contains("tel")) { phoneNumber = "tel. " + phoneNumber } } self.phoneTextView.text = phoneNumber // remove all html tags let detailsStripped = serviceDetailsModel.description.removeHTMLTags() self.descriptionTextView.text = detailsStripped // assign med image if present self.imageView.downloadImageAsync(serviceDetailsModel.medImgURL) SVProgressHUD.dismiss() // remove blured loading view self.view.removeBlurSubviewForTag(.loading) } } } self.viewModel.fetchServiceDetails(for: selectedServiceId) } override func viewDidLoad() { super.viewDidLoad() // blur background self.view.addBlurSubview(at: 1, style: .light) // setup background if let backgroundImage = backgroundImage { self.backgroundImageView.image = backgroundImage } // blur main screen while loading the content self.view.addBlurSubview (style: .light, tag: .loading) // setup with default images let serviceImage = UIImage(named: self.selectedServiceType + ".png") self.imageView.image = serviceImage SVProgressHUD.show() initViewModel() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(true) displayAdvertisementBanner() } // MARK: - Request for advertisement func displayAdvertisementBanner() { self.adHandler = AdvertisementHandler(bannerAdView: self.bannerView) if let adHandler = self.adHandler { // adViewHeightConstraint set to hide/show banner if there is/isn't ad to show adHandler.adViewHeightConstraint = self.bannerViewHeightConstraint adHandler.showAd(viewController: self) } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "showServiceMap" { let controller = segue.destination as! ServiceMapViewController controller.gpsLat = self.gpsLat controller.gpsLng = self.gpsLng controller.pinTitle = self.pinTitle controller.pinSubtitle = self.pinSubtitle } } }
gpl-3.0
84d05877807fbca5b7f032290683ea30
32.892216
90
0.55424
5.95163
false
false
false
false
RobinChao/PageMenu
Demos/Demo 4/PageMenuDemoTabbar/PageMenuDemoTabbar/TestCollectionViewController.swift
86
2196
// // TestCollectionViewController.swift // NFTopMenuController // // Created by Niklas Fahl on 12/17/14. // Copyright (c) 2014 Niklas Fahl. All rights reserved. // import UIKit let reuseIdentifier = "MoodCollectionViewCell" class TestCollectionViewController: UICollectionViewController { var moodArray : [String] = ["Relaxed", "Playful", "Happy", "Adventurous", "Wealthy", "Hungry", "Loved", "Active"] var backgroundPhotoNameArray : [String] = ["mood1.jpg", "mood2.jpg", "mood3.jpg", "mood4.jpg", "mood5.jpg", "mood6.jpg", "mood7.jpg", "mood8.jpg"] var photoNameArray : [String] = ["relax.png", "playful.png", "happy.png", "adventurous.png", "wealthy.png", "hungry.png", "loved.png", "active.png"] override func viewDidLoad() { super.viewDidLoad() self.collectionView!.registerNib(UINib(nibName: "MoodCollectionViewCell", bundle: nil), forCellWithReuseIdentifier: reuseIdentifier) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: UICollectionViewDataSource override func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int { //#warning Incomplete method implementation -- Return the number of sections return 1 } override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { //#warning Incomplete method implementation -- Return the number of items in the section return 8 } override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { let cell : MoodCollectionViewCell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! MoodCollectionViewCell // Configure the cell cell.backgroundImageView.image = UIImage(named: backgroundPhotoNameArray[indexPath.row]) cell.moodTitleLabel.text = moodArray[indexPath.row] cell.moodIconImageView.image = UIImage(named: photoNameArray[indexPath.row]) return cell } }
bsd-3-clause
0fa58ad118b10bdcf799412f14dd1fe4
40.433962
166
0.712659
4.732759
false
false
false
false
shahabc/ProjectNexus
Mobile Buy SDK Sample Apps/Advanced App - ObjC/MessageExtension/BuildIceCreamViewController.swift
1
6286
/* Copyright (C) 2016 Apple Inc. All Rights Reserved. See LICENSE.txt for this sample’s licensing information Abstract: The view controller shown to select an ice-cream part for a partially built ice cream. */ import UIKit class BuildIceCreamViewController: UIViewController { // MARK: Properties static let storyboardIdentifier = "BuildIceCreamViewController" weak var delegate: BuildIceCreamViewControllerDelegate? var iceCream: IceCream? { didSet { guard let iceCream = iceCream else { return } // Determine the ice cream parts to show in the collection view. if iceCream.base == nil { iceCreamParts = Base.all.map { $0 } prompt = NSLocalizedString("Select a base", comment: "") } else if iceCream.scoops == nil { iceCreamParts = Scoops.all.map { $0 } prompt = NSLocalizedString("Add some scoops", comment: "") } else if iceCream.topping == nil { iceCreamParts = Topping.all.map { $0 } prompt = NSLocalizedString("Finish with a topping", comment: "") } } } /// An array of `IceCreamPart`s to show in the collection view. fileprivate var iceCreamParts = [IceCreamPart]() { didSet { // Update the collection view to show the new ice cream parts. guard isViewLoaded else { return } collectionView.reloadData() } } private var prompt: String? @IBOutlet weak var promptLabel: UILabel! @IBOutlet weak var iceCreamView: IceCreamView! @IBOutlet weak var iceCreamViewHeightConstraint: NSLayoutConstraint! @IBOutlet weak var collectionView: UICollectionView! @IBOutlet weak var collectionViewHeightConstraint: NSLayoutConstraint! // MARK: UIViewController override func viewDidLoad() { super.viewDidLoad() // Make sure the prompt and ice cream view are showing the correct information. promptLabel.text = prompt iceCreamView.iceCream = iceCream /* We want the collection view to decelerate faster than normal so comes to rests on a body part more quickly. */ collectionView.decelerationRate = UIScrollViewDecelerationRateFast } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() // There is nothing to layout of there are no ice cream parts to pick from. guard !iceCreamParts.isEmpty else { return } guard let layout = collectionView.collectionViewLayout as? UICollectionViewFlowLayout else { fatalError("Expected the collection view to have a UICollectionViewFlowLayout") } // The ideal cell width is 1/3 of the width of the collection view. layout.itemSize.width = floor(view.bounds.size.width / 3.0) // Set the cell height using the aspect ratio of the ice cream part images. let iceCreamPartImageSize = iceCreamParts[0].image.size guard iceCreamPartImageSize.width > 0 else { return } let imageAspectRatio = iceCreamPartImageSize.width / iceCreamPartImageSize.height layout.itemSize.height = floor(layout.itemSize.width / imageAspectRatio) // Set the collection view's height constraint to match the cell size. collectionViewHeightConstraint.constant = layout.itemSize.height // Adjust the collection view's `contentInset` so the first item is centered. var contentInset = collectionView.contentInset contentInset.left = (view.bounds.size.width - layout.itemSize.width) / 2.0 contentInset.right = contentInset.left collectionView.contentInset = contentInset // Calculate the ideal height of the ice cream view. let iceCreamViewContentHeight = iceCreamView.arrangedSubviews.reduce(0.0) { total, arrangedSubview in return total + arrangedSubview.intrinsicContentSize.height } let iceCreamPartImageScale = layout.itemSize.height / iceCreamPartImageSize.height iceCreamViewHeightConstraint.constant = floor(iceCreamViewContentHeight * iceCreamPartImageScale) } // MARK: Interface Builder actions @IBAction func didTapSelect(_: AnyObject) { // Determine the index path of the centered cell in the collection view. guard let layout = collectionView.collectionViewLayout as? IceCreamPartCollectionViewLayout else { fatalError("Expected the collection view to have a IceCreamPartCollectionViewLayout") } let halfWidth = collectionView.bounds.size.width / 2.0 guard let indexPath = layout.indexPathForVisibleItemClosest(to: collectionView.contentOffset.x + halfWidth) else { return } // Call the delegate with the body part for the centered cell. delegate?.buildIceCreamViewController(self, didSelect: iceCreamParts[indexPath.row]) } } /** A delegate protocol for the `BuildIceCreamViewController` class. */ protocol BuildIceCreamViewControllerDelegate: class { /// Called when the user taps to select an `IceCreamPart` in the `BuildIceCreamViewController`. func buildIceCreamViewController(_ controller: BuildIceCreamViewController, didSelect iceCreamPart: IceCreamPart) } /** Extends `BuildIceCreamViewController` to conform to the `UICollectionViewDataSource` protocol. */ extension BuildIceCreamViewController: UICollectionViewDataSource { func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return iceCreamParts.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: IceCreamPartCell.reuseIdentifier, for: indexPath as IndexPath) as? IceCreamPartCell else { fatalError("Unable to dequeue a BodyPartCell") } let iceCreamPart = iceCreamParts[indexPath.row] cell.imageView.image = iceCreamPart.image return cell } }
mit
6bbb4275c3fc055a0d4f3c0eeb7e83d9
40.071895
220
0.68205
5.307432
false
false
false
false
Pencroff/ai-hackathon-2017
IOS APP/Pods/Cloudinary/Cloudinary/Features/ManagementApi/RequestsParams/CLDTextRequestParams.swift
1
8366
// // CLDTextRequestParams.swift // // Copyright (c) 2016 Cloudinary (http://cloudinary.com) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // import Foundation /** This class represents the different parameters that can be passed when performing a request to generate a text-image. */ open class CLDTextRequestParams: CLDRequestParams { // MARK: Init public override init() { super.init() } /** Initializes a CLDTextRequestParams instance. - parameter text: The text string to generate an image for. - returns: A new instance of CLDTextRequestParams. */ internal init(text: String) { super.init() setParam(TextParams.Text.rawValue, value: text) } /** Initializes a CLDTextRequestParams instance. - parameter params: A dictionary of the request parameters. - returns: A new instance of CLDTextRequestParams. */ public init(params: [String : AnyObject]) { super.init() self.params = params } // MARK: Set Params /** Set an identifier that is used for accessing the generated image. If not specified, a unique identifier is generated by Cloudinary. - parameter text: The identifier. - returns: A new instance of CLDTextRequestParams. */ @discardableResult open func setPublicId(_ publicId: String) -> CLDTextRequestParams { setParam(TextParams.PublicId.rawValue, value: publicId) return self } /** Set a font family. - parameter fontFamily: The name of the font family. - returns: A new instance of CLDTextRequestParams. */ @discardableResult open func setFontFamily(_ fontFamily: String) -> CLDTextRequestParams { setParam(TextParams.FontFamily.rawValue, value: fontFamily) return self } /** Set the font size in points. - parameter fontSize: The font size in points. default is 12. - returns: A new instance of CLDTextRequestParams. */ @discardableResult open func setFontSizeFromInt(_ fontSize: Int) -> CLDTextRequestParams { return setFontSize(String(fontSize)) } /** Set the font size in points. - parameter fontSize: The font size in points. default is 12. - returns: A new instance of CLDTextRequestParams. */ @discardableResult open func setFontSize(_ fontSize: String) -> CLDTextRequestParams { setParam(TextParams.FontSize.rawValue, value: fontSize) return self } /** Set the font size in points. - parameter fontColor: A name or RGB representation of the font's color. For example: `red` or #ff0000. default is black. - returns: A new instance of CLDTextRequestParams. */ @discardableResult open func setFontColor(_ fontColor: String) -> CLDTextRequestParams { setParam(TextParams.FontColor.rawValue, value: fontColor) return self } /** Set the font weight. - parameter fontWeight: The font weight to set. default is normal. - returns: A new instance of CLDTextRequestParams. */ @discardableResult @objc(setFontWeightFromFontWeight:) open func setFontWeight(_ fontWeight: CLDFontWeight) -> CLDTextRequestParams { return setFontWeight(String(describing: fontWeight)) } /** Set the font weight. - parameter fontWeight: The font weight to set. default is normal. - returns: A new instance of CLDTextRequestParams. */ @discardableResult open func setFontWeight(_ fontWeight: String) -> CLDTextRequestParams { setParam(TextParams.FontWeight.rawValue, value: fontWeight) return self } /** Set the font style. - parameter fontStyle: The font style to set. default is normal. - returns: A new instance of CLDTextRequestParams. */ @discardableResult @objc(setFontStyleFromFontStyle:) open func setFontStyle(_ fontStyle: CLDFontStyle) -> CLDTextRequestParams { return setFontStyle(String(describing: fontStyle)) } /** Set the font style. - parameter fontStyle: The font style to set. default is normal. - returns: A new instance of CLDTextRequestParams. */ @discardableResult open func setFontStyle(_ fontStyle: String) -> CLDTextRequestParams { setParam(TextParams.FontStyle.rawValue, value: fontStyle) return self } /** Set the background color. - parameter background: A name or RGB representation of the background color. For example: `red` or #ff0000. default is transparent. - returns: A new instance of CLDTextRequestParams. */ @discardableResult open func setBackground(_ background: String) -> CLDTextRequestParams { setParam(TextParams.Background.rawValue, value: background) return self } /** Set the text opacity level from 0 to 100. - parameter opacity: The text opacity value between 0 (invisible) and 100. default is 100. - returns: A new instance of CLDTextRequestParams. */ @discardableResult open func setOpacity(_ opacity: Int) -> CLDTextRequestParams { setParam(TextParams.Opacity.rawValue, value: opacity) return self } /** Set a text decoration to add the the generated text, for example: underline. - parameter textDecoration: The text decoration to set. default is none. - returns: A new instance of CLDTextRequestParams. */ @discardableResult @objc(setTextDecorationFromTextDecoration:) open func setTextDecoration(_ textDecoration: CLDTextDecoration) -> CLDTextRequestParams { return setTextDecoration(String(describing: textDecoration)) } /** Set a text decoration to add the the generated text, for example: underline. - parameter textDecoration: The text decoration to set. default is none. - returns: A new instance of CLDTextRequestParams. */ @discardableResult open func setTextDecoration(_ textDecoration: String) -> CLDTextRequestParams { setParam(TextParams.TextDecoration.rawValue, value: textDecoration) return self } fileprivate enum TextParams: String { case Text = "text" case PublicId = "public_id" case FontFamily = "font_family" case FontSize = "font_size" case FontColor = "font_color" case FontWeight = "font_weight" case FontStyle = "font_style" case Background = "background" case Opacity = "opacity" case TextDecoration = "text_decoration" } }
mit
04e1a391cede51bff2f000fc55a96a43
32.870445
140
0.624432
5.000598
false
false
false
false
temoki/Tortoise
Tortoise/Private/CommandDot.swift
1
847
// // CommandDot.swift // Tortoise // // Created by temoki on 2016/08/12. // Copyright © 2016 temoki. All rights reserved. // import CoreGraphics class CommandDot: Command { private let x: NumberOutput private let y: NumberOutput init(x: NumberOutput, y: NumberOutput) { self.x = x self.y = y } func execute(context: Context) { if context.penDown { let posX = x(TortoiseProperties(context: context)) let posY = y(TortoiseProperties(context: context)) let dotRect = CGRect(x: posX - (context.penWidth / 2), y: posY - (context.penWidth / 2), width: context.penWidth, height: context.penWidth) context.bitmapContext.fill(dotRect) } } }
mit
43ad96028f335c16409925de96f6a540
24.636364
66
0.547281
4.067308
false
false
false
false
february29/Learning
swift/Fch_Contact/Pods/RxSwift/RxSwift/Observables/Catch.swift
30
7682
// // Catch.swift // RxSwift // // Created by Krunoslav Zaher on 4/19/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // extension ObservableType { /** Continues an observable sequence that is terminated by an error with the observable sequence produced by the handler. - seealso: [catch operator on reactivex.io](http://reactivex.io/documentation/operators/catch.html) - parameter handler: Error handler function, producing another observable sequence. - returns: An observable sequence containing the source sequence's elements, followed by the elements produced by the handler's resulting observable sequence in case an error occurred. */ public func catchError(_ handler: @escaping (Swift.Error) throws -> Observable<E>) -> Observable<E> { return Catch(source: asObservable(), handler: handler) } /** Continues an observable sequence that is terminated by an error with a single element. - seealso: [catch operator on reactivex.io](http://reactivex.io/documentation/operators/catch.html) - parameter element: Last element in an observable sequence in case error occurs. - returns: An observable sequence containing the source sequence's elements, followed by the `element` in case an error occurred. */ public func catchErrorJustReturn(_ element: E) -> Observable<E> { return Catch(source: asObservable(), handler: { _ in Observable.just(element) }) } } extension ObservableType { /** Continues an observable sequence that is terminated by an error with the next observable sequence. - seealso: [catch operator on reactivex.io](http://reactivex.io/documentation/operators/catch.html) - returns: An observable sequence containing elements from consecutive source sequences until a source sequence terminates successfully. */ public static func catchError<S: Sequence>(_ sequence: S) -> Observable<E> where S.Iterator.Element == Observable<E> { return CatchSequence(sources: sequence) } } extension ObservableType { /** Repeats the source observable sequence until it successfully terminates. **This could potentially create an infinite sequence.** - seealso: [retry operator on reactivex.io](http://reactivex.io/documentation/operators/retry.html) - returns: Observable sequence to repeat until it successfully terminates. */ public func retry() -> Observable<E> { return CatchSequence(sources: InfiniteSequence(repeatedValue: self.asObservable())) } /** Repeats the source observable sequence the specified number of times in case of an error or until it successfully terminates. If you encounter an error and want it to retry once, then you must use `retry(2)` - seealso: [retry operator on reactivex.io](http://reactivex.io/documentation/operators/retry.html) - parameter maxAttemptCount: Maximum number of times to repeat the sequence. - returns: An observable sequence producing the elements of the given sequence repeatedly until it terminates successfully. */ public func retry(_ maxAttemptCount: Int) -> Observable<E> { return CatchSequence(sources: Swift.repeatElement(self.asObservable(), count: maxAttemptCount)) } } // catch with callback final fileprivate class CatchSinkProxy<O: ObserverType> : ObserverType { typealias E = O.E typealias Parent = CatchSink<O> private let _parent: Parent init(parent: Parent) { _parent = parent } func on(_ event: Event<E>) { _parent.forwardOn(event) switch event { case .next: break case .error, .completed: _parent.dispose() } } } final fileprivate class CatchSink<O: ObserverType> : Sink<O>, ObserverType { typealias E = O.E typealias Parent = Catch<E> private let _parent: Parent private let _subscription = SerialDisposable() init(parent: Parent, observer: O, cancel: Cancelable) { _parent = parent super.init(observer: observer, cancel: cancel) } func run() -> Disposable { let d1 = SingleAssignmentDisposable() _subscription.disposable = d1 d1.setDisposable(_parent._source.subscribe(self)) return _subscription } func on(_ event: Event<E>) { switch event { case .next: forwardOn(event) case .completed: forwardOn(event) dispose() case .error(let error): do { let catchSequence = try _parent._handler(error) let observer = CatchSinkProxy(parent: self) _subscription.disposable = catchSequence.subscribe(observer) } catch let e { forwardOn(.error(e)) dispose() } } } } final fileprivate class Catch<Element> : Producer<Element> { typealias Handler = (Swift.Error) throws -> Observable<Element> fileprivate let _source: Observable<Element> fileprivate let _handler: Handler init(source: Observable<Element>, handler: @escaping Handler) { _source = source _handler = handler } override func run<O: ObserverType>(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == Element { let sink = CatchSink(parent: self, observer: observer, cancel: cancel) let subscription = sink.run() return (sink: sink, subscription: subscription) } } // catch enumerable final fileprivate class CatchSequenceSink<S: Sequence, O: ObserverType> : TailRecursiveSink<S, O> , ObserverType where S.Iterator.Element : ObservableConvertibleType, S.Iterator.Element.E == O.E { typealias Element = O.E typealias Parent = CatchSequence<S> private var _lastError: Swift.Error? override init(observer: O, cancel: Cancelable) { super.init(observer: observer, cancel: cancel) } func on(_ event: Event<Element>) { switch event { case .next: forwardOn(event) case .error(let error): _lastError = error schedule(.moveNext) case .completed: forwardOn(event) dispose() } } override func subscribeToNext(_ source: Observable<E>) -> Disposable { return source.subscribe(self) } override func done() { if let lastError = _lastError { forwardOn(.error(lastError)) } else { forwardOn(.completed) } self.dispose() } override func extract(_ observable: Observable<Element>) -> SequenceGenerator? { if let onError = observable as? CatchSequence<S> { return (onError.sources.makeIterator(), nil) } else { return nil } } } final fileprivate class CatchSequence<S: Sequence> : Producer<S.Iterator.Element.E> where S.Iterator.Element : ObservableConvertibleType { typealias Element = S.Iterator.Element.E let sources: S init(sources: S) { self.sources = sources } override func run<O : ObserverType>(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == Element { let sink = CatchSequenceSink<S, O>(observer: observer, cancel: cancel) let subscription = sink.run((self.sources.makeIterator(), nil)) return (sink: sink, subscription: subscription) } }
mit
9ca51f357d66c8df656150b009d172eb
31.685106
189
0.643145
4.744287
false
false
false
false
milseman/swift
test/SILGen/vtable_thunks_reabstraction.swift
9
50775
// RUN: %target-swift-frontend -emit-silgen %s | %FileCheck %s struct S {} class B {} class C: B {} class D: C {} func callMethodsOnOpaque<T, U>(o: Opaque<T>, t: T, u: U, tt: T.Type) { _ = o.inAndOut(x: t) _ = o.inAndOutGeneric(x: t, y: u) _ = o.inAndOutMetatypes(x: tt) _ = o.inAndOutTuples(x: (t, (tt, { $0 }))) _ = o.variantOptionality(x: t) _ = o.variantOptionalityMetatypes(x: tt) _ = o.variantOptionalityFunctions(x: { $0 }) _ = o.variantOptionalityTuples(x: (t, (tt, { $0 }))) } func callMethodsOnStillOpaque<T, U>(o: StillOpaque<T>, t: T, u: U, tt: T.Type) { _ = o.inAndOut(x: t) _ = o.inAndOutGeneric(x: t, y: u) _ = o.inAndOutMetatypes(x: tt) _ = o.inAndOutTuples(x: (t, (tt, { $0 }))) _ = o.variantOptionality(x: t) _ = o.variantOptionalityMetatypes(x: tt) _ = o.variantOptionalityFunctions(x: { $0 }) _ = o.variantOptionalityTuples(x: (t, (tt, { $0 }))) } func callMethodsOnConcreteValue<U>(o: ConcreteValue, t: S, u: U, tt: S.Type) { _ = o.inAndOut(x: t) _ = o.inAndOutGeneric(x: t, y: u) _ = o.inAndOutMetatypes(x: tt) _ = o.inAndOutTuples(x: (t, (tt, { $0 }))) _ = o.variantOptionality(x: t) _ = o.variantOptionalityMetatypes(x: tt) _ = o.variantOptionalityFunctions(x: { $0 }) _ = o.variantOptionalityTuples(x: (t, (tt, { $0 }))) } func callMethodsOnConcreteClass<U>(o: ConcreteClass, t: C, u: U, tt: C.Type) { _ = o.inAndOut(x: t) _ = o.inAndOutGeneric(x: t, y: u) _ = o.inAndOutMetatypes(x: tt) _ = o.inAndOutTuples(x: (t, (tt, { $0 }))) _ = o.variantOptionality(x: t) _ = o.variantOptionalityMetatypes(x: tt) _ = o.variantOptionalityFunctions(x: { $0 }) _ = o.variantOptionalityTuples(x: (t, (tt, { $0 }))) } func callMethodsOnConcreteClassVariance<U>(o: ConcreteClassVariance, b: B, c: C, u: U, tt: C.Type) { _ = o.inAndOut(x: b) _ = o.inAndOutGeneric(x: c, y: u) _ = o.inAndOutMetatypes(x: tt) _ = o.inAndOutTuples(x: (c, (tt, { $0 }))) _ = o.variantOptionality(x: b) _ = o.variantOptionalityMetatypes(x: tt) _ = o.variantOptionalityFunctions(x: { $0 }) _ = o.variantOptionalityTuples(x: (c, (tt, { $0 }))) } func callMethodsOnOpaqueTuple<T, U>(o: OpaqueTuple<T>, t: (T, T), u: U, tt: (T, T).Type) { _ = o.inAndOut(x: t) _ = o.inAndOutGeneric(x: t, y: u) _ = o.inAndOutMetatypes(x: tt) _ = o.inAndOutTuples(x: (t, (tt, { $0 }))) _ = o.variantOptionality(x: t) _ = o.variantOptionalityMetatypes(x: tt) _ = o.variantOptionalityFunctions(x: { $0 }) _ = o.variantOptionalityTuples(x: (t, (tt, { $0 }))) } func callMethodsOnConcreteTuple<U>(o: ConcreteTuple, t: (S, S), u: U, tt: (S, S).Type) { _ = o.inAndOut(x: t) _ = o.inAndOutGeneric(x: t, y: u) _ = o.inAndOutMetatypes(x: tt) _ = o.inAndOutTuples(x: (t, (tt, { $0 }))) _ = o.variantOptionality(x: t) _ = o.variantOptionalityMetatypes(x: tt) _ = o.variantOptionalityFunctions(x: { $0 }) _ = o.variantOptionalityTuples(x: (t, (tt, { $0 }))) } func callMethodsOnOpaqueFunction<X, Y, U>(o: OpaqueFunction<X, Y>, t: @escaping (X) -> Y, u: U, tt: ((X) -> Y).Type) { _ = o.inAndOut(x: t) _ = o.inAndOutGeneric(x: t, y: u) _ = o.inAndOutMetatypes(x: tt) _ = o.inAndOutTuples(x: (t, (tt, { $0 }))) _ = o.variantOptionality(x: t) _ = o.variantOptionalityMetatypes(x: tt) _ = o.variantOptionalityFunctions(x: { $0 }) _ = o.variantOptionalityTuples(x: (t, (tt, { $0 }))) } func callMethodsOnConcreteFunction<U>(o: ConcreteFunction, t: @escaping (S) -> S, u: U, tt: ((S) -> S).Type) { _ = o.inAndOut(x: t) _ = o.inAndOutGeneric(x: t, y: u) _ = o.inAndOutMetatypes(x: tt) _ = o.inAndOutTuples(x: (t, (tt, { $0 }))) _ = o.variantOptionality(x: t) _ = o.variantOptionalityMetatypes(x: tt) _ = o.variantOptionalityFunctions(x: { $0 }) _ = o.variantOptionalityTuples(x: (t, (tt, { $0 }))) } func callMethodsOnOpaqueMetatype<T, U>(o: OpaqueMetatype<T>, t: T.Type, u: U, tt: T.Type.Type) { _ = o.inAndOut(x: t) _ = o.inAndOutGeneric(x: t, y: u) _ = o.inAndOutMetatypes(x: tt) _ = o.inAndOutTuples(x: (t, (tt, { $0 }))) _ = o.variantOptionality(x: t) _ = o.variantOptionalityMetatypes(x: tt) _ = o.variantOptionalityFunctions(x: { $0 }) _ = o.variantOptionalityTuples(x: (t, (tt, { $0 }))) } func callMethodsOnConcreteValueMetatype<U>(o: ConcreteValueMetatype, t: S.Type, u: U, tt: S.Type.Type) { _ = o.inAndOut(x: t) _ = o.inAndOutGeneric(x: t, y: u) _ = o.inAndOutMetatypes(x: tt) _ = o.inAndOutTuples(x: (t, (tt, { $0 }))) _ = o.variantOptionality(x: t) _ = o.variantOptionalityMetatypes(x: tt) _ = o.variantOptionalityFunctions(x: { $0 }) _ = o.variantOptionalityTuples(x: (t, (tt, { $0 }))) } func callMethodsOnConcreteClassMetatype<U>(o: ConcreteClassMetatype, t: C.Type, u: U, tt: C.Type.Type) { _ = o.inAndOut(x: t) _ = o.inAndOutGeneric(x: t, y: u) _ = o.inAndOutMetatypes(x: tt) _ = o.inAndOutTuples(x: (t, (tt, { $0 }))) _ = o.variantOptionality(x: t) _ = o.variantOptionalityMetatypes(x: tt) _ = o.variantOptionalityFunctions(x: { $0 }) _ = o.variantOptionalityTuples(x: (t, (tt, { $0 }))) } func callMethodsOnConcreteOptional<U>(o: ConcreteOptional, t: S?, u: U, tt: S?.Type) { _ = o.inAndOut(x: t) _ = o.inAndOutGeneric(x: t, y: u) _ = o.inAndOutMetatypes(x: tt) _ = o.inAndOutTuples(x: (t, (tt, { $0 }))) _ = o.variantOptionality(x: t) _ = o.variantOptionalityMetatypes(x: tt) _ = o.variantOptionalityFunctions(x: { $0 }) _ = o.variantOptionalityTuples(x: (t, (tt, { $0 }))) } class Opaque<T> { typealias ObnoxiousTuple = (T, (T.Type, (T) -> T)) func inAndOut(x: T) -> T { return x } func inAndOutGeneric<U>(x: T, y: U) -> U { return y } func inAndOutMetatypes(x: T.Type) -> T.Type { return x } func inAndOutFunctions(x: @escaping (T) -> T) -> (T) -> T { return x } func inAndOutTuples(x: ObnoxiousTuple) -> ObnoxiousTuple { return x } func variantOptionality(x: T) -> T? { return x } func variantOptionalityMetatypes(x: T.Type) -> T.Type? { return x } func variantOptionalityFunctions(x: @escaping (T) -> T) -> ((T) -> T)? { return x } func variantOptionalityTuples(x: ObnoxiousTuple) -> ObnoxiousTuple? { return x } } // CHECK-LABEL: sil_vtable Opaque { // CHECK-NEXT: #Opaque.inAndOut!1: <T> (Opaque<T>) -> (T) -> T : _T027vtable_thunks_reabstraction6OpaqueC8inAndOutxx1x_tF // Opaque.inAndOut(x:) // CHECK-NEXT: #Opaque.inAndOutGeneric!1: <T><U> (Opaque<T>) -> (T, U) -> U : _T027vtable_thunks_reabstraction6OpaqueC15inAndOutGenericqd__x1x_qd__1ytlF // Opaque.inAndOutGeneric<A>(x:y:) // CHECK-NEXT: #Opaque.inAndOutMetatypes!1: <T> (Opaque<T>) -> (T.Type) -> T.Type : _T027vtable_thunks_reabstraction6OpaqueC17inAndOutMetatypesxmxm1x_tF // Opaque.inAndOutMetatypes(x:) // CHECK-NEXT: #Opaque.inAndOutFunctions!1: <T> (Opaque<T>) -> (@escaping (T) -> T) -> (T) -> T : _T027vtable_thunks_reabstraction6OpaqueC17inAndOutFunctionsxxcxxc1x_tF // Opaque.inAndOutFunctions(x:) // CHECK-NEXT: #Opaque.inAndOutTuples!1: <T> (Opaque<T>) -> ((T, (T.Type, (T) -> T))) -> (T, (T.Type, (T) -> T)) : _T027vtable_thunks_reabstraction6OpaqueC14inAndOutTuplesx_xm_xxcttx_xm_xxctt1x_tF // Opaque.inAndOutTuples(x:) // CHECK-NEXT: #Opaque.variantOptionality!1: <T> (Opaque<T>) -> (T) -> T? : _T027vtable_thunks_reabstraction6OpaqueC18variantOptionalityxSgx1x_tF // Opaque.variantOptionality(x:) // CHECK-NEXT: #Opaque.variantOptionalityMetatypes!1: <T> (Opaque<T>) -> (T.Type) -> T.Type? : _T027vtable_thunks_reabstraction6OpaqueC27variantOptionalityMetatypesxmSgxm1x_tF // Opaque.variantOptionalityMetatypes(x:) // CHECK-NEXT: #Opaque.variantOptionalityFunctions!1: <T> (Opaque<T>) -> (@escaping (T) -> T) -> ((T) -> T)? : _T027vtable_thunks_reabstraction6OpaqueC27variantOptionalityFunctionsxxcSgxxc1x_tF // Opaque.variantOptionalityFunctions(x:) // CHECK-NEXT: #Opaque.variantOptionalityTuples!1: <T> (Opaque<T>) -> ((T, (T.Type, (T) -> T))) -> (T, (T.Type, (T) -> T))? : _T027vtable_thunks_reabstraction6OpaqueC24variantOptionalityTuplesx_xm_xxcttSgx_xm_xxctt1x_tF // Opaque.variantOptionalityTuples(x:) // CHECK-NEXT: #Opaque.init!initializer.1: <T> (Opaque<T>.Type) -> () -> Opaque<T> : _T027vtable_thunks_reabstraction6OpaqueCACyxGycfc // Opaque.init() // CHECK-NEXT: #Opaque.deinit!deallocator: _T027vtable_thunks_reabstraction6OpaqueCfD // Opaque.__deallocating_deinit // CHECK-NEXT: } class StillOpaque<T>: Opaque<T> { override func variantOptionalityTuples(x: ObnoxiousTuple?) -> ObnoxiousTuple { return x! } } // CHECK-LABEL: sil_vtable StillOpaque { // CHECK-NEXT: #Opaque.inAndOut!1: <T> (Opaque<T>) -> (T) -> T : _T027vtable_thunks_reabstraction6OpaqueC8inAndOutxx1x_tF // Opaque.inAndOut(x:) // CHECK-NEXT: #Opaque.inAndOutGeneric!1: <T><U> (Opaque<T>) -> (T, U) -> U : _T027vtable_thunks_reabstraction6OpaqueC15inAndOutGenericqd__x1x_qd__1ytlF // Opaque.inAndOutGeneric<A>(x:y:) // CHECK-NEXT: #Opaque.inAndOutMetatypes!1: <T> (Opaque<T>) -> (T.Type) -> T.Type : _T027vtable_thunks_reabstraction6OpaqueC17inAndOutMetatypesxmxm1x_tF // Opaque.inAndOutMetatypes(x:) // CHECK-NEXT: #Opaque.inAndOutFunctions!1: <T> (Opaque<T>) -> (@escaping (T) -> T) -> (T) -> T : _T027vtable_thunks_reabstraction6OpaqueC17inAndOutFunctionsxxcxxc1x_tF // Opaque.inAndOutFunctions(x:) // CHECK-NEXT: #Opaque.inAndOutTuples!1: <T> (Opaque<T>) -> ((T, (T.Type, (T) -> T))) -> (T, (T.Type, (T) -> T)) : _T027vtable_thunks_reabstraction6OpaqueC14inAndOutTuplesx_xm_xxcttx_xm_xxctt1x_tF // Opaque.inAndOutTuples(x:) // CHECK-NEXT: #Opaque.variantOptionality!1: <T> (Opaque<T>) -> (T) -> T? : _T027vtable_thunks_reabstraction6OpaqueC18variantOptionalityxSgx1x_tF // Opaque.variantOptionality(x:) // CHECK-NEXT: #Opaque.variantOptionalityMetatypes!1: <T> (Opaque<T>) -> (T.Type) -> T.Type? : _T027vtable_thunks_reabstraction6OpaqueC27variantOptionalityMetatypesxmSgxm1x_tF // Opaque.variantOptionalityMetatypes(x:) // CHECK-NEXT: #Opaque.variantOptionalityFunctions!1: <T> (Opaque<T>) -> (@escaping (T) -> T) -> ((T) -> T)? : _T027vtable_thunks_reabstraction6OpaqueC27variantOptionalityFunctionsxxcSgxxc1x_tF // Opaque.variantOptionalityFunctions(x:) // CHECK-NEXT: #Opaque.variantOptionalityTuples!1: <T> (Opaque<T>) -> ((T, (T.Type, (T) -> T))) -> (T, (T.Type, (T) -> T))? : hidden _T027vtable_thunks_reabstraction11StillOpaqueC24variantOptionalityTuplesx_xm_xxcttx_xm_xxcttSg1x_tFAA0E0CAdEx_xm_xxcttAF_tFTV // vtable thunk for Opaque.variantOptionalityTuples(x:) dispatching to StillOpaque.variantOptionalityTuples(x:) // CHECK-NEXT: #Opaque.init!initializer.1: <T> (Opaque<T>.Type) -> () -> Opaque<T> : _T027vtable_thunks_reabstraction11StillOpaqueCACyxGycfc // StillOpaque.init() // Tuple becomes more optional -- needs new vtable entry // CHECK-NEXT: #StillOpaque.variantOptionalityTuples!1: <T> (StillOpaque<T>) -> ((T, (T.Type, (T) -> T))?) -> (T, (T.Type, (T) -> T)) : _T027vtable_thunks_reabstraction11StillOpaqueC24variantOptionalityTuplesx_xm_xxcttx_xm_xxcttSg1x_tF // StillOpaque.variantOptionalityTuples(x:) // CHECK-NEXT: #StillOpaque.deinit!deallocator: _T027vtable_thunks_reabstraction11StillOpaqueCfD // StillOpaque.__deallocating_deinit // CHECK-NEXT: } class ConcreteValue: Opaque<S> { override func inAndOut(x: S) -> S { return x } override func inAndOutGeneric<Z>(x: S, y: Z) -> Z { return y } override func inAndOutMetatypes(x: S.Type) -> S.Type { return x } override func inAndOutFunctions(x: @escaping (S) -> S) -> (S) -> S { return x } override func inAndOutTuples(x: ObnoxiousTuple) -> ObnoxiousTuple { return x } override func variantOptionality(x: S?) -> S { return x! } override func variantOptionalityMetatypes(x: S.Type?) -> S.Type { return x! } override func variantOptionalityFunctions(x: ((S) -> S)?) -> (S) -> S { return x! } override func variantOptionalityTuples(x: ObnoxiousTuple?) -> ObnoxiousTuple { return x! } } // CHECK-LABEL: sil_vtable ConcreteValue { // CHECK-NEXT: #Opaque.inAndOut!1: <T> (Opaque<T>) -> (T) -> T : hidden _T027vtable_thunks_reabstraction13ConcreteValueC8inAndOutAA1SVAF1x_tFAA6OpaqueCADxxAG_tFTV // vtable thunk for Opaque.inAndOut(x:) dispatching to ConcreteValue.inAndOut(x:) // CHECK-NEXT: #Opaque.inAndOutGeneric!1: <T><U> (Opaque<T>) -> (T, U) -> U : hidden _T027vtable_thunks_reabstraction13ConcreteValueC15inAndOutGenericxAA1SV1x_x1ytlFAA6OpaqueCADqd__xAG_qd__AHtlFTV // vtable thunk for Opaque.inAndOutGeneric<A>(x:y:) dispatching to ConcreteValue.inAndOutGeneric<A>(x:y:) // CHECK-NEXT: #Opaque.inAndOutMetatypes!1: <T> (Opaque<T>) -> (T.Type) -> T.Type : hidden _T027vtable_thunks_reabstraction13ConcreteValueC17inAndOutMetatypesAA1SVmAFm1x_tFAA6OpaqueCADxmxmAG_tFTV // vtable thunk for Opaque.inAndOutMetatypes(x:) dispatching to ConcreteValue.inAndOutMetatypes(x:) // CHECK-NEXT: #Opaque.inAndOutFunctions!1: <T> (Opaque<T>) -> (@escaping (T) -> T) -> (T) -> T : hidden _T027vtable_thunks_reabstraction13ConcreteValueC17inAndOutFunctionsAA1SVAFcA2Fc1x_tFAA6OpaqueCADxxcxxcAG_tFTV // vtable thunk for Opaque.inAndOutFunctions(x:) dispatching to ConcreteValue.inAndOutFunctions(x:) // CHECK-NEXT: #Opaque.inAndOutTuples!1: <T> (Opaque<T>) -> ((T, (T.Type, (T) -> T))) -> (T, (T.Type, (T) -> T)) : hidden _T027vtable_thunks_reabstraction13ConcreteValueC14inAndOutTuplesAA1SV_AFm_A2FcttAF_AFm_A2Fctt1x_tFAA6OpaqueCADx_xm_xxcttx_xm_xxcttAG_tFTV // vtable thunk for Opaque.inAndOutTuples(x:) dispatching to ConcreteValue.inAndOutTuples(x:) // CHECK-NEXT: #Opaque.variantOptionality!1: <T> (Opaque<T>) -> (T) -> T? : hidden _T027vtable_thunks_reabstraction13ConcreteValueC18variantOptionalityAA1SVAFSg1x_tFAA6OpaqueCADxSgxAH_tFTV // vtable thunk for Opaque.variantOptionality(x:) dispatching to ConcreteValue.variantOptionality(x:) // CHECK-NEXT: #Opaque.variantOptionalityMetatypes!1: <T> (Opaque<T>) -> (T.Type) -> T.Type? : hidden _T027vtable_thunks_reabstraction13ConcreteValueC27variantOptionalityMetatypesAA1SVmAFmSg1x_tFAA6OpaqueCADxmSgxmAH_tFTV // vtable thunk for Opaque.variantOptionalityMetatypes(x:) dispatching to ConcreteValue.variantOptionalityMetatypes(x:) // CHECK-NEXT: #Opaque.variantOptionalityFunctions!1: <T> (Opaque<T>) -> (@escaping (T) -> T) -> ((T) -> T)? : hidden _T027vtable_thunks_reabstraction13ConcreteValueC27variantOptionalityFunctionsAA1SVAFcA2FcSg1x_tFAA6OpaqueCADxxcSgxxcAH_tFTV // vtable thunk for Opaque.variantOptionalityFunctions(x:) dispatching to ConcreteValue.variantOptionalityFunctions(x:) // CHECK-NEXT: #Opaque.variantOptionalityTuples!1: <T> (Opaque<T>) -> ((T, (T.Type, (T) -> T))) -> (T, (T.Type, (T) -> T))? : hidden _T027vtable_thunks_reabstraction13ConcreteValueC24variantOptionalityTuplesAA1SV_AFm_A2FcttAF_AFm_A2FcttSg1x_tFAA6OpaqueCADx_xm_xxcttSgx_xm_xxcttAH_tFTV // vtable thunk for Opaque.variantOptionalityTuples(x:) dispatching to ConcreteValue.variantOptionalityTuples(x:) // CHECK-NEXT: #Opaque.init!initializer.1: <T> (Opaque<T>.Type) -> () -> Opaque<T> : _T027vtable_thunks_reabstraction13ConcreteValueCACycfc // ConcreteValue.init() // Value types becoming more optional -- needs new vtable entry // CHECK-NEXT: #ConcreteValue.variantOptionality!1: (ConcreteValue) -> (S?) -> S : _T027vtable_thunks_reabstraction13ConcreteValueC18variantOptionalityAA1SVAFSg1x_tF // ConcreteValue.variantOptionality(x:) // CHECK-NEXT: #ConcreteValue.variantOptionalityMetatypes!1: (ConcreteValue) -> (S.Type?) -> S.Type : _T027vtable_thunks_reabstraction13ConcreteValueC27variantOptionalityMetatypesAA1SVmAFmSg1x_tF // ConcreteValue.variantOptionalityMetatypes(x:) // CHECK-NEXT: #ConcreteValue.variantOptionalityFunctions!1: (ConcreteValue) -> (((S) -> S)?) -> (S) -> S : _T027vtable_thunks_reabstraction13ConcreteValueC27variantOptionalityFunctionsAA1SVAFcA2FcSg1x_tF // ConcreteValue.variantOptionalityFunctions(x:) // CHECK-NEXT: #ConcreteValue.variantOptionalityTuples!1: (ConcreteValue) -> ((S, (S.Type, (S) -> S))?) -> (S, (S.Type, (S) -> S)) : _T027vtable_thunks_reabstraction13ConcreteValueC24variantOptionalityTuplesAA1SV_AFm_A2FcttAF_AFm_A2FcttSg1x_tF // ConcreteValue.variantOptionalityTuples(x:) // CHECK-NEXT: #ConcreteValue.deinit!deallocator: _T027vtable_thunks_reabstraction13ConcreteValueCfD // ConcreteValue.__deallocating_deinit // CHECK-NEXT: } class ConcreteClass: Opaque<C> { override func inAndOut(x: C) -> C { return x } override func inAndOutMetatypes(x: C.Type) -> C.Type { return x } override func inAndOutFunctions(x: @escaping (C) -> C) -> (C) -> C { return x } override func inAndOutTuples(x: ObnoxiousTuple) -> ObnoxiousTuple { return x } override func variantOptionality(x: C?) -> C { return x! } override func variantOptionalityMetatypes(x: C.Type?) -> C.Type { return x! } override func variantOptionalityFunctions(x: ((C) -> C)?) -> (C) -> C { return x! } override func variantOptionalityTuples(x: ObnoxiousTuple?) -> ObnoxiousTuple { return x! } } // CHECK-LABEL: sil_vtable ConcreteClass { // CHECK-NEXT: #Opaque.inAndOut!1: <T> (Opaque<T>) -> (T) -> T : hidden _T027vtable_thunks_reabstraction13ConcreteClassC8inAndOutAA1CCAF1x_tFAA6OpaqueCADxxAG_tFTV // vtable thunk for Opaque.inAndOut(x:) dispatching to ConcreteClass.inAndOut(x:) // CHECK-NEXT: #Opaque.inAndOutGeneric!1: <T><U> (Opaque<T>) -> (T, U) -> U : _T027vtable_thunks_reabstraction6OpaqueC15inAndOutGenericqd__x1x_qd__1ytlF // Opaque.inAndOutGeneric<A>(x:y:) // CHECK-NEXT: #Opaque.inAndOutMetatypes!1: <T> (Opaque<T>) -> (T.Type) -> T.Type : _T027vtable_thunks_reabstraction13ConcreteClassC17inAndOutMetatypesAA1CCmAFm1x_tF // ConcreteClass.inAndOutMetatypes(x:) // CHECK-NEXT: #Opaque.inAndOutFunctions!1: <T> (Opaque<T>) -> (@escaping (T) -> T) -> (T) -> T : hidden _T027vtable_thunks_reabstraction13ConcreteClassC17inAndOutFunctionsAA1CCAFcA2Fc1x_tFAA6OpaqueCADxxcxxcAG_tFTV // vtable thunk for Opaque.inAndOutFunctions(x:) dispatching to ConcreteClass.inAndOutFunctions(x:) // CHECK-NEXT: #Opaque.inAndOutTuples!1: <T> (Opaque<T>) -> ((T, (T.Type, (T) -> T))) -> (T, (T.Type, (T) -> T)) : hidden _T027vtable_thunks_reabstraction13ConcreteClassC14inAndOutTuplesAA1CC_AFm_A2FcttAF_AFm_A2Fctt1x_tFAA6OpaqueCADx_xm_xxcttx_xm_xxcttAG_tFTV // vtable thunk for Opaque.inAndOutTuples(x:) dispatching to ConcreteClass.inAndOutTuples(x:) // CHECK-NEXT: #Opaque.variantOptionality!1: <T> (Opaque<T>) -> (T) -> T? : hidden _T027vtable_thunks_reabstraction13ConcreteClassC18variantOptionalityAA1CCAFSg1x_tFAA6OpaqueCADxSgxAH_tFTV // vtable thunk for Opaque.variantOptionality(x:) dispatching to ConcreteClass.variantOptionality(x:) // CHECK-NEXT: #Opaque.variantOptionalityMetatypes!1: <T> (Opaque<T>) -> (T.Type) -> T.Type? : _T027vtable_thunks_reabstraction13ConcreteClassC27variantOptionalityMetatypesAA1CCmAFmSg1x_tF // ConcreteClass.variantOptionalityMetatypes(x:) // CHECK-NEXT: #Opaque.variantOptionalityFunctions!1: <T> (Opaque<T>) -> (@escaping (T) -> T) -> ((T) -> T)? : hidden _T027vtable_thunks_reabstraction13ConcreteClassC27variantOptionalityFunctionsAA1CCAFcA2FcSg1x_tFAA6OpaqueCADxxcSgxxcAH_tFTV // vtable thunk for Opaque.variantOptionalityFunctions(x:) dispatching to ConcreteClass.variantOptionalityFunctions(x:) // CHECK-NEXT: #Opaque.variantOptionalityTuples!1: <T> (Opaque<T>) -> ((T, (T.Type, (T) -> T))) -> (T, (T.Type, (T) -> T))? : hidden _T027vtable_thunks_reabstraction13ConcreteClassC24variantOptionalityTuplesAA1CC_AFm_A2FcttAF_AFm_A2FcttSg1x_tFAA6OpaqueCADx_xm_xxcttSgx_xm_xxcttAH_tFTV // vtable thunk for Opaque.variantOptionalityTuples(x:) dispatching to ConcreteClass.variantOptionalityTuples(x:) // CHECK-NEXT: #Opaque.init!initializer.1: <T> (Opaque<T>.Type) -> () -> Opaque<T> : _T027vtable_thunks_reabstraction13ConcreteClassCACycfc // ConcreteClass.init() // Class references are ABI-compatible with optional class references, and // similarly for class metatypes. // // Function and tuple optionality change still needs a new vtable entry // as above. // CHECK-NEXT: #ConcreteClass.variantOptionalityFunctions!1: (ConcreteClass) -> (((C) -> C)?) -> (C) -> C : _T027vtable_thunks_reabstraction13ConcreteClassC27variantOptionalityFunctionsAA1CCAFcA2FcSg1x_tF // ConcreteClass.variantOptionalityFunctions(x:) // CHECK-NEXT: #ConcreteClass.variantOptionalityTuples!1: (ConcreteClass) -> ((C, (C.Type, (C) -> C))?) -> (C, (C.Type, (C) -> C)) : _T027vtable_thunks_reabstraction13ConcreteClassC24variantOptionalityTuplesAA1CC_AFm_A2FcttAF_AFm_A2FcttSg1x_tF // ConcreteClass.variantOptionalityTuples(x:) // CHECK-NEXT: #ConcreteClass.deinit!deallocator: _T027vtable_thunks_reabstraction13ConcreteClassCfD // ConcreteClass.__deallocating_deinit // CHECK-NEXT: } class ConcreteClassVariance: Opaque<C> { override func inAndOut(x: B) -> D { return x as! D } override func variantOptionality(x: B?) -> D { return x as! D } } // CHECK-LABEL: sil_vtable ConcreteClassVariance { // CHECK-NEXT: #Opaque.inAndOut!1: <T> (Opaque<T>) -> (T) -> T : hidden _T027vtable_thunks_reabstraction21ConcreteClassVarianceC8inAndOutAA1DCAA1BC1x_tFAA6OpaqueCADxxAI_tFTV // vtable thunk for Opaque.inAndOut(x:) dispatching to ConcreteClassVariance.inAndOut(x:) // CHECK-NEXT: #Opaque.inAndOutGeneric!1: <T><U> (Opaque<T>) -> (T, U) -> U : _T027vtable_thunks_reabstraction6OpaqueC15inAndOutGenericqd__x1x_qd__1ytlF // Opaque.inAndOutGeneric<A>(x:y:) // CHECK-NEXT: #Opaque.inAndOutMetatypes!1: <T> (Opaque<T>) -> (T.Type) -> T.Type : _T027vtable_thunks_reabstraction6OpaqueC17inAndOutMetatypesxmxm1x_tF // Opaque.inAndOutMetatypes(x:) // CHECK-NEXT: #Opaque.inAndOutFunctions!1: <T> (Opaque<T>) -> (@escaping (T) -> T) -> (T) -> T : _T027vtable_thunks_reabstraction6OpaqueC17inAndOutFunctionsxxcxxc1x_tF // Opaque.inAndOutFunctions(x:) // CHECK-NEXT: #Opaque.inAndOutTuples!1: <T> (Opaque<T>) -> ((T, (T.Type, (T) -> T))) -> (T, (T.Type, (T) -> T)) : _T027vtable_thunks_reabstraction6OpaqueC14inAndOutTuplesx_xm_xxcttx_xm_xxctt1x_tF // Opaque.inAndOutTuples(x:) // CHECK-NEXT: #Opaque.variantOptionality!1: <T> (Opaque<T>) -> (T) -> T? : hidden _T027vtable_thunks_reabstraction21ConcreteClassVarianceC18variantOptionalityAA1DCAA1BCSg1x_tFAA6OpaqueCADxSgxAJ_tFTV // vtable thunk for Opaque.variantOptionality(x:) dispatching to ConcreteClassVariance.variantOptionality(x:) // CHECK-NEXT: #Opaque.variantOptionalityMetatypes!1: <T> (Opaque<T>) -> (T.Type) -> T.Type? : _T027vtable_thunks_reabstraction6OpaqueC27variantOptionalityMetatypesxmSgxm1x_tF // Opaque.variantOptionalityMetatypes(x:) // CHECK-NEXT: #Opaque.variantOptionalityFunctions!1: <T> (Opaque<T>) -> (@escaping (T) -> T) -> ((T) -> T)? : _T027vtable_thunks_reabstraction6OpaqueC27variantOptionalityFunctionsxxcSgxxc1x_tF // Opaque.variantOptionalityFunctions(x:) // CHECK-NEXT: #Opaque.variantOptionalityTuples!1: <T> (Opaque<T>) -> ((T, (T.Type, (T) -> T))) -> (T, (T.Type, (T) -> T))? : _T027vtable_thunks_reabstraction6OpaqueC24variantOptionalityTuplesx_xm_xxcttSgx_xm_xxctt1x_tF // Opaque.variantOptionalityTuples(x:) // CHECK-NEXT: #Opaque.init!initializer.1: <T> (Opaque<T>.Type) -> () -> Opaque<T> : _T027vtable_thunks_reabstraction21ConcreteClassVarianceCACycfc // ConcreteClassVariance.init() // No new vtable entries -- class references are ABI compatible with // optional class references. // CHECK-NEXT: #ConcreteClassVariance.deinit!deallocator: _T027vtable_thunks_reabstraction21ConcreteClassVarianceCfD // ConcreteClassVariance.__deallocating_deinit // CHECK-NEXT: } class OpaqueTuple<U>: Opaque<(U, U)> { override func inAndOut(x: (U, U)) -> (U, U) { return x } override func variantOptionality(x: (U, U)?) -> (U, U) { return x! } } // CHECK-LABEL: sil_vtable OpaqueTuple { // CHECK-NEXT: #Opaque.inAndOut!1: <T> (Opaque<T>) -> (T) -> T : hidden _T027vtable_thunks_reabstraction11OpaqueTupleC8inAndOutx_xtx_xt1x_tFAA0D0CADxxAE_tFTV // vtable thunk for Opaque.inAndOut(x:) dispatching to OpaqueTuple.inAndOut(x:) // CHECK-NEXT: #Opaque.inAndOutGeneric!1: <T><U> (Opaque<T>) -> (T, U) -> U : _T027vtable_thunks_reabstraction6OpaqueC15inAndOutGenericqd__x1x_qd__1ytlF // Opaque.inAndOutGeneric<A>(x:y:) // CHECK-NEXT: #Opaque.inAndOutMetatypes!1: <T> (Opaque<T>) -> (T.Type) -> T.Type : _T027vtable_thunks_reabstraction6OpaqueC17inAndOutMetatypesxmxm1x_tF // Opaque.inAndOutMetatypes(x:) // CHECK-NEXT: #Opaque.inAndOutFunctions!1: <T> (Opaque<T>) -> (@escaping (T) -> T) -> (T) -> T : _T027vtable_thunks_reabstraction6OpaqueC17inAndOutFunctionsxxcxxc1x_tF // Opaque.inAndOutFunctions(x:) // CHECK-NEXT: #Opaque.inAndOutTuples!1: <T> (Opaque<T>) -> ((T, (T.Type, (T) -> T))) -> (T, (T.Type, (T) -> T)) : _T027vtable_thunks_reabstraction6OpaqueC14inAndOutTuplesx_xm_xxcttx_xm_xxctt1x_tF // Opaque.inAndOutTuples(x:) // CHECK-NEXT: #Opaque.variantOptionality!1: <T> (Opaque<T>) -> (T) -> T? : hidden _T027vtable_thunks_reabstraction11OpaqueTupleC18variantOptionalityx_xtx_xtSg1x_tFAA0D0CADxSgxAF_tFTV // vtable thunk for Opaque.variantOptionality(x:) dispatching to OpaqueTuple.variantOptionality(x:) // CHECK-NEXT: #Opaque.variantOptionalityMetatypes!1: <T> (Opaque<T>) -> (T.Type) -> T.Type? : _T027vtable_thunks_reabstraction6OpaqueC27variantOptionalityMetatypesxmSgxm1x_tF // Opaque.variantOptionalityMetatypes(x:) // CHECK-NEXT: #Opaque.variantOptionalityFunctions!1: <T> (Opaque<T>) -> (@escaping (T) -> T) -> ((T) -> T)? : _T027vtable_thunks_reabstraction6OpaqueC27variantOptionalityFunctionsxxcSgxxc1x_tF // Opaque.variantOptionalityFunctions(x:) // CHECK-NEXT: #Opaque.variantOptionalityTuples!1: <T> (Opaque<T>) -> ((T, (T.Type, (T) -> T))) -> (T, (T.Type, (T) -> T))? : _T027vtable_thunks_reabstraction6OpaqueC24variantOptionalityTuplesx_xm_xxcttSgx_xm_xxctt1x_tF // Opaque.variantOptionalityTuples(x:) // CHECK-NEXT: #Opaque.init!initializer.1: <T> (Opaque<T>.Type) -> () -> Opaque<T> : _T027vtable_thunks_reabstraction11OpaqueTupleCACyxGycfc // OpaqueTuple.init() // Optionality change of tuple. // CHECK-NEXT: #OpaqueTuple.variantOptionality!1: <U> (OpaqueTuple<U>) -> ((U, U)?) -> (U, U) : _T027vtable_thunks_reabstraction11OpaqueTupleC18variantOptionalityx_xtx_xtSg1x_tF // OpaqueTuple.variantOptionality(x:) // CHECK-NEXT: #OpaqueTuple.deinit!deallocator: _T027vtable_thunks_reabstraction11OpaqueTupleCfD // OpaqueTuple.__deallocating_deinit // CHECK-NEXT: } class ConcreteTuple: Opaque<(S, S)> { override func inAndOut(x: (S, S)) -> (S, S) { return x } override func variantOptionality(x: (S, S)?) -> (S, S) { return x! } } // CHECK-LABEL: sil_vtable ConcreteTuple { // CHECK-NEXT: #Opaque.inAndOut!1: <T> (Opaque<T>) -> (T) -> T : hidden _T027vtable_thunks_reabstraction13ConcreteTupleC8inAndOutAA1SV_AFtAF_AFt1x_tFAA6OpaqueCADxxAG_tFTV // vtable thunk for Opaque.inAndOut(x:) dispatching to ConcreteTuple.inAndOut(x:) // CHECK-NEXT: #Opaque.inAndOutGeneric!1: <T><U> (Opaque<T>) -> (T, U) -> U : _T027vtable_thunks_reabstraction6OpaqueC15inAndOutGenericqd__x1x_qd__1ytlF // Opaque.inAndOutGeneric<A>(x:y:) // CHECK-NEXT: #Opaque.inAndOutMetatypes!1: <T> (Opaque<T>) -> (T.Type) -> T.Type : _T027vtable_thunks_reabstraction6OpaqueC17inAndOutMetatypesxmxm1x_tF // Opaque.inAndOutMetatypes(x:) // CHECK-NEXT: #Opaque.inAndOutFunctions!1: <T> (Opaque<T>) -> (@escaping (T) -> T) -> (T) -> T : _T027vtable_thunks_reabstraction6OpaqueC17inAndOutFunctionsxxcxxc1x_tF // Opaque.inAndOutFunctions(x:) // CHECK-NEXT: #Opaque.inAndOutTuples!1: <T> (Opaque<T>) -> ((T, (T.Type, (T) -> T))) -> (T, (T.Type, (T) -> T)) : _T027vtable_thunks_reabstraction6OpaqueC14inAndOutTuplesx_xm_xxcttx_xm_xxctt1x_tF // Opaque.inAndOutTuples(x:) // CHECK-NEXT: #Opaque.variantOptionality!1: <T> (Opaque<T>) -> (T) -> T? : hidden _T027vtable_thunks_reabstraction13ConcreteTupleC18variantOptionalityAA1SV_AFtAF_AFtSg1x_tFAA6OpaqueCADxSgxAH_tFTV // vtable thunk for Opaque.variantOptionality(x:) dispatching to ConcreteTuple.variantOptionality(x:) // CHECK-NEXT: #Opaque.variantOptionalityMetatypes!1: <T> (Opaque<T>) -> (T.Type) -> T.Type? : _T027vtable_thunks_reabstraction6OpaqueC27variantOptionalityMetatypesxmSgxm1x_tF // Opaque.variantOptionalityMetatypes(x:) // CHECK-NEXT: #Opaque.variantOptionalityFunctions!1: <T> (Opaque<T>) -> (@escaping (T) -> T) -> ((T) -> T)? : _T027vtable_thunks_reabstraction6OpaqueC27variantOptionalityFunctionsxxcSgxxc1x_tF // Opaque.variantOptionalityFunctions(x:) // CHECK-NEXT: #Opaque.variantOptionalityTuples!1: <T> (Opaque<T>) -> ((T, (T.Type, (T) -> T))) -> (T, (T.Type, (T) -> T))? : _T027vtable_thunks_reabstraction6OpaqueC24variantOptionalityTuplesx_xm_xxcttSgx_xm_xxctt1x_tF // Opaque.variantOptionalityTuples(x:) // CHECK-NEXT: #Opaque.init!initializer.1: <T> (Opaque<T>.Type) -> () -> Opaque<T> : _T027vtable_thunks_reabstraction13ConcreteTupleCACycfc // ConcreteTuple.init() // Optionality change of tuple. // CHECK-NEXT: #ConcreteTuple.variantOptionality!1: (ConcreteTuple) -> ((S, S)?) -> (S, S) : _T027vtable_thunks_reabstraction13ConcreteTupleC18variantOptionalityAA1SV_AFtAF_AFtSg1x_tF // ConcreteTuple.variantOptionality(x:) // CHECK-NEXT: #ConcreteTuple.deinit!deallocator: _T027vtable_thunks_reabstraction13ConcreteTupleCfD // ConcreteTuple.__deallocating_deinit // CHECK-NEXT: } class OpaqueFunction<U, V>: Opaque<(U) -> V> { override func inAndOut(x: @escaping (U) -> V) -> (U) -> V { return x } override func variantOptionality(x: ((U) -> V)?) -> (U) -> V { return x! } } // CHECK-LABEL: sil_vtable OpaqueFunction { // CHECK-NEXT: #Opaque.inAndOut!1: <T> (Opaque<T>) -> (T) -> T : hidden _T027vtable_thunks_reabstraction14OpaqueFunctionC8inAndOutq_xcq_xc1x_tFAA0D0CADxxAE_tFTV // vtable thunk for Opaque.inAndOut(x:) dispatching to OpaqueFunction.inAndOut(x:) // CHECK-NEXT: #Opaque.inAndOutGeneric!1: <T><U> (Opaque<T>) -> (T, U) -> U : _T027vtable_thunks_reabstraction6OpaqueC15inAndOutGenericqd__x1x_qd__1ytlF // Opaque.inAndOutGeneric<A>(x:y:) // CHECK-NEXT: #Opaque.inAndOutMetatypes!1: <T> (Opaque<T>) -> (T.Type) -> T.Type : _T027vtable_thunks_reabstraction6OpaqueC17inAndOutMetatypesxmxm1x_tF // Opaque.inAndOutMetatypes(x:) // CHECK-NEXT: #Opaque.inAndOutFunctions!1: <T> (Opaque<T>) -> (@escaping (T) -> T) -> (T) -> T : _T027vtable_thunks_reabstraction6OpaqueC17inAndOutFunctionsxxcxxc1x_tF // Opaque.inAndOutFunctions(x:) // CHECK-NEXT: #Opaque.inAndOutTuples!1: <T> (Opaque<T>) -> ((T, (T.Type, (T) -> T))) -> (T, (T.Type, (T) -> T)) : _T027vtable_thunks_reabstraction6OpaqueC14inAndOutTuplesx_xm_xxcttx_xm_xxctt1x_tF // Opaque.inAndOutTuples(x:) // CHECK-NEXT: #Opaque.variantOptionality!1: <T> (Opaque<T>) -> (T) -> T? : hidden _T027vtable_thunks_reabstraction14OpaqueFunctionC18variantOptionalityq_xcq_xcSg1x_tFAA0D0CADxSgxAF_tFTV // vtable thunk for Opaque.variantOptionality(x:) dispatching to OpaqueFunction.variantOptionality(x:) // CHECK-NEXT: #Opaque.variantOptionalityMetatypes!1: <T> (Opaque<T>) -> (T.Type) -> T.Type? : _T027vtable_thunks_reabstraction6OpaqueC27variantOptionalityMetatypesxmSgxm1x_tF // Opaque.variantOptionalityMetatypes(x:) // CHECK-NEXT: #Opaque.variantOptionalityFunctions!1: <T> (Opaque<T>) -> (@escaping (T) -> T) -> ((T) -> T)? : _T027vtable_thunks_reabstraction6OpaqueC27variantOptionalityFunctionsxxcSgxxc1x_tF // Opaque.variantOptionalityFunctions(x:) // CHECK-NEXT: #Opaque.variantOptionalityTuples!1: <T> (Opaque<T>) -> ((T, (T.Type, (T) -> T))) -> (T, (T.Type, (T) -> T))? : _T027vtable_thunks_reabstraction6OpaqueC24variantOptionalityTuplesx_xm_xxcttSgx_xm_xxctt1x_tF // Opaque.variantOptionalityTuples(x:) // CHECK-NEXT: #Opaque.init!initializer.1: <T> (Opaque<T>.Type) -> () -> Opaque<T> : _T027vtable_thunks_reabstraction14OpaqueFunctionCACyxq_Gycfc // OpaqueFunction.init() // Optionality change of function. // CHECK-NEXT: #OpaqueFunction.variantOptionality!1: <U, V> (OpaqueFunction<U, V>) -> (((U) -> V)?) -> (U) -> V : _T027vtable_thunks_reabstraction14OpaqueFunctionC18variantOptionalityq_xcq_xcSg1x_tF // OpaqueFunction.variantOptionality(x:) // CHECK-NEXT: #OpaqueFunction.deinit!deallocator: _T027vtable_thunks_reabstraction14OpaqueFunctionCfD // OpaqueFunction.__deallocating_deinit // CHECK-NEXT: } class ConcreteFunction: Opaque<(S) -> S> { override func inAndOut(x: @escaping (S) -> S) -> (S) -> S { return x } override func variantOptionality(x: ((S) -> S)?) -> (S) -> S { return x! } } // CHECK-LABEL: sil_vtable ConcreteFunction { // CHECK-NEXT: #Opaque.inAndOut!1: <T> (Opaque<T>) -> (T) -> T : hidden _T027vtable_thunks_reabstraction16ConcreteFunctionC8inAndOutAA1SVAFcA2Fc1x_tFAA6OpaqueCADxxAG_tFTV // vtable thunk for Opaque.inAndOut(x:) dispatching to ConcreteFunction.inAndOut(x:) // CHECK-NEXT: #Opaque.inAndOutGeneric!1: <T><U> (Opaque<T>) -> (T, U) -> U : _T027vtable_thunks_reabstraction6OpaqueC15inAndOutGenericqd__x1x_qd__1ytlF // Opaque.inAndOutGeneric<A>(x:y:) // CHECK-NEXT: #Opaque.inAndOutMetatypes!1: <T> (Opaque<T>) -> (T.Type) -> T.Type : _T027vtable_thunks_reabstraction6OpaqueC17inAndOutMetatypesxmxm1x_tF // Opaque.inAndOutMetatypes(x:) // CHECK-NEXT: #Opaque.inAndOutFunctions!1: <T> (Opaque<T>) -> (@escaping (T) -> T) -> (T) -> T : _T027vtable_thunks_reabstraction6OpaqueC17inAndOutFunctionsxxcxxc1x_tF // Opaque.inAndOutFunctions(x:) // CHECK-NEXT: #Opaque.inAndOutTuples!1: <T> (Opaque<T>) -> ((T, (T.Type, (T) -> T))) -> (T, (T.Type, (T) -> T)) : _T027vtable_thunks_reabstraction6OpaqueC14inAndOutTuplesx_xm_xxcttx_xm_xxctt1x_tF // Opaque.inAndOutTuples(x:) // CHECK-NEXT: #Opaque.variantOptionality!1: <T> (Opaque<T>) -> (T) -> T? : hidden _T027vtable_thunks_reabstraction16ConcreteFunctionC18variantOptionalityAA1SVAFcA2FcSg1x_tFAA6OpaqueCADxSgxAH_tFTV // vtable thunk for Opaque.variantOptionality(x:) dispatching to ConcreteFunction.variantOptionality(x:) // CHECK-NEXT: #Opaque.variantOptionalityMetatypes!1: <T> (Opaque<T>) -> (T.Type) -> T.Type? : _T027vtable_thunks_reabstraction6OpaqueC27variantOptionalityMetatypesxmSgxm1x_tF // Opaque.variantOptionalityMetatypes(x:) // CHECK-NEXT: #Opaque.variantOptionalityFunctions!1: <T> (Opaque<T>) -> (@escaping (T) -> T) -> ((T) -> T)? : _T027vtable_thunks_reabstraction6OpaqueC27variantOptionalityFunctionsxxcSgxxc1x_tF // Opaque.variantOptionalityFunctions(x:) // CHECK-NEXT: #Opaque.variantOptionalityTuples!1: <T> (Opaque<T>) -> ((T, (T.Type, (T) -> T))) -> (T, (T.Type, (T) -> T))? : _T027vtable_thunks_reabstraction6OpaqueC24variantOptionalityTuplesx_xm_xxcttSgx_xm_xxctt1x_tF // Opaque.variantOptionalityTuples(x:) // CHECK-NEXT: #Opaque.init!initializer.1: <T> (Opaque<T>.Type) -> () -> Opaque<T> : _T027vtable_thunks_reabstraction16ConcreteFunctionCACycfc // ConcreteFunction.init() // Optionality change of function. // CHECK-NEXT: #ConcreteFunction.variantOptionality!1: (ConcreteFunction) -> (((S) -> S)?) -> (S) -> S : _T027vtable_thunks_reabstraction16ConcreteFunctionC18variantOptionalityAA1SVAFcA2FcSg1x_tF // ConcreteFunction.variantOptionality(x:) // CHECK-NEXT: #ConcreteFunction.deinit!deallocator: _T027vtable_thunks_reabstraction16ConcreteFunctionCfD // ConcreteFunction.__deallocating_deinit // CHECK-NEXT: } class OpaqueMetatype<U>: Opaque<U.Type> { override func inAndOut(x: U.Type) -> U.Type { return x } override func variantOptionality(x: U.Type?) -> U.Type { return x! } } // CHECK-LABEL: sil_vtable OpaqueMetatype { // CHECK-NEXT: #Opaque.inAndOut!1: <T> (Opaque<T>) -> (T) -> T : hidden _T027vtable_thunks_reabstraction14OpaqueMetatypeC8inAndOutxmxm1x_tFAA0D0CADxxAE_tFTV // vtable thunk for Opaque.inAndOut(x:) dispatching to OpaqueMetatype.inAndOut(x:) // CHECK-NEXT: #Opaque.inAndOutGeneric!1: <T><U> (Opaque<T>) -> (T, U) -> U : _T027vtable_thunks_reabstraction6OpaqueC15inAndOutGenericqd__x1x_qd__1ytlF // Opaque.inAndOutGeneric<A>(x:y:) // CHECK-NEXT: #Opaque.inAndOutMetatypes!1: <T> (Opaque<T>) -> (T.Type) -> T.Type : _T027vtable_thunks_reabstraction6OpaqueC17inAndOutMetatypesxmxm1x_tF // Opaque.inAndOutMetatypes(x:) // CHECK-NEXT: #Opaque.inAndOutFunctions!1: <T> (Opaque<T>) -> (@escaping (T) -> T) -> (T) -> T : _T027vtable_thunks_reabstraction6OpaqueC17inAndOutFunctionsxxcxxc1x_tF // Opaque.inAndOutFunctions(x:) // CHECK-NEXT: #Opaque.inAndOutTuples!1: <T> (Opaque<T>) -> ((T, (T.Type, (T) -> T))) -> (T, (T.Type, (T) -> T)) : _T027vtable_thunks_reabstraction6OpaqueC14inAndOutTuplesx_xm_xxcttx_xm_xxctt1x_tF // Opaque.inAndOutTuples(x:) // CHECK-NEXT: #Opaque.variantOptionality!1: <T> (Opaque<T>) -> (T) -> T? : hidden _T027vtable_thunks_reabstraction14OpaqueMetatypeC18variantOptionalityxmxmSg1x_tFAA0D0CADxSgxAF_tFTV // vtable thunk for Opaque.variantOptionality(x:) dispatching to OpaqueMetatype.variantOptionality(x:) // CHECK-NEXT: #Opaque.variantOptionalityMetatypes!1: <T> (Opaque<T>) -> (T.Type) -> T.Type? : _T027vtable_thunks_reabstraction6OpaqueC27variantOptionalityMetatypesxmSgxm1x_tF // Opaque.variantOptionalityMetatypes(x:) // CHECK-NEXT: #Opaque.variantOptionalityFunctions!1: <T> (Opaque<T>) -> (@escaping (T) -> T) -> ((T) -> T)? : _T027vtable_thunks_reabstraction6OpaqueC27variantOptionalityFunctionsxxcSgxxc1x_tF // Opaque.variantOptionalityFunctions(x:) // CHECK-NEXT: #Opaque.variantOptionalityTuples!1: <T> (Opaque<T>) -> ((T, (T.Type, (T) -> T))) -> (T, (T.Type, (T) -> T))? : _T027vtable_thunks_reabstraction6OpaqueC24variantOptionalityTuplesx_xm_xxcttSgx_xm_xxctt1x_tF // Opaque.variantOptionalityTuples(x:) // CHECK-NEXT: #Opaque.init!initializer.1: <T> (Opaque<T>.Type) -> () -> Opaque<T> : _T027vtable_thunks_reabstraction14OpaqueMetatypeCACyxGycfc // OpaqueMetatype.init() // Optionality change of metatype. // CHECK-NEXT: #OpaqueMetatype.variantOptionality!1: <U> (OpaqueMetatype<U>) -> (U.Type?) -> U.Type : _T027vtable_thunks_reabstraction14OpaqueMetatypeC18variantOptionalityxmxmSg1x_tF // OpaqueMetatype.variantOptionality(x:) // CHECK-NEXT: #OpaqueMetatype.deinit!deallocator: _T027vtable_thunks_reabstraction14OpaqueMetatypeCfD // OpaqueMetatype.__deallocating_deinit // CHECK-NEXT: } class ConcreteValueMetatype: Opaque<S.Type> { override func inAndOut(x: S.Type) -> S.Type { return x } override func variantOptionality(x: S.Type?) -> S.Type { return x! } } // CHECK-LABEL: sil_vtable ConcreteValueMetatype { // CHECK-NEXT: #Opaque.inAndOut!1: <T> (Opaque<T>) -> (T) -> T : hidden _T027vtable_thunks_reabstraction21ConcreteValueMetatypeC8inAndOutAA1SVmAFm1x_tFAA6OpaqueCADxxAG_tFTV // vtable thunk for Opaque.inAndOut(x:) dispatching to ConcreteValueMetatype.inAndOut(x:) // CHECK-NEXT: #Opaque.inAndOutGeneric!1: <T><U> (Opaque<T>) -> (T, U) -> U : _T027vtable_thunks_reabstraction6OpaqueC15inAndOutGenericqd__x1x_qd__1ytlF // Opaque.inAndOutGeneric<A>(x:y:) // CHECK-NEXT: #Opaque.inAndOutMetatypes!1: <T> (Opaque<T>) -> (T.Type) -> T.Type : _T027vtable_thunks_reabstraction6OpaqueC17inAndOutMetatypesxmxm1x_tF // Opaque.inAndOutMetatypes(x:) // CHECK-NEXT: #Opaque.inAndOutFunctions!1: <T> (Opaque<T>) -> (@escaping (T) -> T) -> (T) -> T : _T027vtable_thunks_reabstraction6OpaqueC17inAndOutFunctionsxxcxxc1x_tF // Opaque.inAndOutFunctions(x:) // CHECK-NEXT: #Opaque.inAndOutTuples!1: <T> (Opaque<T>) -> ((T, (T.Type, (T) -> T))) -> (T, (T.Type, (T) -> T)) : _T027vtable_thunks_reabstraction6OpaqueC14inAndOutTuplesx_xm_xxcttx_xm_xxctt1x_tF // Opaque.inAndOutTuples(x:) // CHECK-NEXT: #Opaque.variantOptionality!1: <T> (Opaque<T>) -> (T) -> T? : hidden _T027vtable_thunks_reabstraction21ConcreteValueMetatypeC18variantOptionalityAA1SVmAFmSg1x_tFAA6OpaqueCADxSgxAH_tFTV // vtable thunk for Opaque.variantOptionality(x:) dispatching to ConcreteValueMetatype.variantOptionality(x:) // CHECK-NEXT: #Opaque.variantOptionalityMetatypes!1: <T> (Opaque<T>) -> (T.Type) -> T.Type? : _T027vtable_thunks_reabstraction6OpaqueC27variantOptionalityMetatypesxmSgxm1x_tF // Opaque.variantOptionalityMetatypes(x:) // CHECK-NEXT: #Opaque.variantOptionalityFunctions!1: <T> (Opaque<T>) -> (@escaping (T) -> T) -> ((T) -> T)? : _T027vtable_thunks_reabstraction6OpaqueC27variantOptionalityFunctionsxxcSgxxc1x_tF // Opaque.variantOptionalityFunctions(x:) // CHECK-NEXT: #Opaque.variantOptionalityTuples!1: <T> (Opaque<T>) -> ((T, (T.Type, (T) -> T))) -> (T, (T.Type, (T) -> T))? : _T027vtable_thunks_reabstraction6OpaqueC24variantOptionalityTuplesx_xm_xxcttSgx_xm_xxctt1x_tF // Opaque.variantOptionalityTuples(x:) // CHECK-NEXT: #Opaque.init!initializer.1: <T> (Opaque<T>.Type) -> () -> Opaque<T> : _T027vtable_thunks_reabstraction21ConcreteValueMetatypeCACycfc // ConcreteValueMetatype.init() // Optionality change of metatype. // CHECK-NEXT: #ConcreteValueMetatype.variantOptionality!1: (ConcreteValueMetatype) -> (S.Type?) -> S.Type : _T027vtable_thunks_reabstraction21ConcreteValueMetatypeC18variantOptionalityAA1SVmAFmSg1x_tF // ConcreteValueMetatype.variantOptionality(x:) // CHECK-NEXT: #ConcreteValueMetatype.deinit!deallocator: _T027vtable_thunks_reabstraction21ConcreteValueMetatypeCfD // ConcreteValueMetatype.__deallocating_deinit // CHECK-NEXT: } class ConcreteClassMetatype: Opaque<C.Type> { override func inAndOut(x: C.Type) -> C.Type { return x } override func variantOptionality(x: C.Type?) -> C.Type { return x! } } // CHECK-LABEL: sil_vtable ConcreteClassMetatype { // CHECK-NEXT: #Opaque.inAndOut!1: <T> (Opaque<T>) -> (T) -> T : hidden _T027vtable_thunks_reabstraction21ConcreteClassMetatypeC8inAndOutAA1CCmAFm1x_tFAA6OpaqueCADxxAG_tFTV // vtable thunk for Opaque.inAndOut(x:) dispatching to ConcreteClassMetatype.inAndOut(x:) // CHECK-NEXT: #Opaque.inAndOutGeneric!1: <T><U> (Opaque<T>) -> (T, U) -> U : _T027vtable_thunks_reabstraction6OpaqueC15inAndOutGenericqd__x1x_qd__1ytlF // Opaque.inAndOutGeneric<A>(x:y:) // CHECK-NEXT: #Opaque.inAndOutMetatypes!1: <T> (Opaque<T>) -> (T.Type) -> T.Type : _T027vtable_thunks_reabstraction6OpaqueC17inAndOutMetatypesxmxm1x_tF // Opaque.inAndOutMetatypes(x:) // CHECK-NEXT: #Opaque.inAndOutFunctions!1: <T> (Opaque<T>) -> (@escaping (T) -> T) -> (T) -> T : _T027vtable_thunks_reabstraction6OpaqueC17inAndOutFunctionsxxcxxc1x_tF // Opaque.inAndOutFunctions(x:) // CHECK-NEXT: #Opaque.inAndOutTuples!1: <T> (Opaque<T>) -> ((T, (T.Type, (T) -> T))) -> (T, (T.Type, (T) -> T)) : _T027vtable_thunks_reabstraction6OpaqueC14inAndOutTuplesx_xm_xxcttx_xm_xxctt1x_tF // Opaque.inAndOutTuples(x:) // CHECK-NEXT: #Opaque.variantOptionality!1: <T> (Opaque<T>) -> (T) -> T? : hidden _T027vtable_thunks_reabstraction21ConcreteClassMetatypeC18variantOptionalityAA1CCmAFmSg1x_tFAA6OpaqueCADxSgxAH_tFTV // vtable thunk for Opaque.variantOptionality(x:) dispatching to ConcreteClassMetatype.variantOptionality(x:) // CHECK-NEXT: #Opaque.variantOptionalityMetatypes!1: <T> (Opaque<T>) -> (T.Type) -> T.Type? : _T027vtable_thunks_reabstraction6OpaqueC27variantOptionalityMetatypesxmSgxm1x_tF // Opaque.variantOptionalityMetatypes(x:) // CHECK-NEXT: #Opaque.variantOptionalityFunctions!1: <T> (Opaque<T>) -> (@escaping (T) -> T) -> ((T) -> T)? : _T027vtable_thunks_reabstraction6OpaqueC27variantOptionalityFunctionsxxcSgxxc1x_tF // Opaque.variantOptionalityFunctions(x:) // CHECK-NEXT: #Opaque.variantOptionalityTuples!1: <T> (Opaque<T>) -> ((T, (T.Type, (T) -> T))) -> (T, (T.Type, (T) -> T))? : _T027vtable_thunks_reabstraction6OpaqueC24variantOptionalityTuplesx_xm_xxcttSgx_xm_xxctt1x_tF // Opaque.variantOptionalityTuples(x:) // CHECK-NEXT: #Opaque.init!initializer.1: <T> (Opaque<T>.Type) -> () -> Opaque<T> : _T027vtable_thunks_reabstraction21ConcreteClassMetatypeCACycfc // ConcreteClassMetatype.init() // Class metatypes are ABI compatible with optional class metatypes. // CHECK-NEXT: #ConcreteClassMetatype.deinit!deallocator: _T027vtable_thunks_reabstraction21ConcreteClassMetatypeCfD // ConcreteClassMetatype.__deallocating_deinit // CHECK-NEXT: } class ConcreteOptional: Opaque<S?> { override func inAndOut(x: S?) -> S? { return x } // FIXME: Should we allow this override in Sema? // override func variantOptionality(x: S??) -> S? { return x! } } // CHECK-LABEL: sil_vtable ConcreteOptional { // CHECK-NEXT: #Opaque.inAndOut!1: <T> (Opaque<T>) -> (T) -> T : hidden _T027vtable_thunks_reabstraction16ConcreteOptionalC8inAndOutAA1SVSgAG1x_tFAA6OpaqueCADxxAH_tFTV // vtable thunk for Opaque.inAndOut(x:) dispatching to ConcreteOptional.inAndOut(x:) // CHECK-NEXT: #Opaque.inAndOutGeneric!1: <T><U> (Opaque<T>) -> (T, U) -> U : _T027vtable_thunks_reabstraction6OpaqueC15inAndOutGenericqd__x1x_qd__1ytlF // Opaque.inAndOutGeneric<A>(x:y:) // CHECK-NEXT: #Opaque.inAndOutMetatypes!1: <T> (Opaque<T>) -> (T.Type) -> T.Type : _T027vtable_thunks_reabstraction6OpaqueC17inAndOutMetatypesxmxm1x_tF // Opaque.inAndOutMetatypes(x:) // CHECK-NEXT: #Opaque.inAndOutFunctions!1: <T> (Opaque<T>) -> (@escaping (T) -> T) -> (T) -> T : _T027vtable_thunks_reabstraction6OpaqueC17inAndOutFunctionsxxcxxc1x_tF // Opaque.inAndOutFunctions(x:) // CHECK-NEXT: #Opaque.inAndOutTuples!1: <T> (Opaque<T>) -> ((T, (T.Type, (T) -> T))) -> (T, (T.Type, (T) -> T)) : _T027vtable_thunks_reabstraction6OpaqueC14inAndOutTuplesx_xm_xxcttx_xm_xxctt1x_tF // Opaque.inAndOutTuples(x:) // CHECK-NEXT: #Opaque.variantOptionality!1: <T> (Opaque<T>) -> (T) -> T? : _T027vtable_thunks_reabstraction6OpaqueC18variantOptionalityxSgx1x_tF // Opaque.variantOptionality(x:) // CHECK-NEXT: #Opaque.variantOptionalityMetatypes!1: <T> (Opaque<T>) -> (T.Type) -> T.Type? : _T027vtable_thunks_reabstraction6OpaqueC27variantOptionalityMetatypesxmSgxm1x_tF // Opaque.variantOptionalityMetatypes(x:) // CHECK-NEXT: #Opaque.variantOptionalityFunctions!1: <T> (Opaque<T>) -> (@escaping (T) -> T) -> ((T) -> T)? : _T027vtable_thunks_reabstraction6OpaqueC27variantOptionalityFunctionsxxcSgxxc1x_tF // Opaque.variantOptionalityFunctions(x:) // CHECK-NEXT: #Opaque.variantOptionalityTuples!1: <T> (Opaque<T>) -> ((T, (T.Type, (T) -> T))) -> (T, (T.Type, (T) -> T))? : _T027vtable_thunks_reabstraction6OpaqueC24variantOptionalityTuplesx_xm_xxcttSgx_xm_xxctt1x_tF // Opaque.variantOptionalityTuples(x:) // CHECK-NEXT: #Opaque.init!initializer.1: <T> (Opaque<T>.Type) -> () -> Opaque<T> : _T027vtable_thunks_reabstraction16ConcreteOptionalCACycfc // ConcreteOptional.init() // CHECK-NEXT: #ConcreteOptional.deinit!deallocator: _T027vtable_thunks_reabstraction16ConcreteOptionalCfD // ConcreteOptional.__deallocating_deinit // CHECK-NEXT: } // Make sure we remap the method's innermost generic parameters // to the correct depth class GenericBase<T> { func doStuff<U>(t: T, u: U) {} init<U>(t: T, u: U) {} } // CHECK-LABEL: sil_vtable GenericBase { // CHECK-NEXT: #GenericBase.doStuff!1: <T><U> (GenericBase<T>) -> (T, U) -> () : _T027vtable_thunks_reabstraction11GenericBaseC7doStuffyx1t_qd__1utlF // GenericBase.doStuff<A>(t:u:) // CHECK-NEXT: #GenericBase.init!initializer.1: <T><U> (GenericBase<T>.Type) -> (T, U) -> GenericBase<T> : _T027vtable_thunks_reabstraction11GenericBaseCACyxGx1t_qd__1utclufc // GenericBase.init<A>(t:u:) // CHECK-NEXT: #GenericBase.deinit!deallocator: _T027vtable_thunks_reabstraction11GenericBaseCfD // GenericBase.__deallocating_deinit // CHECK-NEXT: } class ConcreteSub : GenericBase<Int> { override func doStuff<U>(t: Int, u: U) { super.doStuff(t: t, u: u) } override init<U>(t: Int, u: U) { super.init(t: t, u: u) } } // CHECK-LABEL: sil_vtable ConcreteSub { // CHECK-NEXT: #GenericBase.doStuff!1: <T><U> (GenericBase<T>) -> (T, U) -> () : hidden _T027vtable_thunks_reabstraction11ConcreteSubC7doStuffySi1t_x1utlFAA11GenericBaseCADyxAE_qd__AFtlFTV // vtable thunk for GenericBase.doStuff<A>(t:u:) dispatching to ConcreteSub.doStuff<A>(t:u:) // CHECK-NEXT: #GenericBase.init!initializer.1: <T><U> (GenericBase<T>.Type) -> (T, U) -> GenericBase<T> : hidden _T027vtable_thunks_reabstraction11ConcreteSubCACSi1t_x1utclufcAA11GenericBaseCAGyxGxAD_qd__AEtclufcTV // vtable thunk for GenericBase.init<A>(t:u:) dispatching to ConcreteSub.init<A>(t:u:) // CHECK-NEXT: #ConcreteSub.deinit!deallocator: _T027vtable_thunks_reabstraction11ConcreteSubCfD // ConcreteSub.__deallocating_deinit // CHECK-NEXT: } class ConcreteBase { init<U>(t: Int, u: U) {} func doStuff<U>(t: Int, u: U) {} } // CHECK-LABEL: sil_vtable ConcreteBase { // CHECK-NEXT: #ConcreteBase.init!initializer.1: <U> (ConcreteBase.Type) -> (Int, U) -> ConcreteBase : _T027vtable_thunks_reabstraction12ConcreteBaseCACSi1t_x1utclufc // ConcreteBase.init<A>(t:u:) // CHECK-NEXT: #ConcreteBase.doStuff!1: <U> (ConcreteBase) -> (Int, U) -> () : _T027vtable_thunks_reabstraction12ConcreteBaseC7doStuffySi1t_x1utlF // ConcreteBase.doStuff<A>(t:u:) // CHECK-NEXT: #ConcreteBase.deinit!deallocator: _T027vtable_thunks_reabstraction12ConcreteBaseCfD // ConcreteBase.__deallocating_deinit // CHECK-NEXT: } class GenericSub<T> : ConcreteBase { override init<U>(t: Int, u: U) { super.init(t: t, u: u) } override func doStuff<U>(t: Int, u: U) { super.doStuff(t: t, u: u) } } // CHECK-LABEL: sil_vtable GenericSub { // CHECK-NEXT: #ConcreteBase.init!initializer.1: <U> (ConcreteBase.Type) -> (Int, U) -> ConcreteBase : _T027vtable_thunks_reabstraction10GenericSubCACyxGSi1t_qd__1utclufc // GenericSub.init<A>(t:u:) // CHECK-NEXT: #ConcreteBase.doStuff!1: <U> (ConcreteBase) -> (Int, U) -> () : _T027vtable_thunks_reabstraction10GenericSubC7doStuffySi1t_qd__1utlF // GenericSub.doStuff<A>(t:u:) // CHECK-NEXT: #GenericSub.deinit!deallocator: _T027vtable_thunks_reabstraction10GenericSubCfD // GenericSub.__deallocating_deinit // CHECK-NEXT: } // Issue with generic parameter index class MoreGenericSub1<T, TT> : GenericBase<T> { override func doStuff<U>(t: T, u: U) { super.doStuff(t: t, u: u) } } // CHECK-LABEL: sil_vtable MoreGenericSub1 { // CHECK-NEXT: #GenericBase.doStuff!1: <T><U> (GenericBase<T>) -> (T, U) -> () : _T027vtable_thunks_reabstraction15MoreGenericSub1C7doStuffyx1t_qd__1utlF // MoreGenericSub1.doStuff<A>(t:u:) // CHECK-NEXT: #GenericBase.init!initializer.1: <T><U> (GenericBase<T>.Type) -> (T, U) -> GenericBase<T> : _T027vtable_thunks_reabstraction11GenericBaseCACyxGx1t_qd__1utclufc // GenericBase.init<A>(t:u:) // CHECK-NEXT: #MoreGenericSub1.deinit!deallocator: _T027vtable_thunks_reabstraction15MoreGenericSub1CfD // MoreGenericSub1.__deallocating_deinit // CHECK-NEXT: } class MoreGenericSub2<TT, T> : GenericBase<T> { override func doStuff<U>(t: T, u: U) { super.doStuff(t: t, u: u) } } // CHECK-LABEL: sil_vtable MoreGenericSub2 { // CHECK-NEXT: #GenericBase.doStuff!1: <T><U> (GenericBase<T>) -> (T, U) -> () : _T027vtable_thunks_reabstraction15MoreGenericSub2C7doStuffyq_1t_qd__1utlF // MoreGenericSub2.doStuff<A>(t:u:) // CHECK-NEXT: #GenericBase.init!initializer.1: <T><U> (GenericBase<T>.Type) -> (T, U) -> GenericBase<T> : _T027vtable_thunks_reabstraction11GenericBaseCACyxGx1t_qd__1utclufc // GenericBase.init<A>(t:u:) // CHECK-NEXT: #MoreGenericSub2.deinit!deallocator: _T027vtable_thunks_reabstraction15MoreGenericSub2CfD // MoreGenericSub2.__deallocating_deinit // CHECK-NEXT: }
apache-2.0
9e9f5b309eb277935f46a6996a35b661
89.994624
400
0.717912
2.868158
false
false
false
false
randallli/material-components-ios
components/NavigationBar/examples/NavigationBarTypicalUseExample.swift
1
2768
/* Copyright 2016-present the Material Components for iOS authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ import UIKit import MaterialComponents.MaterialNavigationBar open class NavigationBarTypicalUseSwiftExample: NavigationBarTypicalUseExample { override open func viewDidLoad() { super.viewDidLoad() view.backgroundColor = .white title = "Navigation Bar (Swift)" navBar = MDCNavigationBar() navBar!.observe(navigationItem) let mutator = MDCNavigationBarTextColorAccessibilityMutator() mutator.mutate(navBar!) MDCNavigationBarColorThemer.applySemanticColorScheme(colorScheme!, to: navBar!) view.addSubview(navBar!) navBar!.translatesAutoresizingMaskIntoConstraints = false #if swift(>=3.2) if #available(iOS 11.0, *) { self.view.safeAreaLayoutGuide.topAnchor.constraint(equalTo: self.navBar!.topAnchor).isActive = true } else { NSLayoutConstraint(item: self.topLayoutGuide, attribute: .bottom, relatedBy: .equal, toItem: self.navBar, attribute: .top, multiplier: 1, constant: 0).isActive = true } #else NSLayoutConstraint(item: self.topLayoutGuide, attribute: .bottom, relatedBy: .equal, toItem: self.navBar, attribute: .top, multiplier: 1, constant: 0).isActive = true #endif let viewBindings = ["navBar": navBar!] NSLayoutConstraint.activate(NSLayoutConstraint.constraints(withVisualFormat: "H:|[navBar]|", options: [], metrics: nil, views: viewBindings)) self.setupExampleViews() } override open func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) self.navigationController?.setNavigationBarHidden(true, animated: animated) } override open var prefersStatusBarHidden: Bool { return true } }
apache-2.0
4830bd0c042ca786c5c9b1fc9f8d28b1
33.6
107
0.613801
5.614604
false
false
false
false
sgrinich/BeatsByKenApp
BeatsByKen/BeatsByKen/Home.swift
1
2993
// // ViewController.swift // BeatsByKen /*Copyright (c) 2015 Aidan Carroll, Alex Calamaro, Max Willard, Liz Shank 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. */ // note: this file is no longer used import UIKit import Foundation import CoreData class Home: UIViewController { let managedObjectContext = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. //let managedObjectContext = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext //println(managedObjectContext) /* let newItem = SessionTable.createInManagedObjectContext(managedObjectContext!, heartbeatCount: 4, trialDuration: 5, trialType: "pre1", participantID: 4, sessionID: 1,tableViewRow: 0) let settingsFields = ["Pre-1", "Pre-2", "Pre-3", "Pre-4", "Post-1", "Post-2", "Post-3", "Post-4", "Exer-1", "Exer-2", "Exer-3", "Exer-4"] for (index,field) in enumerate(settingsFields) { if (!SessionTable.checkInManagedObjectContext(managedObjectContext!, participantID: trialSettingsPID, sessionID: trialSettingsSID, tableViewRow: index)) { let newSettings = SessionTable.createInManagedObjectContext(managedObjectContext!, heartbeatCount: 0, trialDuration: 30, trialType: field, participantID: trialSettingsPID, sessionID: trialSettingsSID, tableViewRow: index) println(newSettings) } } if let x = SessionTable.getCurrentSettings(managedObjectContext!, participantID: trialSettingsPID, sessionID: trialSettingsSID) { println("HOME") println(x) } */ } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
mit
b1a1c32709a8577b2e89fdd2c6369078
41.771429
237
0.716004
4.773525
false
false
false
false
TongCui/t_tools
doc/swift/protocols.swift
1
6445
//: ## Introducing Protocol-Oriented Programming in Swift 3 //: [http://www.raywenderlich.com/109156/introducing-protocol-oriented-programming-in-swift-3](http://www.raywenderlich.com/109156/introducing-protocol-oriented-programming-in-swift-3) import Foundation protocol Bird: CustomStringConvertible { var name: String { get } var canFly: Bool { get } } extension CustomStringConvertible where Self: Bird { var description: String { return canFly ? "I can fly" : "Guess I'll just sit here :[" } } //: Define a topSpeed method that chooses the top speed from a collection of racers //: Make `topSpeed()` an extension to collections of racers to make it more discoverable. //: Make `topSpeed()` an extension to collections of racers to make it more discoverable. //: > Extending `Bird` to have default behavior means that `Bird` types that are also `Flyable` no longer need to implement the `canFly` property themselves. extension Bird { // Flyable birds can fly! var canFly: Bool { return self is Flyable } } protocol Flyable { var airspeedVelocity: Double { get } } //: Define some more `Bird` types. struct FlappyBird: Bird, Flyable { let name: String let flappyAmplitude: Double let flappyFrequency: Double var airspeedVelocity: Double { return 3 * flappyFrequency * flappyAmplitude } } struct Penguin: Bird { let name: String } struct SwiftBird: Bird, Flyable { var name: String { return "Swift \(version)" } let version: Double // Swift is FASTER with each version! var airspeedVelocity: Double { return version * 1000.0 } } //: > One of the benefits of protocol extensions over base classes is that you can define default behavior for any type, not just classes. In this case, the `Bird` and `Flyable` protocols are adopted by an `enum`. enum UnladenSwallow: Bird, Flyable { case african case european case unknown var name: String { switch self { case .african: return "African" case .european: return "European" case .unknown: return "What do you mean? African or European?" } } var airspeedVelocity: Double { switch self { case .african: return 10.0 case .european: return 9.9 case .unknown: fatalError("You are thrown from the bridge of death!") } } } //: Override `canFly` for `UnladenSwallow` Unknown Swallows cannot fly. extension UnladenSwallow { var canFly: Bool { return self != .unknown } } //: > Now, `UnladenSwallow.african` will evaluate to the Bird CustomStringConvertible. //: > Because swallows can fly, this evaluates to 'I can fly'. UnladenSwallow.african //: > Even though UnladenSwallow.unknown conforms to Flyable it returns false for flying UnladenSwallow.unknown.canFly // false UnladenSwallow.african.canFly // true Penguin(name: "King Penguin").canFly // false //: #### Collection Wrappers //: > The type of `reveredSlice` is `ReversedRandomAccessCollection<ArraySlice<Int>>` which is just a view into the original array and requires no additional allocations. This makes slicing and chaining operations very cheap. Because `map` is defined as a protocol extension to `Sequence` and both `Array` and `ReversedRandomAccessCollection` conform to `Sequence` we can just as easily call `map` on the reversed slice as we can on the original array. let numbers = [10,20,30,40,50,60] let slice = numbers[1...3] let reversedSlice = slice.reversed() let answer = reversedSlice.map { $0 * 10 } print(answer) //: #### And now for something completely different. //: Motorcycles have nothing in common with birds. They aren't even value types. class Motorcycle { init(name: String) { self.name = name speed = 200 } var name: String var speed: Double } //: #### Racing //: You will need to handle your racers polymorphically. Define a `Racer` protocol. protocol Racer { var speed: Double { get } // speed is the only thing racers care about } //: Make all of your types conform to Racer. You don't have to modify the original model but can re-open them to add this functionality. This is known as retroactive modelling. extension FlappyBird: Racer { var speed: Double { return airspeedVelocity // Just use airspeedVelocity for speed. } } extension SwiftBird: Racer { var speed: Double { return airspeedVelocity } } extension Penguin: Racer { var speed: Double { return 42 // full waddle speed } } // Nothing to do because you already implemented speed. Just declare conformance. extension Motorcycle: Racer {} // Prevent fatal errors for Swallows that don't fly extension UnladenSwallow: Racer { var speed: Double { return canFly ? airspeedVelocity : 0 } } //: Put all of your Racer conforming types into an Array of the protocol. let racers: [Racer] = [UnladenSwallow.african, UnladenSwallow.european, UnladenSwallow.unknown, Penguin(name: "King Penguin"), SwiftBird(version: 3.0), FlappyBird(name: "Felipe", flappyAmplitude: 3.0, flappyFrequency: 20.0), Motorcycle(name: "Giacomo") ] //: Define a topSpeed method that chooses the top speed from a collection of racers func topSpeed(of racers: [Racer]) -> Double { return racers.max(by: { $0.speed < $1.speed })?.speed ?? 0 } topSpeed(of: racers) // 3000 //: Define a generic version topSpeed to allow any collection wrapper such as a Slice of Racers to compile. func topSpeed<RacerType: Sequence>(of racers: RacerType) -> Double where RacerType.Iterator.Element == Racer { return racers.max(by: { $0.speed < $1.speed })?.speed ?? 0 } topSpeed(of: racers[1...3]) // 42 //: Make `topSpeed()` an extension to collections of racers to make it more discoverable. extension Sequence where Iterator.Element == Racer { func topSpeed() -> Double { return self.max(by: { $0.speed < $1.speed })?.speed ?? 0 } } racers.topSpeed() // works 3000 racers[1...3].topSpeed() // also works 42 //: > Swift 3 allows operators to be implemented as static methods within a type. Previously, they had to be global functions. protocol Score: Equatable, Comparable { var value: Int { get } } struct RacingScore: Score { let value: Int static func ==(lhs: RacingScore, rhs: RacingScore) -> Bool { return lhs.value == rhs.value } static func <(lhs: RacingScore, rhs: RacingScore) -> Bool { return lhs.value < rhs.value } } RacingScore(value: 150) >= RacingScore(value: 130)
mit
4b32a3188b65017e006dddfb42b382c2
27.267544
453
0.707525
3.635082
false
false
false
false
forgot/FAAlertController
Source/Views/FAAlertControllerView.swift
1
10251
// // FAAlertControllerView.swift // FAPlacemarkPicker // // Created by Jesse Cox on 8/20/16. // Copyright © 2016 Apprhythmia LLC. All rights reserved. // import UIKit class FAAlertControllerView: UIView { var title: String? var message: String? var textFields: [UITextField]? var items: [Pickable]? var actions: [FAAlertAction] var preferredAction: FAAlertAction? var cancelAction: FAAlertAction? var interfaceView: FAAlertControllerInterfaceView! var headerView: FAAlertControllerHeaderView? var actionsView: FAAlertControllerActionsView? // MARK: View Lifecycle init(title: String?, message: String?, textFields: [UITextField]?, actions: [FAAlertAction]?, preferredAction: FAAlertAction?, items: [Pickable]? = nil) { self.title = title self.message = message self.textFields = textFields self.items = items self.actions = actions == nil ? [FAAlertAction]() : actions! self.preferredAction = preferredAction super.init(frame: .zero) translatesAutoresizingMaskIntoConstraints = false prepareActions() switch FAAlertControllerAppearanceManager.sharedInstance.preferredStyle { case .alert: configureAlert() case .actionSheet: configureActionSheet() case .picker: configurePicker() } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: Internal Functions func configureAlert() { // Create the alert view interfaceView = FAAlertControllerInterfaceView() // Create and add the header view let headerView = FAAlertControllerHeaderView() headerView.title = title headerView.message = message headerView.textFields = textFields headerView.prepareForLayout() headerView.layoutIfNeeded() interfaceView.stack.addArrangedSubview(headerView) self.headerView = headerView // Create and add the actions view if !actions.isEmpty { // Create and add the separator view let separatorView = FAAlertControllerHorizontalSeparatorView() interfaceView.stack.addArrangedSubview(separatorView) let actionsView = FAAlertControllerActionsView() actionsView.actions = actions actionsView.preferredAction = preferredAction actionsView.cancelAction = cancelAction actionsView.prepareForLayout() actionsView.layoutIfNeeded() interfaceView.stack.addArrangedSubview(actionsView) self.actionsView = actionsView } interfaceView.stack.layoutIfNeeded() addSubview(interfaceView) // Setup constraints interfaceView.centerXAnchor.constraint(equalTo: centerXAnchor).isActive = true interfaceView.centerYAnchor.constraint(equalTo: centerYAnchor).isActive = true widthAnchor.constraint(equalTo: interfaceView.widthAnchor).isActive = true heightAnchor.constraint(equalTo: interfaceView.heightAnchor).isActive = true let constraint = headerView.heightAnchor.constraint(equalTo: interfaceView.heightAnchor, multiplier: 1.5) constraint.priority = 249 addConstraint(constraint) constraint.isActive = true } func configureActionSheet() { // Create the layout view let layoutView = UIStackView(arrangedSubviews: [UIView]()) layoutView.translatesAutoresizingMaskIntoConstraints = false layoutView.axis = .vertical layoutView.spacing = 8 layoutView.heightAnchor.constraint(lessThanOrEqualToConstant: 528).isActive = true // Create the primary interface view interfaceView = FAAlertControllerInterfaceView() // Create and add the header view let headerView = FAAlertControllerHeaderView() headerView.title = title headerView.message = message headerView.prepareForLayout() headerView.layoutIfNeeded() interfaceView.stack.addArrangedSubview(headerView) self.headerView = headerView // Create and add the actions view if !actions.isEmpty { // Create and add the separator view let separatorView = FAAlertControllerHorizontalSeparatorView() interfaceView.stack.addArrangedSubview(separatorView) let actionsView = FAAlertControllerActionsView() actionsView.actions = actions actionsView.prepareForLayout() actionsView.layoutIfNeeded() interfaceView.stack.addArrangedSubview(actionsView) self.actionsView = actionsView } interfaceView.stack.layoutIfNeeded() interfaceView.layoutIfNeeded() // Add the primary interface view layoutView.addArrangedSubview(interfaceView) // If the cancel action is not nil, create and configure a secondary interface view if cancelAction != nil { // Create the secondary interface view let secondaryInterfaceView = FAAlertControllerInterfaceView(withBackdrop: false) // Create and add the actions view let cancelActionView = FAAlertControllerActionsView() cancelActionView.actions = [cancelAction!] cancelActionView.prepareForLayout() cancelActionView.layoutIfNeeded() secondaryInterfaceView.stack.addArrangedSubview(cancelActionView) secondaryInterfaceView.stack.layoutIfNeeded() secondaryInterfaceView.layoutIfNeeded() // Add the secondary interface view layoutView.addArrangedSubview(secondaryInterfaceView) } addSubview(layoutView) layoutView.centerXAnchor.constraint(equalTo: centerXAnchor).isActive = true layoutView.centerYAnchor.constraint(equalTo: centerYAnchor).isActive = true widthAnchor.constraint(equalTo: layoutView.widthAnchor).isActive = true heightAnchor.constraint(equalTo: layoutView.heightAnchor).isActive = true let constraint = headerView.heightAnchor.constraint(equalTo: layoutView.heightAnchor, multiplier: 1.5) constraint.priority = 249 addConstraint(constraint) constraint.isActive = true layoutView.layoutIfNeeded() layoutIfNeeded() } func configurePicker() { // Create the alert view interfaceView = FAAlertControllerInterfaceView() // Create and add the header view let headerView = FAAlertControllerHeaderView() headerView.title = title headerView.message = message headerView.items = items headerView.prepareForLayout() headerView.layoutIfNeeded() interfaceView.stack.addArrangedSubview(headerView) self.headerView = headerView // Create and add the actions view if !actions.isEmpty { // Create and add the separator view let separatorView = FAAlertControllerHorizontalSeparatorView() interfaceView.stack.addArrangedSubview(separatorView) let actionsView = FAAlertControllerActionsView() actionsView.actions = actions actionsView.preferredAction = preferredAction actionsView.cancelAction = cancelAction actionsView.prepareForLayout() actionsView.layoutIfNeeded() interfaceView.stack.addArrangedSubview(actionsView) self.actionsView = actionsView } else { // Add default cancel action actions = [FAAlertAction(title: "Cancel", style: .cancel, handler: nil)] } interfaceView.stack.layoutIfNeeded() addSubview(interfaceView) // Setup constraints interfaceView.centerXAnchor.constraint(equalTo: centerXAnchor).isActive = true interfaceView.centerYAnchor.constraint(equalTo: centerYAnchor).isActive = true widthAnchor.constraint(equalTo: interfaceView.widthAnchor).isActive = true heightAnchor.constraint(equalTo: interfaceView.heightAnchor).isActive = true let constraint = headerView.heightAnchor.constraint(equalTo: interfaceView.heightAnchor, multiplier: 1.5) constraint.priority = 249 addConstraint(constraint) constraint.isActive = true } /// Prepares the array of FAAlertAction items by identifying the preferredAction and cancelAction, if any, and sorting the array accordingly. func prepareActions() { // Loops through the actions checking for any with a `.cancel` style, then moves it to the end of the actions array. Additionally, it sets the identified cancel action, if any, to the preferred action if no other preferred action has been set. for action in actions { if action.style == .cancel { guard let index = actions.index(of: action) else { preconditionFailure("The index of the action is nil, which should never ever happen if it was able to be identified in the first place.") } cancelAction = actions.remove(at: index) if preferredAction == nil { cancelAction?.isPreferredAction = true } } } if FAAlertControllerAppearanceManager.sharedInstance.preferredStyle == .alert || FAAlertControllerAppearanceManager.sharedInstance.preferredStyle == .picker { if let _cancelAction = cancelAction { actions.append(_cancelAction) } } FAAlertControllerAppearanceManager.sharedInstance.numberOfActions = actions.count } }
mit
68132bab1b21ded427a514b12ed5ccdc
37.533835
251
0.643024
6.145084
false
false
false
false
jatinpandey/Tipsy
Tipsy/ViewController.swift
1
3115
// // ViewController.swift // Tipsy // // Created by Jatin Pandey on 9/2/14. // Copyright (c) 2014 Jatin Pandey. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var tipLabel: UILabel! @IBOutlet weak var totalLabel: UILabel! @IBOutlet weak var billField: UITextField! @IBOutlet weak var tipControl: UISegmentedControl! @IBOutlet weak var defaultLabel: UILabel! override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) println("view will appear") var defaults = NSUserDefaults.standardUserDefaults() var defPerc = defaults.objectForKey("defaultTipPercentage") as Double var defPercDisp = Int(defPerc * 100) defaultLabel.text = "\(defPercDisp)%" updateTotal(self) } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) println("view did appear") } override func viewWillDisappear(animated: Bool) { super.viewWillDisappear(animated) println("view will disappear") } override func viewDidDisappear(animated: Bool) { super.viewDidDisappear(animated) println("view did disappear") } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. tipLabel.text = "$0.00" totalLabel.text = "$0.00" } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func calculateTotal(bill: Double, tipPercentage: Double) -> Double { var tip = bill * (tipPercentage) var total = bill + tip return total } @IBAction func updateOnSegmentUpdated(sender: AnyObject) { var tipPercentages = [0.12, 0.15, 0.20] var tipPercentage = tipPercentages[tipControl.selectedSegmentIndex] var billAmount = NSString(string: billField.text).doubleValue var total = calculateTotal(billAmount , tipPercentage: tipPercentage) tipLabel.text = String(format: "$%.2f", tipPercentage*billAmount) totalLabel.text = String(format: "$%.2f", total) } @IBAction func updateTotal(sender: AnyObject) { //var tipPercentages = [0.12, 0.15, 0.20] //var tipPercentage = tipPercentages[tipControl.selectedSegmentIndex] var defaults = NSUserDefaults.standardUserDefaults() var defaultPercentage = defaults.objectForKey("defaultTipPercentage") as Double var billAmount = NSString(string: billField.text).doubleValue var total = calculateTotal(billAmount , tipPercentage: defaultPercentage) tipLabel.text = String(format: "$%.2f", billAmount * defaultPercentage) totalLabel.text = String(format: "$%.2f", total) } @IBAction func onTap(sender: AnyObject) { view.endEditing(true) } }
mit
e8f47180803de8648bebab500d35980c
29.539216
87
0.636597
4.913249
false
false
false
false
denmarkin/photog
Photog/ViewControllers/FeedViewController.swift
1
1476
// // FeedViewController.swift // Photog // // Created by One Month on 9/14/14. // Copyright (c) 2014 One Month. All rights reserved. // import UIKit class FeedViewController: UIViewController, UITableViewDataSource { var items = [] @IBOutlet var tableView: UITableView? override func viewDidLoad() { super.viewDidLoad() var nib = UINib(nibName: "PostCell", bundle: nil) tableView?.registerNib(nib, forCellReuseIdentifier: "PostCellIdentifier") } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) NetworkManager.sharedInstance.fetchFeed { (objects, error) -> () in if let constObjects = objects { self.items = constObjects self.tableView?.reloadData() } else { self.showAlert("Posts Feed", message: "Unable to fetch Feed") } } } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return items.count } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("PostCellIdentifier") as! PostCell var item = items[indexPath.row] as! PFObject cell.post = item return cell } }
mit
da65e0307e7357ea124123ce024bb176
24.894737
107
0.594851
5.252669
false
false
false
false
plus44/hcr-2016
app/Carthage/Checkouts/SwiftyJSON/Tests/SwiftyJSONTests/NumberTests.swift
4
15996
// NumberTests.swift // // Copyright (c) 2014 - 2016 Pinglin Tang // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import XCTest import SwiftyJSON class NumberTests: XCTestCase { func testNumber() { //getter var json = JSON(NSNumber(value: 9876543210.123456789)) XCTAssertEqual(json.number!, 9876543210.123456789) XCTAssertEqual(json.numberValue, 9876543210.123456789) XCTAssertEqual(json.stringValue, "9876543210.123457") json.string = "1000000000000000000000000000.1" XCTAssertNil(json.number) XCTAssertEqual(json.numberValue.description, "1000000000000000000000000000.1") json.string = "1e+27" XCTAssertEqual(json.numberValue.description, "1000000000000000000000000000") //setter json.number = NSNumber(value: 123456789.0987654321) XCTAssertEqual(json.number!, 123456789.0987654321) XCTAssertEqual(json.numberValue, 123456789.0987654321) json.number = nil XCTAssertEqual(json.numberValue, 0) XCTAssertEqual(json.object as? NSNull, NSNull()) XCTAssertTrue(json.number == nil) json.numberValue = 2.9876 XCTAssertEqual(json.number!, 2.9876) } func testBool() { var json = JSON(true) XCTAssertEqual(json.bool!, true) XCTAssertEqual(json.boolValue, true) XCTAssertEqual(json.numberValue, true as NSNumber) XCTAssertEqual(json.stringValue, "true") json.bool = false XCTAssertEqual(json.bool!, false) XCTAssertEqual(json.boolValue, false) XCTAssertEqual(json.numberValue, false as NSNumber) json.bool = nil XCTAssertTrue(json.bool == nil) XCTAssertEqual(json.boolValue, false) XCTAssertEqual(json.numberValue, 0) json.boolValue = true XCTAssertEqual(json.bool!, true) XCTAssertEqual(json.boolValue, true) XCTAssertEqual(json.numberValue, true as NSNumber) } func testDouble() { var json = JSON(9876543210.123456789) XCTAssertEqual(json.double!, 9876543210.123456789) XCTAssertEqual(json.doubleValue, 9876543210.123456789) XCTAssertEqual(json.numberValue, 9876543210.123456789) XCTAssertEqual(json.stringValue, "9876543210.123457") json.double = 2.8765432 XCTAssertEqual(json.double!, 2.8765432) XCTAssertEqual(json.doubleValue, 2.8765432) XCTAssertEqual(json.numberValue, 2.8765432) json.doubleValue = 89.0987654 XCTAssertEqual(json.double!, 89.0987654) XCTAssertEqual(json.doubleValue, 89.0987654) XCTAssertEqual(json.numberValue, 89.0987654) json.double = nil XCTAssertEqual(json.boolValue, false) XCTAssertEqual(json.doubleValue, 0.0) XCTAssertEqual(json.numberValue, 0) } func testFloat() { var json = JSON(54321.12345) XCTAssertTrue(json.float! == 54321.12345) XCTAssertTrue(json.floatValue == 54321.12345) print(json.numberValue.doubleValue) XCTAssertEqual(json.numberValue, 54321.12345) XCTAssertEqual(json.stringValue, "54321.12345") json.double = 23231.65 XCTAssertTrue(json.float! == 23231.65) XCTAssertTrue(json.floatValue == 23231.65) XCTAssertEqual(json.numberValue, NSNumber(value:23231.65)) json.double = -98766.23 XCTAssertEqual(json.float!, -98766.23) XCTAssertEqual(json.floatValue, -98766.23) XCTAssertEqual(json.numberValue, NSNumber(value:-98766.23)) } func testInt() { var json = JSON(123456789) XCTAssertEqual(json.int!, 123456789) XCTAssertEqual(json.intValue, 123456789) XCTAssertEqual(json.numberValue, NSNumber(value: 123456789)) XCTAssertEqual(json.stringValue, "123456789") json.int = nil XCTAssertTrue(json.boolValue == false) XCTAssertTrue(json.intValue == 0) XCTAssertEqual(json.numberValue, 0) XCTAssertEqual(json.object as? NSNull, NSNull()) XCTAssertTrue(json.int == nil) json.intValue = 76543 XCTAssertEqual(json.int!, 76543) XCTAssertEqual(json.intValue, 76543) XCTAssertEqual(json.numberValue, NSNumber(value: 76543)) json.intValue = 98765421 XCTAssertEqual(json.int!, 98765421) XCTAssertEqual(json.intValue, 98765421) XCTAssertEqual(json.numberValue, NSNumber(value: 98765421)) } func testUInt() { var json = JSON(123456789) XCTAssertTrue(json.uInt! == 123456789) XCTAssertTrue(json.uIntValue == 123456789) XCTAssertEqual(json.numberValue, NSNumber(value: 123456789)) XCTAssertEqual(json.stringValue, "123456789") json.uInt = nil XCTAssertTrue(json.boolValue == false) XCTAssertTrue(json.uIntValue == 0) XCTAssertEqual(json.numberValue, 0) XCTAssertEqual(json.object as? NSNull, NSNull()) XCTAssertTrue(json.uInt == nil) json.uIntValue = 76543 XCTAssertTrue(json.uInt! == 76543) XCTAssertTrue(json.uIntValue == 76543) XCTAssertEqual(json.numberValue, NSNumber(value: 76543)) json.uIntValue = 98765421 XCTAssertTrue(json.uInt! == 98765421) XCTAssertTrue(json.uIntValue == 98765421) XCTAssertEqual(json.numberValue, NSNumber(value: 98765421)) } func testInt8() { let n127 = NSNumber(value: 127) var json = JSON(n127) XCTAssertTrue(json.int8! == n127.int8Value) XCTAssertTrue(json.int8Value == n127.int8Value) XCTAssertTrue(json.number! == n127) XCTAssertEqual(json.numberValue, n127) XCTAssertEqual(json.stringValue, "127") let nm128 = NSNumber(value: -128) json.int8Value = nm128.int8Value XCTAssertTrue(json.int8! == nm128.int8Value) XCTAssertTrue(json.int8Value == nm128.int8Value) XCTAssertTrue(json.number! == nm128) XCTAssertEqual(json.numberValue, nm128) XCTAssertEqual(json.stringValue, "-128") let n0 = NSNumber(value: 0 as Int8) json.int8Value = n0.int8Value XCTAssertTrue(json.int8! == n0.int8Value) XCTAssertTrue(json.int8Value == n0.int8Value) print(json.number) XCTAssertTrue(json.number! == n0) XCTAssertEqual(json.numberValue, n0) #if (arch(x86_64) || arch(arm64)) XCTAssertEqual(json.stringValue, "false") #elseif (arch(i386) || arch(arm)) XCTAssertEqual(json.stringValue, "0") #endif let n1 = NSNumber(value: 1 as Int8) json.int8Value = n1.int8Value XCTAssertTrue(json.int8! == n1.int8Value) XCTAssertTrue(json.int8Value == n1.int8Value) XCTAssertTrue(json.number! == n1) XCTAssertEqual(json.numberValue, n1) #if (arch(x86_64) || arch(arm64)) XCTAssertEqual(json.stringValue, "true") #elseif (arch(i386) || arch(arm)) XCTAssertEqual(json.stringValue, "1") #endif } func testUInt8() { let n255 = NSNumber(value: 255) var json = JSON(n255) XCTAssertTrue(json.uInt8! == n255.uint8Value) XCTAssertTrue(json.uInt8Value == n255.uint8Value) XCTAssertTrue(json.number! == n255) XCTAssertEqual(json.numberValue, n255) XCTAssertEqual(json.stringValue, "255") let nm2 = NSNumber(value: 2) json.uInt8Value = nm2.uint8Value XCTAssertTrue(json.uInt8! == nm2.uint8Value) XCTAssertTrue(json.uInt8Value == nm2.uint8Value) XCTAssertTrue(json.number! == nm2) XCTAssertEqual(json.numberValue, nm2) XCTAssertEqual(json.stringValue, "2") let nm0 = NSNumber(value: 0) json.uInt8Value = nm0.uint8Value XCTAssertTrue(json.uInt8! == nm0.uint8Value) XCTAssertTrue(json.uInt8Value == nm0.uint8Value) XCTAssertTrue(json.number! == nm0) XCTAssertEqual(json.numberValue, nm0) XCTAssertEqual(json.stringValue, "0") let nm1 = NSNumber(value: 1) json.uInt8 = nm1.uint8Value XCTAssertTrue(json.uInt8! == nm1.uint8Value) XCTAssertTrue(json.uInt8Value == nm1.uint8Value) XCTAssertTrue(json.number! == nm1) XCTAssertEqual(json.numberValue, nm1) XCTAssertEqual(json.stringValue, "1") } func testInt16() { let n32767 = NSNumber(value: 32767) var json = JSON(n32767) XCTAssertTrue(json.int16! == n32767.int16Value) XCTAssertTrue(json.int16Value == n32767.int16Value) XCTAssertTrue(json.number! == n32767) XCTAssertEqual(json.numberValue, n32767) XCTAssertEqual(json.stringValue, "32767") let nm32768 = NSNumber(value: -32768) json.int16Value = nm32768.int16Value XCTAssertTrue(json.int16! == nm32768.int16Value) XCTAssertTrue(json.int16Value == nm32768.int16Value) XCTAssertTrue(json.number! == nm32768) XCTAssertEqual(json.numberValue, nm32768) XCTAssertEqual(json.stringValue, "-32768") let n0 = NSNumber(value: 0) json.int16Value = n0.int16Value XCTAssertTrue(json.int16! == n0.int16Value) XCTAssertTrue(json.int16Value == n0.int16Value) print(json.number) XCTAssertTrue(json.number! == n0) XCTAssertEqual(json.numberValue, n0) XCTAssertEqual(json.stringValue, "0") let n1 = NSNumber(value: 1) json.int16 = n1.int16Value XCTAssertTrue(json.int16! == n1.int16Value) XCTAssertTrue(json.int16Value == n1.int16Value) XCTAssertTrue(json.number! == n1) XCTAssertEqual(json.numberValue, n1) XCTAssertEqual(json.stringValue, "1") } func testUInt16() { let n65535 = NSNumber(value: 65535) var json = JSON(n65535) XCTAssertTrue(json.uInt16! == n65535.uint16Value) XCTAssertTrue(json.uInt16Value == n65535.uint16Value) XCTAssertTrue(json.number! == n65535) XCTAssertEqual(json.numberValue, n65535) XCTAssertEqual(json.stringValue, "65535") let n32767 = NSNumber(value: 32767) json.uInt16 = n32767.uint16Value XCTAssertTrue(json.uInt16! == n32767.uint16Value) XCTAssertTrue(json.uInt16Value == n32767.uint16Value) XCTAssertTrue(json.number! == n32767) XCTAssertEqual(json.numberValue, n32767) XCTAssertEqual(json.stringValue, "32767") } func testInt32() { let n2147483647 = NSNumber(value: 2147483647) var json = JSON(n2147483647) XCTAssertTrue(json.int32! == n2147483647.int32Value) XCTAssertTrue(json.int32Value == n2147483647.int32Value) XCTAssertTrue(json.number! == n2147483647) XCTAssertEqual(json.numberValue, n2147483647) XCTAssertEqual(json.stringValue, "2147483647") let n32767 = NSNumber(value: 32767) json.int32 = n32767.int32Value XCTAssertTrue(json.int32! == n32767.int32Value) XCTAssertTrue(json.int32Value == n32767.int32Value) XCTAssertTrue(json.number! == n32767) XCTAssertEqual(json.numberValue, n32767) XCTAssertEqual(json.stringValue, "32767") let nm2147483648 = NSNumber(value: -2147483648) json.int32Value = nm2147483648.int32Value XCTAssertTrue(json.int32! == nm2147483648.int32Value) XCTAssertTrue(json.int32Value == nm2147483648.int32Value) XCTAssertTrue(json.number! == nm2147483648) XCTAssertEqual(json.numberValue, nm2147483648) XCTAssertEqual(json.stringValue, "-2147483648") } func testUInt32() { let n2147483648 = NSNumber(value: 2147483648 as UInt32) var json = JSON(n2147483648) XCTAssertTrue(json.uInt32! == n2147483648.uint32Value) XCTAssertTrue(json.uInt32Value == n2147483648.uint32Value) XCTAssertTrue(json.number! == n2147483648) XCTAssertEqual(json.numberValue, n2147483648) XCTAssertEqual(json.stringValue, "2147483648") let n32767 = NSNumber(value: 32767 as UInt32) json.uInt32 = n32767.uint32Value XCTAssertTrue(json.uInt32! == n32767.uint32Value) XCTAssertTrue(json.uInt32Value == n32767.uint32Value) XCTAssertTrue(json.number! == n32767) XCTAssertEqual(json.numberValue, n32767) XCTAssertEqual(json.stringValue, "32767") let n0 = NSNumber(value: 0 as UInt32) json.uInt32Value = n0.uint32Value XCTAssertTrue(json.uInt32! == n0.uint32Value) XCTAssertTrue(json.uInt32Value == n0.uint32Value) XCTAssertTrue(json.number! == n0) XCTAssertEqual(json.numberValue, n0) XCTAssertEqual(json.stringValue, "0") } func testInt64() { let int64Max = NSNumber(value: INT64_MAX) var json = JSON(int64Max) XCTAssertTrue(json.int64! == int64Max.int64Value) XCTAssertTrue(json.int64Value == int64Max.int64Value) XCTAssertTrue(json.number! == int64Max) XCTAssertEqual(json.numberValue, int64Max) XCTAssertEqual(json.stringValue, int64Max.stringValue) let n32767 = NSNumber(value: 32767) json.int64 = n32767.int64Value XCTAssertTrue(json.int64! == n32767.int64Value) XCTAssertTrue(json.int64Value == n32767.int64Value) XCTAssertTrue(json.number! == n32767) XCTAssertEqual(json.numberValue, n32767) XCTAssertEqual(json.stringValue, "32767") let int64Min = NSNumber(value: (INT64_MAX-1) * -1) json.int64Value = int64Min.int64Value XCTAssertTrue(json.int64! == int64Min.int64Value) XCTAssertTrue(json.int64Value == int64Min.int64Value) XCTAssertTrue(json.number! == int64Min) XCTAssertEqual(json.numberValue, int64Min) XCTAssertEqual(json.stringValue, int64Min.stringValue) } func testUInt64() { let uInt64Max = NSNumber(value: UINT64_MAX) var json = JSON(uInt64Max) XCTAssertTrue(json.uInt64! == uInt64Max.uint64Value) XCTAssertTrue(json.uInt64Value == uInt64Max.uint64Value) XCTAssertTrue(json.number! == uInt64Max) XCTAssertEqual(json.numberValue, uInt64Max) XCTAssertEqual(json.stringValue, uInt64Max.stringValue) let n32767 = NSNumber(value: 32767) json.int64 = n32767.int64Value XCTAssertTrue(json.int64! == n32767.int64Value) XCTAssertTrue(json.int64Value == n32767.int64Value) XCTAssertTrue(json.number! == n32767) XCTAssertEqual(json.numberValue, n32767) XCTAssertEqual(json.stringValue, "32767") } }
apache-2.0
543ebf2b786bdb2f36d47991b0f78413
39.090226
86
0.652226
4.195122
false
false
false
false
MillmanY/MMPlayerView
Example/MMPlayerView/SwiftUIView/Modifier/ObserverCell.swift
1
2470
// // ObserverCell.swift // MMPlayerView_Example // // Created by Millman on 2020/1/15. // Copyright © 2020 CocoaPods. All rights reserved. // import Foundation import SwiftUI import MMPlayerView @available(iOS 13.0.0, *) struct CellPlayerFramePreference: ViewModifier { let index: Int @Binding var frame: CGRect func body(content: Content) -> some View { content .background(GeometryReader{ (proxy) in Color.clear .preference(key: Key.self, value: [Key.Info(idx: self.index, frame: proxy.frame(in: .global))]) }) .onPreferenceChange(Key.self) { (value) in if let f = value.first { self.frame = f.frame } } } struct Key: PreferenceKey, Equatable { struct Info: Equatable { let idx: Int let frame: CGRect init(idx: Int, frame: CGRect) { self.idx = idx self.frame = frame } } static var defaultValue: [Info] = [] static func reduce(value: inout [Info], nextValue: () -> [Info]) { value.append(contentsOf: nextValue()) } } } @available(iOS 13.0.0, *) struct CellPlayerVisiblePreference: ViewModifier { @State var r: CGRect = .zero @Binding var list: [CellPlayerFramePreference.Key.Info] init(list: Binding<[CellPlayerFramePreference.Key.Info]>) { self._list = list } func body(content: Content) -> some View { content.background(GeometryReader{ (proxy) in Color.clear.preference(key: Key.self, value: [proxy.frame(in: .global)]) }) .modifier(FrameModifier<CellPlayerVisiblePreference.Key>(rect: $r)) .onPreferenceChange(CellPlayerFramePreference.Key.self, perform: { (value) in let sort = value.sorted { $0.frame.origin.y < $1.frame.origin.y }.filter { self.r.intersects($0.frame) }.sorted { $0.idx < $1.idx } self.list = sort }) } struct Key: PreferenceKey, Equatable { static var defaultValue: [CGRect] = [] static func reduce(value: inout [CGRect], nextValue: () -> [CGRect]) { let n = nextValue() if n.count > 0 { value.append(contentsOf: n) } } } }
mit
21c78ca52471558490997f48ed4bffdc
30.653846
96
0.5403
4.22774
false
false
false
false
EmmaXiYu/SE491
DonateParkSpot/MySpotTableViewController.swift
1
5239
// // MySpotTableViewController.swift // DonateParkSpot // // Created by Pravangsu Biswas on 10/27/15. // Copyright © 2015 Apple. All rights reserved. // import UIKit import Parse public class MySpotBiddingTableViewController: UITableViewController { @IBOutlet weak var Menu: UIBarButtonItem! var count = 0 var datas = [Spot] () var mySpotArray:NSMutableArray = [] override public func viewDidLoad() { super.viewDidLoad() self.readDatafromServer() self.title = "My Spots" Menu.target = self.revealViewController() Menu.action = Selector("revealToggle:") self.view.addGestureRecognizer(self.revealViewController().panGestureRecognizer()) } func readDatafromServer() { self.datas.removeAll() var query: PFQuery = PFQuery() query = PFQuery(className: "Spot") let currentUser = PFUser.currentUser() query.includeKey("owner") query.whereKey("owner", equalTo:currentUser!) query.orderByDescending("leavingTime") query.findObjectsInBackgroundWithBlock { (objects:[PFObject]?, error:NSError?) -> Void in if error == nil { for object in objects! { let s = Spot(object: object) self.datas.append(s!) } } self.tableView.reloadData() } } //Update the View with Data from Server func update() { count++ //update your table data here self.readDatafromServer() dispatch_async(dispatch_get_main_queue()) { self.tableView.reloadData() } } //This func load take PFList of Bids and convert in to a Model Bids . Currently not in use func GetBidEgar(bidsArray: [PFObject]?) -> [Bid] { var index = 0 var bidList = [Bid]() for object in bidsArray! { let bi: Bid = Bid() let timestamp = object["Timestamp"] as! NSDate let value = object["Value"] as! Double bi.value = value //bi.timestamp = timestamp bidList.insert(bi, atIndex: index) index = index + 1 } return bidList } ///Get in momory BID to test : currently Not in use public func GetBid(i: Int) -> [Bid] { var bidList = [Bid]() for index in 0...i-1 { let bi: Bid = Bid() bi.value = 3 + Double(i) //bi.timestamp = NSDate() bidList.insert(bi, atIndex: index) } return bidList } //Get a bid list for spot id Not in use func GetBidList(spotid: String) -> [Bid] { var index = 0 var bidList = [Bid]() var query: PFQuery = PFQuery() query = PFQuery(className: "Bid") query.whereKey("SpotId", equalTo:spotid) query.findObjectsInBackgroundWithBlock { (objects:[PFObject]?, error:NSError?) -> Void in if error == nil { for object in objects! { let bi: Bid = Bid() let timestamp = object["Timestamp"] as! NSDate let value = object["Value"] as! Double bi.value = value //bi.timestamp = timestamp bidList.insert(bi, atIndex: index) index = index + 1 } } } return bidList } override public func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source override public func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } override public func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return datas.count } /**/ override public func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("MySpotLabelCell", forIndexPath: indexPath) as! SpotCellController let s = datas[indexPath.row] cell.spot = s cell.address.text = s.addressText cell.time.text = (s.timeToLeave!.description) if s.statusId == 4 { cell.backgroundColor = UIColor.lightGrayColor() cell.cancelButton.enabled = false cell.selectionStyle = .None cell.userInteractionEnabled = false } return cell } override public func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == "ToMySpotBidMulti" { if let destinationVC = segue.destinationViewController as? MySpotMultiBidTableViewController{ if let blogIndex = tableView.indexPathForSelectedRow?.row { destinationVC.spot = datas[blogIndex] } } } // } }
apache-2.0
7529883f713413a5a62f205ec786ac9f
30.365269
129
0.554219
5.026871
false
false
false
false
sora0077/DribbbleKit
DribbbleKit/Sources/Teams/Members/ListTeamMembers.swift
1
737
// // ListTeamMembers.swift // DribbbleKit // // Created by 林 達也 on 2017/04/20. // Copyright © 2017年 jp.sora0077. All rights reserved. // import Foundation import APIKit import Alter public struct ListTeamMembers<Data: UserData>: PaginatorRequest { public typealias Element = Data public let path: String public let parameters: Any? public init(id: User.Identifier, page: Int? = nil, perPage: Int? = configuration?.perPage) { path = "/teams/\(id.value)/members" parameters = [ "page": page, "per_page": perPage].cleaned } public init(path: String, parameters: [String : Any]) throws { self.path = path self.parameters = parameters } }
mit
3d371b93c3f0e4c59c0917a322e5a881
23.266667
96
0.637363
3.913978
false
false
false
false
AfricanSwift/TUIKit
TUIKit/Source/Foundation/Custom+Extensions.swift
1
4827
// // File: Custom+Extensions.swift // Created by: African Swift import Foundation // MARK: - // MARK: Threading - infix operator ~> {} /// Executes the lefthand closure on a background thread and, /// upon completion, the righthand closure on the main thread. /// Passes the background closure's output, if any, to the main closure. /// /// - parameters: /// - backgroundClosure: code to execute on background thread /// - mainClosure: code to execute on main thread after background completes /// - returns: Void internal func ~> <R> ( backgroundClosure: () -> R, mainClosure: (result: R) -> ()) { queue.async { let result = backgroundClosure() DispatchQueue.main.async(execute: { mainClosure(result: result) }) } } /// Serial dispatch queue used by the ~> operator /// /// - returns: dispatch_queue_t private let queue = DispatchQueue( label: "serial-worker", attributes: DispatchQueueAttributes.serial) // MARK: - // MARK: Array Extensions - internal extension Array { /// Return Array of type T with tuple of Array Index and Element /// /// - parameters: /// - function: map function to execute /// - returns: (Int, Element) internal func mapWithIndex<T>(_ function: (Int, Element) -> T) -> [T] { return zip((self.indices), self).map(function) } } /// Initialize 2D array /// /// - parameters: /// - d1: 1st array dimension /// - d2: 2nd array dimension /// - repeatedValue: Initial array value /// - returns: Two dimensional array of type T internal func init2D<T>(d1: Int, d2: Int, repeatedValue value: T) -> [[T]] { return Array( repeating: Array( repeating: value, count: d2), count: d1) } /// Initialize 3D array /// /// - parameters: /// - d1: 1st array dimension /// - d2: 2nd array dimension /// - d3: 3rd array dimension /// - repeatedValue: Initial array value /// - returns: Three dimensional array of type T internal func init3D<T>(d1: Int, d2: Int, d3: Int, repeatedValue value: T) -> [[[T]]] { return Array( repeating: Array( repeating: Array( repeating: value, count: d3), count: d2), count: d1) } /// Initialize 4D array /// /// - parameters: /// - d1: 1st array dimension /// - d2: 2nd array dimension /// - d3: 3rd array dimension /// - d4: 4th array dimension /// - repeatedValue: Initial array value /// - returns: Fourth dimensional array of type T internal func init4D<T>(d1: Int, d2: Int, d3: Int, d4: Int, repeatedValue value: T) -> [[[[T]]]] { return Array( repeating: Array( repeating: Array( repeating: Array( repeating: value, count: d4), count: d3), count: d2), count: d1) } // MARK: - // MARK: Code / Execution Timing - /// Measure closure exection /// /// - parameters: /// - title: String /// - closure: closure to measure execution duration internal func measure(_ title: String = "", closure: () -> Void) { let start = Date().timeIntervalSince1970 closure() let result = String(format: "%.5f ms", title, (Date().timeIntervalSince1970 - start) * 1000) print("\(title) duration: \(result)") } // MARK: - // MARK: C-Style Loop - /// Replacement for C Style For Loop for ;; /// /// ```` /// var i: Int = 0 // initialization /// for _ in CStyleLoop(i < 10, i += 1) /// { /// print(i) /// } /// ```` /// - Author: Joe Groff (Apple) internal struct CStyleLoop: Sequence, IteratorProtocol { let condition: () -> Bool let increment: () -> Void var started = false internal init( _ condition: @autoclosure(escaping)() -> Bool, _ increment: @autoclosure(escaping)() -> Void) { self.increment = increment self.condition = condition } internal func makeIterator() -> CStyleLoop { return self } internal mutating func next() -> Void? { if started { increment() } else { started = true } if condition() { return () } return nil } } //// MARK: - guard / if let unwrapping debugging - // //infix operator =∅ {} ///// Nil Evaluate Operator ///// Useful to isolate a failure with multiple unwraps in guard by adding =∅ (#file, #line) ///// - parameter lhs: left hand side of operator ///// - parameter reference: tuple containing current file and line number ///// - returns: original unaltered lhs of type T //internal func =∅<T> (lhs: T?, reference: (file: String, line: Int)) -> T? { // #if !debug // var unwrap = false // if let _ = lhs { unwrap = true } // let source = reference.file // .characters // .split("/") // .map{String($0)} // .last ?? "" // let outcome = "unwrap(\(unwrap ? "success" : "failure"))" // let status = "\(source)(\(reference.line)), \(outcome), value: \(lhs)" // print(status) // #endif // return lhs //}
mit
fcae217fda85eeea1a14be7d5f9bd163
24.240838
96
0.610039
3.592399
false
false
false
false
lionchina/RxSwiftBook
RxTableViewWithSection/RxTableViewWithSection/AppDelegate.swift
1
4623
// // AppDelegate.swift // RxTableViewWithSection // // Created by MaxChen on 04/08/2017. // Copyright © 2017 com.linglustudio. All rights reserved. // import UIKit import CoreData @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. 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 invalidate graphics rendering callbacks. 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 active 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:. // Saves changes in the application's managed object context before the application terminates. self.saveContext() } // MARK: - Core Data stack lazy var persistentContainer: NSPersistentContainer = { /* The persistent container for the application. This implementation creates and returns a container, having loaded the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail. */ let container = NSPersistentContainer(name: "RxTableViewWithSection") container.loadPersistentStores(completionHandler: { (storeDescription, error) in if let error = error as NSError? { // Replace this implementation with code to handle the error appropriately. // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. /* Typical reasons for an error here include: * The parent directory does not exist, cannot be created, or disallows writing. * The persistent store is not accessible, due to permissions or data protection when the device is locked. * The device is out of space. * The store could not be migrated to the current model version. Check the error message to determine what the actual problem was. */ fatalError("Unresolved error \(error), \(error.userInfo)") } }) return container }() // MARK: - Core Data Saving support func saveContext () { let context = persistentContainer.viewContext if context.hasChanges { do { try context.save() } catch { // Replace this implementation with code to handle the error appropriately. // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. let nserror = error as NSError fatalError("Unresolved error \(nserror), \(nserror.userInfo)") } } } }
apache-2.0
1713e37dc17671914a36e6c1a213cadb
48.698925
285
0.688014
5.865482
false
false
false
false
GeoffSpielman/SimonSays
simon_says_iOS_app/SimonSays/ChatLog.swift
1
4779
// // ChatLog.swift // SimonSays // // Created by Will Clark on 2016-06-25. // Copyright © 2016 WillClark. All rights reserved. // import UIKit class ChatLog: UIScrollView, UIScrollViewDelegate { var messageQueue : [ChatRecord] = [] var darkColour : UIColor! var lightColour : UIColor! init(parent : UIView, frameHeight : CGFloat, lightColour : UIColor, darkColour : UIColor) { super.init(frame: CGRect(x: screenSize.width * 0.025, y: 20, width: screenSize.width * 0.95, height: frameHeight)) self.darkColour = darkColour self.layer.cornerRadius = screenSize.width / 20 self.backgroundColor = lightColour self.lightColour = lightColour parent.addSubview(self) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func addMessage(message : String, isLocal : Bool, isRecent : Bool) { let newMessage = ChatRecord(parent: self, message: message, isLocal: isLocal, darkColour: darkColour, lightColour: lightColour) let newMessageFrame = UIView(frame: CGRect(x: 0, y: 0, width: newMessage.frame.width + 10, height: newMessage.frame.height + 8)) newMessageFrame.center = newMessage.center newMessage.frame = CGRect(x: 5, y: 4, width: newMessage.frame.width, height: newMessage.frame.height) var bottomOffset = CGPoint(x: 0, y: self.contentSize.height - self.bounds.size.height - newMessage.frame.height) self.setContentOffset(bottomOffset, animated: true) newMessageFrame.addSubview(newMessage) self.addSubview(newMessageFrame) messageQueue.insert(newMessage, atIndex: 0) arrangeMessages() bottomOffset = CGPoint(x: 0, y: self.contentSize.height - self.bounds.size.height) self.setContentOffset(bottomOffset, animated: true) } func arrangeMessages() { var runningHeight : CGFloat = self.frame.width * 0.02 for i in messageQueue { runningHeight += self.frame.width * 0.02 + i.frame.height } self.contentSize = CGSize(width: self.frame.width, height: max(runningHeight, self.frame.height)) runningHeight = self.frame.width * 0.02 for i in messageQueue { i.center = CGPoint(x: i.center.x, y: self.contentSize.height - runningHeight - i.frame.height / 2) runningHeight += self.frame.width * 0.02 + i.frame.height } } } class ChatRecord: UILabel { var isLocal : Bool! init(parent : UIView, message : String, isLocal : Bool, darkColour : UIColor, lightColour : UIColor) { super.init(frame: CGRect(x: 0, y: 0, width: parent.frame.width * 0.5, height: 0)) self.backgroundColor = darkColour self.textColor = UIColor.whiteColor() self.clipsToBounds = true self.text = message self.isLocal = isLocal self.numberOfLines = 0 self.lineBreakMode = NSLineBreakMode.ByWordWrapping self.frame = CGRect(x: 0, y: 0, width: self.frame.width , height: self.requiredHeight() + 16) self.frame = CGRect(x: 0, y: 0, width: self.requiredWidth() + 20 , height: self.frame.height) if isLocal { self.center = CGPoint(x: (parent.frame.width * 0.98) - (self.frame.width / 2), y: self.center.y) print("Local") } else { self.center = CGPoint(x: (parent.frame.width * 0.02) + (self.frame.width / 2), y: self.center.y) print("Not local") } self.layer.cornerRadius = screenSize.width / 20 self.textAlignment = .Center } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } extension UILabel{ func requiredHeight() -> CGFloat{ let label : UILabel = UILabel(frame: CGRectMake(0, 0, self.frame.width, CGFloat.max)) label.numberOfLines = 0 label.lineBreakMode = NSLineBreakMode.ByWordWrapping label.font = self.font label.text = self.text label.sizeToFit() return label.frame.height } func requiredWidth() -> CGFloat{ let label : UILabel = UILabel(frame: CGRectMake(0, 0, self.frame.width, CGFloat.max)) label.numberOfLines = 0 label.lineBreakMode = NSLineBreakMode.ByWordWrapping label.font = self.font label.text = self.text label.sizeToFit() return label.frame.width } }
mit
4411cf4702ca68a8e0a7dd06fc60676f
30.025974
136
0.600879
4.327899
false
false
false
false
jerrypupu111/LearnDrawingToolSet
SwiftGL-Demo/Source/SubViewAnimationGestureHandler.swift
1
7873
// // EdgeGestureHandler.swift // SwiftGL // // Created by jerry on 2015/8/26. // Copyright © 2015年 Jerry Chan. All rights reserved. // import UIKit class SubViewAnimationGestureHandler:NSObject { weak var mainView:UIView! weak var paintView:UIView! //播放區域 play back panel weak var playBackPanel:UIView! weak var playBackPanelBottomConstraint: NSLayoutConstraint! var playBackPanelHideBottomY:CGFloat = 128 var playBackPanelHeight:CGFloat = 128 //工具列 tool view weak var toolView:UIView! weak var toolViewLeadingConstraint: NSLayoutConstraint! var toolViewHideLeadingX:CGFloat = -240 var toolViewWidth:CGFloat = 240 var isToolPanelLocked:Bool = false //註解欄位 weak var noteListView:UIView! weak var noteListViewTrailingConstraint: NSLayoutConstraint! var noteListViewTrailingX:CGFloat = -240 var noteListViewWidth:CGFloat = 240 var toolViewState:SubViewPanelAnimateState! weak var pvController:PaintViewController! init(pvController:PaintViewController) { super.init() self.mainView = pvController.mainView self.paintView = pvController.paintView self.toolView = pvController.toolView self.toolViewLeadingConstraint = pvController.toolViewLeadingConstraint self.playBackPanel = pvController.playBackView self.playBackPanelBottomConstraint = pvController.playBackViewBottomConstraint self.noteListView = pvController.noteListView self.noteListViewTrailingConstraint = pvController.noteListViewTrailingConstraint self.pvController = pvController hidePlayBackView(0) //hideToolView(0) //playBackPanelBottomConstraint.constant = playBackPanelHideBottomY //toolViewLeadingConstraint.constant = toolViewHideLeadingX let toolViewPanGestureRecognizer = UIPanGestureRecognizer(target: self, action: #selector(SubViewAnimationGestureHandler.handlePan(_:))) toolView.addGestureRecognizer(toolViewPanGestureRecognizer) let leftEdgeGestureReconizer = UIScreenEdgePanGestureRecognizer(target: self, action: #selector(SubViewAnimationGestureHandler.handleLeftEdgePan(_:))) leftEdgeGestureReconizer.edges = UIRectEdge.left mainView.addGestureRecognizer(leftEdgeGestureReconizer) let leftEdgeGestureReconizer2 = UIScreenEdgePanGestureRecognizer(target: self, action: #selector(SubViewAnimationGestureHandler.handleLeftEdgePan(_:))) leftEdgeGestureReconizer2.edges = UIRectEdge.left paintView.addGestureRecognizer(leftEdgeGestureReconizer2) /* let bottomEdgeGestureRecognizer = UIScreenEdgePanGestureRecognizer(target: self, action: "handleBottemEdgePan:") bottomEdgeGestureRecognizer.edges = UIRectEdge.Bottom mainView.addGestureRecognizer(bottomEdgeGestureRecognizer) //playback panel let playBackPanelPanRecognizer = UIPanGestureRecognizer(target: self, action: "handlePlayBackPanelPan:") playBackPanel.addGestureRecognizer(playBackPanelPanRecognizer) */ } func handlePan(_ sender:UIPanGestureRecognizer) { let delta = sender.translation(in: mainView) let vel = sender.velocity(in: mainView) switch sender.state { case UIGestureRecognizerState.changed: print("tool view pan", terminator: "") toolViewLeadingConstraint.constant = delta.x if toolViewLeadingConstraint.constant > 0 { toolViewLeadingConstraint.constant = 0 } case .ended: if vel.x < -100 { print("hide", terminator: "") hideToolView(0.2) } else { print("show", terminator: "") showToolView(0.2) } default: break } toolView.layoutIfNeeded() } func handleLeftEdgePan(_ sender:UIScreenEdgePanGestureRecognizer) { if isToolPanelLocked { return } let delta = sender.translation(in: mainView) switch sender.state { //case UIGestureRecognizerState.Changed: // toolView.center = CGPointMake(toolView_center.x + delta.x, toolView_center.y) case .ended: if delta.x > 0 { showToolView(0.2) } default: break } } var isToolViewHidden:Bool = false func showToolView(_ duration:TimeInterval) { UIView.animate(withDuration: duration, delay: 0.0, options: UIViewAnimationOptions.curveEaseOut, animations: { self.toolViewLeadingConstraint.constant = 0 self.toolView.layoutIfNeeded() }, completion: { finished in self.isToolViewHidden = false } ) } func hideToolView(_ duration:TimeInterval) { if isToolViewHidden == false { UIView.animate(withDuration: duration, delay: 0.0, options: UIViewAnimationOptions.curveEaseOut, animations: { self.toolViewLeadingConstraint.constant = self.toolViewHideLeadingX self.toolView.layoutIfNeeded() }, completion: { finished in self.isToolViewHidden = true } ) } } func handleBottemEdgePan(_ sender:UIScreenEdgePanGestureRecognizer) { let delta = sender.translation(in: mainView) switch sender.state { //case UIGestureRecognizerState.Changed: // toolView.center = CGPointMake(toolView_center.x + delta.x, toolView_center.y) case .ended: if delta.y < 0 { showPlayBackView(0.2) } default: break } } func handlePlayBackPanelPan(_ sender:UIPanGestureRecognizer) { let delta = sender.translation(in: mainView) let vel = sender.velocity(in: mainView) switch sender.state { case UIGestureRecognizerState.changed: playBackPanelBottomConstraint.constant = delta.y if playBackPanelBottomConstraint.constant < -playBackPanelHeight { playBackPanelBottomConstraint.constant = -playBackPanelHeight } case .ended: if vel.y > 10 { hidePlayBackView(0.2) } else { showPlayBackView(0.2) } default: break } } func showPlayBackView(_ duration:TimeInterval) { UIView.animate(withDuration: duration, delay: 0.0, options: UIViewAnimationOptions.curveEaseOut, animations: { self.playBackPanelBottomConstraint.constant = 0 }, completion: { finished in } ) } func hidePlayBackView(_ duration:TimeInterval) { UIView.animate(withDuration: duration, delay: 0.0, options: UIViewAnimationOptions.curveEaseOut, animations: { self.playBackPanelBottomConstraint.constant = self.playBackPanelHideBottomY }, completion: { finished in } ) } }
mit
091702b107dcd56633f9a977a55293d0
29.418605
159
0.592762
5.569908
false
false
false
false
DataBreweryIncubator/StructuredQuery
Tests/RelationTests/ExpressionTests.swift
1
1755
import XCTest @testable import Relation @testable import Schema @testable import Types // TODO: name for alias, tableColumn, tablelikeColumn class ExpressionTestCase: XCTestCase { func testNullLiteral(){ let e: Expression e = nil XCTAssertEqual(e, Expression.null) } func testStringLiteral(){ let e: Expression e = "text" XCTAssertEqual(e, Expression.string("text")) } func testIntLiteral(){ let e: Expression e = 1024 XCTAssertEqual(e, Expression.integer(1024)) } func testBoolLiteral(){ let e: Expression e = true XCTAssertEqual(e, Expression.bool(true)) } func testBinaryOperator(){ let a: Expression = 1 let b: Expression = 2 var e: Expression e = a + b if case .binary = e { } else { XCTFail("Expression is not a binary expression") } e = a == b if case .binary = e { } else { XCTFail("Expression is not a binary expression") } } func testChilren() { var e: Expression e = nil XCTAssertEqual(e.children.count, 0) e = 1 XCTAssertEqual(e.children.count, 0) e = "text" XCTAssertEqual(e.children.count, 0) e = Expression.integer(1) + (Expression.integer(2) + 3) XCTAssertEqual(e.children.count, 2) XCTAssertEqual(e.children[0], Expression.integer(1)) } // FIXME: Enable this test func _testBaseTables() { var e: Expression e = nil // XCTAssertEqual(e.baseTables.count, 0) let table = Table("events", Column("id", INTEGER)) } }
mit
d5d5730838fb8c29052ff24859f6c202
19.406977
63
0.554416
4.3875
false
true
false
false
PlanTeam/BSON
Sources/BSON/Types/AnyPrimitive.swift
1
3438
import Foundation public struct AnyPrimitive: PrimitiveEncodable, Hashable, Encodable, Decodable { public static func == (lhs: AnyPrimitive, rhs: AnyPrimitive) -> Bool { return lhs.primitive.equals(rhs.primitive) } public func hash(into hasher: inout Hasher) { switch primitive { case let value as Double: value.hash(into: &hasher) case let value as String: value.hash(into: &hasher) case let value as Document: value.hash(into: &hasher) case let value as Binary: value.hash(into: &hasher) case let value as ObjectId: value.hash(into: &hasher) case let value as Bool: value.hash(into: &hasher) case let value as Date: value.hash(into: &hasher) case let value as Int32: value.hash(into: &hasher) case let value as _BSON64BitInteger: value.hash(into: &hasher) case let value as Timestamp: value.hash(into: &hasher) case let value as Decimal128: value.hash(into: &hasher) case is Null: ObjectIdentifier(Null.self).hash(into: &hasher) case is MaxKey: ObjectIdentifier(MaxKey.self).hash(into: &hasher) case is MinKey: ObjectIdentifier(MinKey.self).hash(into: &hasher) case let value as RegularExpression: value.hash(into: &hasher) case let value as JavaScriptCode: value.hash(into: &hasher) case let value as JavaScriptCodeWithScope: value.hash(into: &hasher) case let value as BSONPrimitiveRepresentable: AnyPrimitive(value.primitive).hash(into: &hasher) default: fatalError("Invalid primitive") } } public let primitive: Primitive public init(_ primitive: Primitive) { self.primitive = primitive } public func encodePrimitive() throws -> Primitive { primitive } public func encode(to encoder: Encoder) throws { try primitive.encode(to: encoder) } public init(from decoder: Decoder) throws { if let decoder = decoder as? _BSONDecoder { self.primitive = decoder.primitive ?? Null() } else { // TODO: Unsupported decoding method throw BSONTypeConversionError(from: Any.self, to: Primitive.self) } } } public struct EitherPrimitive<L: Primitive, R: Primitive>: PrimitiveEncodable, Sendable, Encodable { private enum Value: Sendable { case l(L) case r(R) } private let value: Value public var primitive: Primitive { switch value { case .l(let l): return l case .r(let r): return r } } public var lhs: L? { switch value { case .l(let l): return l case .r: return nil } } public var rhs: R? { switch value { case .l: return nil case .r(let r): return r } } public init(_ value: L) { self.value = .l(value) } public init(_ value: R) { self.value = .r(value) } public func encodePrimitive() throws -> Primitive { primitive } public func encode(to encoder: Encoder) throws { try primitive.encode(to: encoder) } }
mit
856c553acec20858dc51eec3fd77ae28
27.890756
100
0.567772
4.419023
false
false
false
false
russbishop/swift
test/type/protocol_composition.swift
1
3047
// RUN: %target-parse-verify-swift func canonical_empty_protocol() -> protocol<> { return 1 } protocol P1 { func p1() func f(_: Int) -> Int } protocol P2 : P1 { func p2() } protocol P3 { func p3() } protocol P4 : P3 { func p4() func f(_: Double) -> Double } typealias Any = protocol<> typealias Any2 = protocol< > // Okay to inherit a typealias for a protocol<> type. protocol P5 : Any { } extension Int : P5 { } typealias Bogus = protocol<P1, Int> // expected-error{{non-protocol type 'Int' cannot be used within 'protocol<...>'}} func testEquality() { // Remove duplicates from protocol-conformance types. let x1 : (_ : protocol<P2, P4>) -> () let x2 : (_ : protocol<P3, P4, P2, P1>) -> () x1 = x2 _ = x1 // Singleton protocol-conformance types, after duplication, are the same as // simply naming the protocol type. let x3 : (_ : protocol<P2, P1>) -> () let x4 : (_ : P2) -> () x3 = x4 _ = x3 // Empty protocol-conformance types are empty. let x5 : (_ : Any) -> () let x6 : (_ : Any2) -> () x5 = x6 _ = x5 let x7 : (_ : protocol<P1, P3>) -> () let x8 : (_ : protocol<P2>) -> () x7 = x8 // expected-error{{cannot assign value of type '(P2) -> ()' to type '(protocol<P1, P3>) -> ()'}} _ = x7 } // Name lookup into protocol-conformance types func testLookup() { let x1 : protocol<P2, P1, P4> x1.p1() x1.p2() x1.p3() x1.p4() var _ : Int = x1.f(1) var _ : Double = x1.f(1.0) } protocol REPLPrintable { func replPrint() } protocol SuperREPLPrintable : REPLPrintable { func superReplPrint() } protocol FooProtocol { func format(_ kind: UnicodeScalar, layout: String) -> String } struct SuperPrint : REPLPrintable, FooProtocol, SuperREPLPrintable { func replPrint() {} func superReplPrint() {} func format(_ kind: UnicodeScalar, layout: String) -> String {} } struct Struct1 {} extension Struct1 : REPLPrintable, FooProtocol { func replPrint() {} func format(_ kind: UnicodeScalar, layout: String) -> String {} } func accept_manyPrintable(_: protocol<REPLPrintable, FooProtocol>) {} func return_superPrintable() -> protocol<FooProtocol, SuperREPLPrintable> {} func testConversion() { // Conversions for literals. var x : protocol<REPLPrintable, FooProtocol> = Struct1() accept_manyPrintable(Struct1()) // Conversions for nominal types that conform to a number of protocols. let sp : SuperPrint x = sp accept_manyPrintable(sp) // Conversions among existential types. var x2 : protocol<SuperREPLPrintable, FooProtocol> x2 = x // expected-error{{value of type 'protocol<FooProtocol, REPLPrintable>' does not conform to 'protocol<FooProtocol, SuperREPLPrintable>' in assignment}} x = x2 // Subtyping var _ : () -> protocol<FooProtocol, SuperREPLPrintable> = return_superPrintable // FIXME: closures make ABI conversions explicit. rdar://problem/19517003 var _ : () -> protocol<FooProtocol, REPLPrintable> = { return_superPrintable() } } // Test the parser's splitting of >= into > and =. var x : protocol<P5>=17
apache-2.0
966ed81f5481920f12f77743b73ce4a8
23.572581
160
0.653758
3.412094
false
false
false
false
Daniel-Lopez/EZSwiftExtensions
EZSwiftExtensionsTests/EZSwiftExtensionsTestsNSDate.swift
1
1723
// // EZSwiftExtensionsTestsNSDate.swift // EZSwiftExtensions // // Created by Valentino Urbano on 28/01/16. // Copyright © 2016 Goktug Yilmaz. All rights reserved. // import XCTest class EZSwiftExtensionsTestsNSDate: XCTestCase { // note that NSDate uses UTC in NSDate(timeIntervalSince1970: _) var string: String! let format = "dd-mm-yyyy hh:mm:ss" override func setUp() { super.setUp() string = "01-01-1970 00:00:00" } func testDateFromString() { guard let dateFromString = NSDate(fromString: string, format: format) else { XCTFail("Date From String Couldn't be initialized.") return } XCTAssertEqualWithAccuracy(dateFromString.timeIntervalSince1970, 0, accuracy: 60 * 60 * 24) } func testDateToString() { let dateToString = NSDate(timeIntervalSince1970: 0).toString(format: format) guard let dateFromString = NSDate(fromString: dateToString, format: format) else { XCTFail("Date From String Couldn't be initialized.") return } XCTAssertEqualWithAccuracy(dateFromString.timeIntervalSince1970, 0, accuracy: 60 * 60 * 24) } func testTimePassedBetweenDates() { let date = NSDate(timeIntervalSince1970: 0) XCTAssertTrue(date.timePassed().containsString("years")) let now = NSDate() XCTAssertTrue(now.timePassed().containsString("now") || now.timePassed().containsString("seconds")) } func testComparable() { let date = NSDate() let future = NSDate(timeIntervalSinceNow: 1000) XCTAssertTrue(date < future) XCTAssertFalse(date > future) XCTAssertTrue(date == date) } }
mit
d9b4c158e95570ca644eee9a43229649
31.490566
107
0.655633
4.704918
false
true
false
false
AgaKhanFoundation/WCF-iOS
Pods/FirebaseCoreInternal/FirebaseCore/Internal/Sources/HeartbeatLogging/HeartbeatController.swift
2
5645
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import Foundation /// An object that provides API to log and flush heartbeats from a synchronized storage container. public final class HeartbeatController { /// The thread-safe storage object to log and flush heartbeats from. private let storage: HeartbeatStorageProtocol /// The max capacity of heartbeats to store in storage. private let heartbeatsStorageCapacity: Int = 30 /// Current date provider. It is used for testability. private let dateProvider: () -> Date /// Used for standardizing dates for calendar-day comparision. static let dateStandardizer: (Date) -> (Date) = { var calendar = Calendar(identifier: .iso8601) calendar.locale = Locale(identifier: "en_US_POSIX") calendar.timeZone = TimeZone(secondsFromGMT: 0)! return calendar.startOfDay(for:) }() /// Public initializer. /// - Parameter id: The `id` to associate this controller's heartbeat storage with. public convenience init(id: String) { self.init(id: id, dateProvider: Date.init) } /// Convenience initializer. Mirrors the semantics of the public intializer with the added benefit of /// injecting a custom date provider for improved testability. /// - Parameters: /// - id: The id to associate this controller's heartbeat storage with. /// - dateProvider: A date provider. convenience init(id: String, dateProvider: @escaping () -> Date) { let storage = HeartbeatStorage.getInstance(id: id) self.init(storage: storage, dateProvider: dateProvider) } /// Designated initializer. /// - Parameters: /// - storage: A heartbeat storage container. /// - dateProvider: A date provider. Defaults to providing the current date. init(storage: HeartbeatStorageProtocol, dateProvider: @escaping () -> Date = Date.init) { self.storage = storage self.dateProvider = { Self.dateStandardizer(dateProvider()) } } /// Asynchronously logs a new heartbeat, if needed. /// /// - Note: This API is thread-safe. /// - Parameter agent: The string agent (i.e. Firebase User Agent) to associate the logged heartbeat with. public func log(_ agent: String) { let date = dateProvider() storage.readAndWriteAsync { heartbeatsBundle in var heartbeatsBundle = heartbeatsBundle ?? HeartbeatsBundle(capacity: self.heartbeatsStorageCapacity) // Filter for the time periods where the last heartbeat to be logged for // that time period was logged more than one time period (i.e. day) ago. let timePeriods = heartbeatsBundle.lastAddedHeartbeatDates.filter { timePeriod, lastDate in date.timeIntervalSince(lastDate) >= timePeriod.timeInterval } .map { timePeriod, _ in timePeriod } if !timePeriods.isEmpty { // A heartbeat should only be logged if there is a time period(s) to // associate it with. let heartbeat = Heartbeat(agent: agent, date: date, timePeriods: timePeriods) heartbeatsBundle.append(heartbeat) } return heartbeatsBundle } } /// Synchronously flushes heartbeats from storage into a heartbeats payload. /// /// - Note: This API is thread-safe. /// - Returns: The flushed heartbeats in the form of `HeartbeatsPayload`. @discardableResult public func flush() -> HeartbeatsPayload { let resetTransform = { (heartbeatsBundle: HeartbeatsBundle?) -> HeartbeatsBundle? in guard let oldHeartbeatsBundle = heartbeatsBundle else { return nil // Storage was empty. } // The new value that's stored will use the old's cache to prevent the // logging of duplicates after flushing. return HeartbeatsBundle( capacity: self.heartbeatsStorageCapacity, cache: oldHeartbeatsBundle.lastAddedHeartbeatDates ) } // Synchronously gets and returns the stored heartbeats, resetting storage // using the given transform. If the operation throws, assume no // heartbeat(s) were retrieved or set. if let heartbeatsBundle = try? storage.getAndSet(using: resetTransform) { return heartbeatsBundle.makeHeartbeatsPayload() } else { return HeartbeatsPayload.emptyPayload } } /// Synchronously flushes the heartbeat for today. /// /// If no heartbeat was logged today, the returned payload is empty. /// /// - Note: This API is thread-safe. /// - Returns: A heartbeats payload for the flushed heartbeat. @discardableResult public func flushHeartbeatFromToday() -> HeartbeatsPayload { let todaysDate = dateProvider() var todaysHeartbeat: Heartbeat? storage.readAndWriteSync { heartbeatsBundle in guard var heartbeatsBundle = heartbeatsBundle else { return nil // Storage was empty. } todaysHeartbeat = heartbeatsBundle.removeHeartbeat(from: todaysDate) return heartbeatsBundle } // Note that `todaysHeartbeat` is updated in the above read/write block. if todaysHeartbeat != nil { return todaysHeartbeat!.makeHeartbeatsPayload() } else { return HeartbeatsPayload.emptyPayload } } }
bsd-3-clause
e1193f71c4ccedc15f1ca3841345dd74
38.201389
108
0.707352
4.519616
false
false
false
false
mcomisso/ToDo-MVVM
todoMVVM/ViewModel.swift
1
3167
// // ViewModel.swift // todoMVVM // // Created by Matteo Comisso on 19/01/16. // Copyright © 2016 mcomisso. All rights reserved. // import Foundation import UIKit class ToDoViewModel: NSObject { var todoDataSource: Array<ToDo> var todoCompleted: Array<ToDo> let demo1 = ToDo(withContent: "First Todo") let demo2 = ToDo(withContent: "Second Todo") override init() { self.todoDataSource = [] self.todoCompleted = [] } /** Set a bunch of demo data */ func completeWithDemoData() { self.appendToDataSource(self.demo1) self.appendToDataSource(self.demo2) } /** Counts available items in DataSource - returns: Numbers of item available in DataSource */ func countAvailableTodos() -> Int { return self.todoDataSource.count } /** Create new todos - parameter content: The content string of newly created Todo */ func createNewTodo(content: String) { let newTodo = ToDo(withContent: content) self.appendToDataSource(newTodo) } /** Handle current completion status of todos - parameter todo: The item to handle */ func addCompletedTodo(todo: ToDo) { todo.completed = true self.appedToCompleted(todo) } /** Removes the Todo item from the completed array - parameter todo: The item to remove */ func removeCompletedTodo(todo: ToDo) { self.removeFromCompleted(todo) } /** Removes all completed Todos */ func clearCompletedTodo() { for todo in self.todoCompleted { guard let index = self.todoDataSource.indexOf(todo) else { continue } self.todoDataSource.removeAtIndex(index) } self.todoCompleted.removeAll() } func isCompleted(todo: ToDo) -> Bool { return self.todoCompleted.contains(todo) } func handleTodoAtIndexPath(indexPath: NSIndexPath) { let todo = self.todoDataSource[indexPath.row] todo.completed ? self.removeCompletedTodo(todo) : self.addCompletedTodo(todo) } // Deletion func deleteTodoItem(todo: ToDo) { self.removeFromDataSource(todo) self.removeFromCompleted(todo) } } extension ToDoViewModel { func todoAtIndex(index: Int) -> ToDo? { return self.todoDataSource[index] } private func appedToCompleted(todo: ToDo) { self.todoCompleted.append(todo) } private func appendToDataSource(todo: ToDo) { self.todoDataSource.append(todo) } private func removeFromDataSource(todo: ToDo) { guard let index = self.todoDataSource.indexOf(todo) else { return } self.todoDataSource.removeAtIndex(index) } private func removeFromCompleted(todo: ToDo) { defer { todo.completed = false } guard let index = self.todoCompleted.indexOf(todo) else { return } self.todoCompleted.removeAtIndex(index) } }
mit
a93c67454c13b3f47dddcdc37365e3ce
22.992424
85
0.60518
4.503556
false
false
false
false
CoderST/DYZB
DYZB/DYZB/Class/Profile/ViewModel/ProfileViewModel.swift
1
6443
// // ProfileViewModel.swift // DYZB // // Created by xiudou on 2017/6/21. // Copyright © 2017年 xiudo. All rights reserved. // import UIKit fileprivate let ProfileCellIdentifier = "ProfileCellIdentifier" let profileHeadViewHeight : CGFloat = sScreenW * 5 / 6 class ProfileViewModel: NSObject,ViewModelProtocol { var user : User? // 本地cell数据数组 var groupDatas : [ProfileGroupModel] = [ProfileGroupModel]() // 获取最新请求时间 fileprivate lazy var baseViewModel : BaseViewModel = BaseViewModel() func loadProfileDatas(_ finishCallBack:@escaping ()->(), _ messageCallBack :@escaping (_ message : String)->(), _ failCallBack :@escaping ()->()){ let group = DispatchGroup() group.enter() // 第一组数据 let recruit = ProfileModel(imageName: "image_my_recruitment", titleName: "主播招募", subTitleName: "", targetClass: MyTaskViewController.self) let groupOne = ProfileGroupModel() groupOne.groupModels = [recruit] // 第二组数据 let myVideo = ProfileModel(imageName: "image_my_video_icon", titleName: "我的视频", subTitleName: "", targetClass: RecruitViewController.self) let videoCollect = ProfileModel(imageName: "image_my_video_collection", titleName: "视频收藏", subTitleName: "", targetClass: RecruitViewController.self) let groupTwo = ProfileGroupModel() groupTwo.groupModels = [myVideo,videoCollect] // 第三组数据 let myAccount = ProfileModel(imageName: "image_my_account", titleName: "我的账户", subTitleName: "", targetClass: MyAccountViewController.self) let platCenter = ProfileModel(imageName: "image_my_recommend", titleName: "游戏中心", subTitleName: "", targetClass: GameCenterViewController.self) let groupThree = ProfileGroupModel() groupThree.groupModels = [myAccount,platCenter] // 第四组数据 let remind = ProfileModel(imageName: "image_my_remind", titleName: "开播提醒", subTitleName: "", targetClass: RecruitViewController.self) let groupFour = ProfileGroupModel() groupFour.groupModels = [remind] groupDatas = [groupOne,groupTwo,groupThree,groupFour] group.leave() // let now = Date() // //当前时间的时间戳 // let timeInterval:TimeInterval = now.timeIntervalSince1970 // let timeStamp = Int(timeInterval) /* posid 800001 roomid 0 */ let params = ["token" : TOKEN] let URLString = String(format: "http://capi.douyucdn.cn/api/v1/my_info?aid=ios&client_sys=ios&time=%@&auth=%@", Date.getNowDate(),AUTH) group.enter() NetworkTools.requestData(.post, URLString: URLString, parameters: params) { (result) in guard let result = result as? [String : Any] else { failCallBack() return } guard let error = result["error"] as? Int else{ failCallBack() return } if error != 0 { group.leave() debugLog(result) failCallBack() return } guard let dict = result["data"] as? [String : Any] else { failCallBack() return } self.user = User(dict: dict) debugLog(dict) group.leave() finishCallBack() } } // MARK:- 绑定 func bindViewModel(bindView: UIView) { if bindView is UICollectionView{ let collectionView = bindView as! UICollectionView collectionView.dataSource = self collectionView.delegate = self // 注册cell collectionView.register(ProfileCell.self, forCellWithReuseIdentifier: ProfileCellIdentifier) } } } extension ProfileViewModel : UICollectionViewDataSource { func numberOfSections(in collectionView: UICollectionView) -> Int{ return groupDatas.count } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int{ let group = groupDatas[section] return group.groupModels.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell{ let cell = collectionView.dequeueReusableCell(withReuseIdentifier: ProfileCellIdentifier, for: indexPath) as! ProfileCell let group = groupDatas[indexPath.section] let profileModel = group.groupModels[indexPath.item] cell.profileModel = profileModel return cell } } extension ProfileViewModel : UICollectionViewDelegateFlowLayout { func scrollViewDidScroll(_ scrollView: UIScrollView) { debugLog(scrollView.contentOffset.y) // 禁止下拉 if scrollView.contentOffset.y <= -profileHeadViewHeight { scrollView.contentOffset.y = -profileHeadViewHeight } } func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { let group = groupDatas[indexPath.section] let profileModel = group.groupModels[indexPath.item] if let desVC = profileModel.targetClass as? UIViewController.Type { let vc = desVC.init() if vc is MyTaskViewController { let desvc = vc as!MyTaskViewController // 获取时间 baseViewModel.updateDate { guard let time = userDefaults.object(forKey: dateKey) as? Int else { return } let url = "http://www.douyu.com/h5mobile/welcome/jump/5?aid=ios&client_sys=ios&time=\(time)&token=\(TOKEN)&auth=\(AUTH)" desvc.open_url = url getNavigation().pushViewController(vc, animated: true) } }else{ getNavigation().pushViewController(vc, animated: true) } } } // 组间距 func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets{ return UIEdgeInsets(top: 0, left: 0, bottom: 10, right: 0) } }
mit
a46271d91cd9acba912125de0ed30fd0
37.280488
161
0.616279
4.935535
false
false
false
false
benlangmuir/swift
test/refactoring/ConvertAsync/basic.swift
7
44523
// REQUIRES: concurrency // RUN: %empty-directory(%t) enum CustomError: Error { case invalid case insecure } typealias SomeCallback = (String) -> Void typealias SomeResultCallback = (Result<String, CustomError>) -> Void typealias NestedAliasCallback = SomeCallback // 1. Check various functions for having/not having async alternatives // RUN: %refactor-check-compiles -add-async-alternative -dump-text -source-filename %s -pos=%(line+4):1 | %FileCheck -check-prefix=ASYNC-SIMPLE %s // RUN: %refactor-check-compiles -add-async-alternative -dump-text -source-filename %s -pos=%(line+3):6 | %FileCheck -check-prefix=ASYNC-SIMPLE %s // RUN: %refactor-check-compiles -add-async-alternative -dump-text -source-filename %s -pos=%(line+2):12 | %FileCheck -check-prefix=ASYNC-SIMPLE %s // RUN: %refactor-check-compiles -add-async-alternative -dump-text -source-filename %s -pos=%(line+1):20 | %FileCheck -check-prefix=ASYNC-SIMPLE %s func simple(/*cs*/ completion: @escaping (String) -> Void /*ce*/) { } // ASYNC-SIMPLE: basic.swift [[# @LINE-1]]:1 -> [[# @LINE-1]]:1 // ASYNC-SIMPLE-NEXT: @available(*, renamed: "simple()") // ASYNC-SIMPLE-EMPTY: // ASYNC-SIMPLE-NEXT: basic.swift [[# @LINE-4]]:67 -> [[# @LINE-4]]:70 // ASYNC-SIMPLE-NEXT: { // ASYNC-SIMPLE-NEXT: Task { // ASYNC-SIMPLE-NEXT: let result = await simple() // ASYNC-SIMPLE-NEXT: completion(result) // ASYNC-SIMPLE-NEXT: } // ASYNC-SIMPLE-NEXT: } // ASYNC-SIMPLE-EMPTY: // ASYNC-SIMPLE-NEXT: basic.swift [[# @LINE-12]]:70 -> [[# @LINE-12]]:70 // ASYNC-SIMPLE-EMPTY: // ASYNC-SIMPLE-EMPTY: // ASYNC-SIMPLE-EMPTY: // ASYNC-SIMPLE-NEXT: basic.swift [[# @LINE-16]]:70 -> [[# @LINE-16]]:70 // ASYNC-SIMPLE-NEXT: func simple() async -> String { } // RUN: %refactor-check-compiles -add-async-alternative -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=ASYNC-SIMPLENOLABEL %s func simpleWithoutLabel(_ completion: @escaping (String) -> Void) { } // ASYNC-SIMPLENOLABEL: { // ASYNC-SIMPLENOLABEL-NEXT: Task { // ASYNC-SIMPLENOLABEL-NEXT: let result = await simpleWithoutLabel() // ASYNC-SIMPLENOLABEL-NEXT: completion(result) // ASYNC-SIMPLENOLABEL-NEXT: } // ASYNC-SIMPLENOLABEL-NEXT: } // ASYNC-SIMPLENOLABEL: func simpleWithoutLabel() async -> String { } // RUN: %refactor-check-compiles -add-async-alternative -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=ASYNC-SIMPLEWITHARG %s func simpleWithArg(/*c1s*/ a: Int /*c1e*/, /*c2s*/ completion: @escaping (String) -> Void /*c2e*/) { } // ASYNC-SIMPLEWITHARG: { // ASYNC-SIMPLEWITHARG-NEXT: Task { // ASYNC-SIMPLEWITHARG-NEXT: let result = await simpleWithArg(a: a) // ASYNC-SIMPLEWITHARG-NEXT: completion(result) // ASYNC-SIMPLEWITHARG-NEXT: } // ASYNC-SIMPLEWITHARG-NEXT: } // ASYNC-SIMPLEWITHARG: func simpleWithArg(/*c1s*/ a: Int /*c1e*/) async -> String { } // RUN: %refactor-check-compiles -add-async-alternative -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=ASYNC-MULTIPLERESULTS %s func multipleResults(completion: @escaping (String, Int) -> Void) { } // ASYNC-MULTIPLERESULTS: { // ASYNC-MULTIPLERESULTS-NEXT: Task { // ASYNC-MULTIPLERESULTS-NEXT: let result = await multipleResults() // ASYNC-MULTIPLERESULTS-NEXT: completion(result.0, result.1) // ASYNC-MULTIPLERESULTS-NEXT: } // ASYNC-MULTIPLERESULTS-NEXT: } // ASYNC-MULTIPLERESULTS: func multipleResults() async -> (String, Int) { } // RUN: %refactor-check-compiles -add-async-alternative -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=ASYNC-NONOPTIONALERROR %s func nonOptionalError(completion: @escaping (String, Error) -> Void) { } // ASYNC-NONOPTIONALERROR: { // ASYNC-NONOPTIONALERROR-NEXT: Task { // ASYNC-NONOPTIONALERROR-NEXT: let result = await nonOptionalError() // ASYNC-NONOPTIONALERROR-NEXT: completion(result.0, result.1) // ASYNC-NONOPTIONALERROR-NEXT: } // ASYNC-NONOPTIONALERROR-NEXT: } // ASYNC-NONOPTIONALERROR: func nonOptionalError() async -> (String, Error) { } // RUN: %refactor-check-compiles -add-async-alternative -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=ASYNC-NOPARAMS %s func noParams(completion: @escaping () -> Void) { } // ASYNC-NOPARAMS: { // ASYNC-NOPARAMS-NEXT: Task { // ASYNC-NOPARAMS-NEXT: await noParams() // ASYNC-NOPARAMS-NEXT: completion() // ASYNC-NOPARAMS-NEXT: } // ASYNC-NOPARAMS-NEXT: } // ASYNC-NOPARAMS: func noParams() async { } // RUN: %refactor-check-compiles -add-async-alternative -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=ASYNC-ERROR %s func error(completion: @escaping (String?, Error?) -> Void) { } // ASYNC-ERROR: { // ASYNC-ERROR-NEXT: Task { // ASYNC-ERROR-NEXT: do { // ASYNC-ERROR-NEXT: let result = try await error() // ASYNC-ERROR-NEXT: completion(result, nil) // ASYNC-ERROR-NEXT: } catch { // ASYNC-ERROR-NEXT: completion(nil, error) // ASYNC-ERROR-NEXT: } // ASYNC-ERROR-NEXT: } // ASYNC-ERROR: func error() async throws -> String { } // RUN: %refactor-check-compiles -add-async-alternative -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=ASYNC-ERRORONLY %s func errorOnly(completion: @escaping (Error?) -> Void) { } // ASYNC-ERRORONLY: { // ASYNC-ERRORONLY-NEXT: Task { // ASYNC-ERRORONLY-NEXT: do { // ASYNC-ERRORONLY-NEXT: try await errorOnly() // ASYNC-ERRORONLY-NEXT: completion(nil) // ASYNC-ERRORONLY-NEXT: } catch { // ASYNC-ERRORONLY-NEXT: completion(error) // ASYNC-ERRORONLY-NEXT: } // ASYNC-ERRORONLY-NEXT: } // ASYNC-ERRORONLY-NEXT: } // ASYNC-ERRORONLY: func errorOnly() async throws { } // RUN: %refactor-check-compiles -add-async-alternative -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=ASYNC-ERRORNONOPTIONALRESULT %s func errorNonOptionalResult(completion: @escaping (String, Error?) -> Void) { } // ASYNC-ERRORNONOPTIONALRESULT: { // ASYNC-ERRORNONOPTIONALRESULT-NEXT: Task { // ASYNC-ERRORNONOPTIONALRESULT-NEXT: do { // ASYNC-ERRORNONOPTIONALRESULT-NEXT: let result = try await errorNonOptionalResult() // ASYNC-ERRORNONOPTIONALRESULT-NEXT: completion(result, nil) // ASYNC-ERRORNONOPTIONALRESULT-NEXT: } catch { // ASYNC-ERRORNONOPTIONALRESULT-NEXT: completion(<#String#>, error) // ASYNC-ERRORNONOPTIONALRESULT-NEXT: } // ASYNC-ERRORNONOPTIONALRESULT-NEXT: } // ASYNC-ERRORNONOPTIONALRESULT-NEXT: } // ASYNC-ERRORNONOPTIONALRESULT: func errorNonOptionalResult() async throws -> String { } // RUN: %refactor-check-compiles -add-async-alternative -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=ASYNC-CUSTOMERROR %s func customError(completion: @escaping (String?, CustomError?) -> Void) { } // ASYNC-CUSTOMERROR: { // ASYNC-CUSTOMERROR-NEXT: Task { // ASYNC-CUSTOMERROR-NEXT: do { // ASYNC-CUSTOMERROR-NEXT: let result = try await customError() // ASYNC-CUSTOMERROR-NEXT: completion(result, nil) // ASYNC-CUSTOMERROR-NEXT: } catch { // ASYNC-CUSTOMERROR-NEXT: completion(nil, (error as! CustomError)) // ASYNC-CUSTOMERROR-NEXT: } // ASYNC-CUSTOMERROR-NEXT: } // ASYNC-CUSTOMERROR-NEXT: } // ASYNC-CUSTOMERROR: func customError() async throws -> String { } // RUN: %refactor-check-compiles -add-async-alternative -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=ASYNC-ALIAS %s func alias(completion: @escaping SomeCallback) { } // ASYNC-ALIAS: { // ASYNC-ALIAS-NEXT: Task { // ASYNC-ALIAS-NEXT: let result = await alias() // ASYNC-ALIAS-NEXT: completion(result) // ASYNC-ALIAS-NEXT: } // ASYNC-ALIAS-NEXT: } // ASYNC-ALIAS: func alias() async -> String { } // RUN: %refactor-check-compiles -add-async-alternative -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=ASYNC-NESTEDALIAS %s func nestedAlias(completion: @escaping NestedAliasCallback) { } // ASYNC-NESTEDALIAS: { // ASYNC-NESTEDALIAS-NEXT: Task { // ASYNC-NESTEDALIAS-NEXT: let result = await nestedAlias() // ASYNC-NESTEDALIAS-NEXT: completion(result) // ASYNC-NESTEDALIAS-NEXT: } // ASYNC-NESTEDALIAS-NEXT: } // ASYNC-NESTEDALIAS: func nestedAlias() async -> String { } // RUN: %refactor-check-compiles -add-async-alternative -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=ASYNC-SIMPLERESULT %s func simpleResult(completion: @escaping (Result<String, Never>) -> Void) { } // ASYNC-SIMPLERESULT: { // ASYNC-SIMPLERESULT-NEXT: Task { // ASYNC-SIMPLERESULT-NEXT: let result = await simpleResult() // ASYNC-SIMPLERESULT-NEXT: completion(.success(result)) // ASYNC-SIMPLERESULT-NEXT: } // ASYNC-SIMPLERESULT-NEXT: } // ASYNC-SIMPLERESULT: func simpleResult() async -> String { } // RUN: %refactor-check-compiles -add-async-alternative -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=ASYNC-ERRORRESULT %s func errorResult(completion: @escaping (Result<String, Error>) -> Void) { } // ASYNC-ERRORRESULT: { // ASYNC-ERRORRESULT-NEXT: Task { // ASYNC-ERRORRESULT-NEXT: do { // ASYNC-ERRORRESULT-NEXT: let result = try await errorResult() // ASYNC-ERRORRESULT-NEXT: completion(.success(result)) // ASYNC-ERRORRESULT-NEXT: } catch { // ASYNC-ERRORRESULT-NEXT: completion(.failure(error)) // ASYNC-ERRORRESULT-NEXT: } // ASYNC-ERRORRESULT-NEXT: } // ASYNC-ERRORRESULT-NEXT: } // ASYNC-ERRORRESULT: func errorResult() async throws -> String { } // RUN: %refactor-check-compiles -add-async-alternative -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=ASYNC-CUSTOMERRORRESULT %s func customErrorResult(completion: @escaping (Result<String, CustomError>) -> Void) { } // ASYNC-CUSTOMERRORRESULT: { // ASYNC-CUSTOMERRORRESULT-NEXT: Task { // ASYNC-CUSTOMERRORRESULT-NEXT: do { // ASYNC-CUSTOMERRORRESULT-NEXT: let result = try await customErrorResult() // ASYNC-CUSTOMERRORRESULT-NEXT: completion(.success(result)) // ASYNC-CUSTOMERRORRESULT-NEXT: } catch { // ASYNC-CUSTOMERRORRESULT-NEXT: completion(.failure(error as! CustomError)) // ASYNC-CUSTOMERRORRESULT-NEXT: } // ASYNC-CUSTOMERRORRESULT-NEXT: } // ASYNC-CUSTOMERRORRESULT-NEXT: } // ASYNC-CUSTOMERRORRESULT: func customErrorResult() async throws -> String { } // RUN: %refactor-check-compiles -add-async-alternative -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=ASYNC-ALIASRESULT %s func aliasedResult(completion: @escaping SomeResultCallback) { } // ASYNC-ALIASRESULT: { // ASYNC-ALIASRESULT-NEXT: Task { // ASYNC-ALIASRESULT-NEXT: do { // ASYNC-ALIASRESULT-NEXT: let result = try await aliasedResult() // ASYNC-ALIASRESULT-NEXT: completion(.success(result)) // ASYNC-ALIASRESULT-NEXT: } catch { // ASYNC-ALIASRESULT-NEXT: completion(.failure(error as! CustomError)) // ASYNC-ALIASRESULT-NEXT: } // ASYNC-ALIASRESULT-NEXT: } // ASYNC-ALIASRESULT-NEXT: } // ASYNC-ALIASRESULT: func aliasedResult() async throws -> String { } // RUN: %refactor-check-compiles -add-async-alternative -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=MANY %s func many(_ completion: @escaping (String, Int) -> Void) { } // MANY: { // MANY-NEXT: Task { // MANY-NEXT: let result = await many() // MANY-NEXT: completion(result.0, result.1) // MANY-NEXT: } // MANY-NEXT: } // MANY: func many() async -> (String, Int) { } // RUN: %refactor-check-compiles -add-async-alternative -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=OPTIONAL-SINGLE %s func optionalSingle(completion: @escaping (String?) -> Void) { } // OPTIONAL-SINGLE: { // OPTIONAL-SINGLE-NEXT: Task { // OPTIONAL-SINGLE-NEXT: let result = await optionalSingle() // OPTIONAL-SINGLE-NEXT: completion(result) // OPTIONAL-SINGLE-NEXT: } // OPTIONAL-SINGLE-NEXT: } // OPTIONAL-SINGLE: func optionalSingle() async -> String? { } // RUN: %refactor-check-compiles -add-async-alternative -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=MANY-OPTIONAL %s func manyOptional(_ completion: @escaping (String?, Int?) -> Void) { } // MANY-OPTIONAL: { // MANY-OPTIONAL-NEXT: Task { // MANY-OPTIONAL-NEXT: let result = await manyOptional() // MANY-OPTIONAL-NEXT: completion(result.0, result.1) // MANY-OPTIONAL-NEXT: } // MANY-OPTIONAL-NEXT: } // MANY-OPTIONAL: func manyOptional() async -> (String?, Int?) { } // RUN: %refactor-check-compiles -add-async-alternative -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=MIXED %s func mixed(_ completion: @escaping (String?, Int) -> Void) { } // MIXED: { // MIXED-NEXT: Task { // MIXED-NEXT: let result = await mixed() // MIXED-NEXT: completion(result.0, result.1) // MIXED-NEXT: } // MIXED-NEXT: } // MIXED: func mixed() async -> (String?, Int) { } // RUN: %refactor-check-compiles -add-async-alternative -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=MIXED-OPTIONAL-ERROR %s func mixedOptionalError(_ completion: @escaping (String?, Int, Error?) -> Void) { } // MIXED-OPTIONAL-ERROR: { // MIXED-OPTIONAL-ERROR-NEXT: Task { // MIXED-OPTIONAL-ERROR-NEXT: do { // MIXED-OPTIONAL-ERROR-NEXT: let result = try await mixedOptionalError() // MIXED-OPTIONAL-ERROR-NEXT: completion(result.0, result.1, nil) // MIXED-OPTIONAL-ERROR-NEXT: } catch { // MIXED-OPTIONAL-ERROR-NEXT: completion(nil, <#Int#>, error) // MIXED-OPTIONAL-ERROR-NEXT: } // MIXED-OPTIONAL-ERROR-NEXT: } // MIXED-OPTIONAL-ERROR-NEXT: } // MIXED-OPTIONAL-ERROR: func mixedOptionalError() async throws -> (String, Int) { } // RUN: %refactor-check-compiles -add-async-alternative -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=MIXED-ERROR %s func mixedError(_ completion: @escaping (String?, Int, Error) -> Void) { } // MIXED-ERROR: { // MIXED-ERROR-NEXT: Task { // MIXED-ERROR-NEXT: let result = await mixedError() // MIXED-ERROR-NEXT: completion(result.0, result.1, result.2) // MIXED-ERROR-NEXT: } // MIXED-ERROR-NEXT: } // MIXED-ERROR: func mixedError() async -> (String?, Int, Error) { } // RUN: %refactor-check-compiles -add-async-alternative -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=GENERIC %s func generic<T, R>(completion: @escaping (T, R) -> Void) { } // GENERIC: { // GENERIC-NEXT: Task { // GENERIC-NEXT: let result: (T, R) = await generic() // GENERIC-NEXT: completion(result.0, result.1) // GENERIC-NEXT: } // GENERIC-NEXT: } // GENERIC: func generic<T, R>() async -> (T, R) { } // RUN: %refactor-check-compiles -add-async-alternative -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=GENERIC-RESULT %s func genericResult<T>(completion: @escaping (T?, Error?) -> Void) where T: Numeric { } // GENERIC-RESULT: { // GENERIC-RESULT-NEXT: Task { // GENERIC-RESULT-NEXT: do { // GENERIC-RESULT-NEXT: let result: T = try await genericResult() // GENERIC-RESULT-NEXT: completion(result, nil) // GENERIC-RESULT-NEXT: } catch { // GENERIC-RESULT-NEXT: completion(nil, error) // GENERIC-RESULT-NEXT: } // GENERIC-RESULT-NEXT: } // GENERIC-RESULT-NEXT: } // GENERIC-RESULT: func genericResult<T>() async throws -> T where T: Numeric { } // FIXME: This doesn't compile after refactoring because we aren't using the generic argument `E` in the async method (SR-14560) // RUN: %refactor -add-async-alternative -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=GENERIC-ERROR %s func genericError<E>(completion: @escaping (String?, E?) -> Void) where E: Error { } // GENERIC-ERROR: { // GENERIC-ERROR-NEXT: Task { // GENERIC-ERROR-NEXT: do { // GENERIC-ERROR-NEXT: let result: String = try await genericError() // GENERIC-ERROR-NEXT: completion(result, nil) // GENERIC-ERROR-NEXT: } catch { // GENERIC-ERROR-NEXT: completion(nil, (error as! E)) // GENERIC-ERROR-NEXT: } // GENERIC-ERROR-NEXT: } // GENERIC-ERROR-NEXT: } // GENERIC-ERROR: func genericError<E>() async throws -> String where E: Error { } // RUN: %refactor-check-compiles -add-async-alternative -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=OTHER-NAME %s func otherName(execute: @escaping (String) -> Void) { } // OTHER-NAME: { // OTHER-NAME-NEXT: Task { // OTHER-NAME-NEXT: let result = await otherName() // OTHER-NAME-NEXT: execute(result) // OTHER-NAME-NEXT: } // OTHER-NAME-NEXT: } // OTHER-NAME: func otherName() async -> String { } // RUN: %refactor-check-compiles -add-async-alternative -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=DEFAULT_ARGS %s func defaultArgs(a: Int, b: Int = 10, completion: @escaping (String) -> Void) { } // DEFAULT_ARGS: { // DEFAULT_ARGS-NEXT: Task { // DEFAULT_ARGS-NEXT: let result = await defaultArgs(a: a, b: b) // DEFAULT_ARGS-NEXT: completion(result) // DEFAULT_ARGS-NEXT: } // DEFAULT_ARGS-NEXT: } // DEFAULT_ARGS: func defaultArgs(a: Int, b: Int = 10) async -> String { } struct MyStruct { var someVar: (Int) -> Void { get { return {_ in } } // RUN: not %refactor -add-async-alternative -dump-text -source-filename %s -pos=%(line+1):5 set (completion) { } } init() { } // RUN: not %refactor -add-async-alternative -dump-text -source-filename %s -pos=%(line+1):3 init(completion: @escaping (String) -> Void) { } func retSelf() -> MyStruct { return self } // RUN: %refactor-check-compiles -add-async-alternative -dump-text -source-filename %s -pos=%(line+1):10 | %FileCheck -check-prefix=MODIFIERS %s public func publicMember(completion: @escaping (String) -> Void) { } // MODIFIERS: public func publicMember() async -> String { } // RUN: %refactor-check-compiles -add-async-alternative -dump-text -source-filename %s -pos=%(line+1):3 | %FileCheck -check-prefix=STATIC %s static func staticMember(completion: @escaping (String) -> Void) { } // STATIC: static func staticMember() async -> String { } // RUN: %refactor-check-compiles -add-async-alternative -dump-text -source-filename %s -pos=%(line+2):11 | %FileCheck -check-prefix=DEPRECATED %s @available(*, deprecated, message: "Deprecated") private func deprecated(completion: @escaping (String) -> Void) { } // DEPRECATED: @available(*, deprecated, message: "Deprecated") // DEPRECATED-NEXT: private func deprecated() async -> String { } } func retStruct() -> MyStruct { return MyStruct() } protocol MyProtocol { // RUN: %refactor-check-compiles -add-async-alternative -dump-text -source-filename %s -pos=%(line+2):3 | %FileCheck -check-prefix=PROTO-MEMBER %s // RUN: %refactor-check-compiles -convert-to-async -dump-text -source-filename %s -pos=%(line+1):3 | %FileCheck -check-prefix=PROTO-MEMBER %s func protoMember(completion: @escaping (String) -> Void) // PROTO-MEMBER: func protoMember() async -> String{{$}} } // RUN: not %refactor -add-async-alternative -dump-text -source-filename %s -pos=%(line+2):1 // RUN: %refactor-check-compiles -convert-to-async -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=NON-COMPLETION %s func nonCompletion(a: Int) { } // NON-COMPLETION: func nonCompletion(a: Int) async { } // RUN: not %refactor -add-async-alternative -dump-text -source-filename %s -pos=%(line+2):1 // RUN: %refactor -convert-to-async -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=NON-ESCAPING-COMPLETION %s func nonEscapingCompletion(completion: (Int) -> Void) { } // NON-ESCAPING-COMPLETION: func nonEscapingCompletion(completion: (Int) -> Void) async { } // RUN: not %refactor -add-async-alternative -dump-text -source-filename %s -pos=%(line+2):1 // RUN: %refactor-check-compiles -convert-to-async -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=MULTIPLE-RESULTS %s func multipleResults(completion: @escaping (Result<String, Error>, Result<String, Error>) -> Void) { } // MULTIPLE-RESULTS: func multipleResults(completion: @escaping (Result<String, Error>, Result<String, Error>) -> Void) async { } // RUN: not %refactor -add-async-alternative -dump-text -source-filename %s -pos=%(line+2):1 // RUN: %refactor-check-compiles -convert-to-async -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=NON-VOID %s func nonVoid(completion: @escaping (String) -> Void) -> Int { return 0 } // NON-VOID: func nonVoid(completion: @escaping (String) -> Void) async -> Int { return 0 } // RUN: not %refactor -add-async-alternative -dump-text -source-filename %s -pos=%(line+2):1 // RUN: %refactor-check-compiles -convert-to-async -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=COMPLETION-NON-VOID %s func completionNonVoid(completion: @escaping (String) -> Int) -> Void { } // COMPLETION-NON-VOID: func completionNonVoid(completion: @escaping (String) -> Int) async -> Void { } // RUN: not %refactor -add-async-alternative -dump-text -source-filename %s -pos=%(line+2):1 // RUN: %refactor-check-compiles -convert-to-async -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=ALREADY-THROWS %s func alreadyThrows(completion: @escaping (String) -> Void) throws { } // ALREADY-THROWS: func alreadyThrows(completion: @escaping (String) -> Void) async throws { } // RUN: not %refactor -add-async-alternative -dump-text -source-filename %s -pos=%(line+2):1 // RUN: %refactor-check-compiles -convert-to-async -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=AUTO-CLOSURE %s func noParamAutoclosure(completion: @escaping @autoclosure () -> Void) { } // AUTO-CLOSURE: func noParamAutoclosure(completion: @escaping @autoclosure () -> Void) async { } // RUN: %refactor-check-compiles -add-async-alternative -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix BLOCK-CONVENTION %s func blockConvention(completion: @escaping @convention(block) () -> Void) { } // BLOCK-CONVENTION: func blockConvention() async { } // RUN: %refactor-check-compiles -add-async-alternative -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix C-CONVENTION %s func cConvention(completion: @escaping @convention(c) () -> Void) { } // C-CONVENTION: func cConvention() async { } // RUN: %refactor-check-compiles -add-async-alternative -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix OPT-VOID-AND-ERROR-HANDLER %s func optVoidAndErrorCompletion(completion: @escaping (Void?, Error?) -> Void) {} // OPT-VOID-AND-ERROR-HANDLER: { // OPT-VOID-AND-ERROR-HANDLER-NEXT: Task { // OPT-VOID-AND-ERROR-HANDLER-NEXT: do { // OPT-VOID-AND-ERROR-HANDLER-NEXT: try await optVoidAndErrorCompletion() // OPT-VOID-AND-ERROR-HANDLER-NEXT: completion((), nil) // OPT-VOID-AND-ERROR-HANDLER-NEXT: } catch { // OPT-VOID-AND-ERROR-HANDLER-NEXT: completion(nil, error) // OPT-VOID-AND-ERROR-HANDLER-NEXT: } // OPT-VOID-AND-ERROR-HANDLER-NEXT: } // OPT-VOID-AND-ERROR-HANDLER-NEXT: } // OPT-VOID-AND-ERROR-HANDLER: func optVoidAndErrorCompletion() async throws {} // RUN: %refactor-check-compiles -add-async-alternative -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix TOO-MUCH-VOID-AND-ERROR-HANDLER %s func tooMuchVoidAndErrorCompletion(completion: @escaping (Void?, Void?, Error?) -> Void) {} // TOO-MUCH-VOID-AND-ERROR-HANDLER: { // TOO-MUCH-VOID-AND-ERROR-HANDLER-NEXT: Task { // TOO-MUCH-VOID-AND-ERROR-HANDLER-NEXT: do { // TOO-MUCH-VOID-AND-ERROR-HANDLER-NEXT: try await tooMuchVoidAndErrorCompletion() // TOO-MUCH-VOID-AND-ERROR-HANDLER-NEXT: completion((), (), nil) // TOO-MUCH-VOID-AND-ERROR-HANDLER-NEXT: } catch { // TOO-MUCH-VOID-AND-ERROR-HANDLER-NEXT: completion(nil, nil, error) // TOO-MUCH-VOID-AND-ERROR-HANDLER-NEXT: } // TOO-MUCH-VOID-AND-ERROR-HANDLER-NEXT: } // TOO-MUCH-VOID-AND-ERROR-HANDLER-NEXT: } // TOO-MUCH-VOID-AND-ERROR-HANDLER: func tooMuchVoidAndErrorCompletion() async throws {} // RUN: %refactor-check-compiles -add-async-alternative -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix VOID-PROPER-AND-ERROR-HANDLER %s func tooVoidProperAndErrorCompletion(completion: @escaping (Void?, String?, Error?) -> Void) {} // VOID-PROPER-AND-ERROR-HANDLER: { // VOID-PROPER-AND-ERROR-HANDLER-NEXT: Task { // VOID-PROPER-AND-ERROR-HANDLER-NEXT: do { // VOID-PROPER-AND-ERROR-HANDLER-NEXT: let result = try await tooVoidProperAndErrorCompletion() // VOID-PROPER-AND-ERROR-HANDLER-NEXT: completion((), result.1, nil) // VOID-PROPER-AND-ERROR-HANDLER-NEXT: } catch { // VOID-PROPER-AND-ERROR-HANDLER-NEXT: completion(nil, nil, error) // VOID-PROPER-AND-ERROR-HANDLER-NEXT: } // VOID-PROPER-AND-ERROR-HANDLER-NEXT: } // VOID-PROPER-AND-ERROR-HANDLER-NEXT: } // VOID-PROPER-AND-ERROR-HANDLER: func tooVoidProperAndErrorCompletion() async throws -> (Void, String) {} // RUN: %refactor-check-compiles -add-async-alternative -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix VOID-AND-ERROR-HANDLER %s func voidAndErrorCompletion(completion: @escaping (Void, Error?) -> Void) {} // VOID-AND-ERROR-HANDLER: { // VOID-AND-ERROR-HANDLER-NEXT: Task { // VOID-AND-ERROR-HANDLER-NEXT: do { // VOID-AND-ERROR-HANDLER-NEXT: try await voidAndErrorCompletion() // VOID-AND-ERROR-HANDLER-NEXT: completion((), nil) // VOID-AND-ERROR-HANDLER-NEXT: } catch { // VOID-AND-ERROR-HANDLER-NEXT: completion((), error) // VOID-AND-ERROR-HANDLER-NEXT: } // VOID-AND-ERROR-HANDLER-NEXT: } // VOID-AND-ERROR-HANDLER-NEXT: } // VOID-AND-ERROR-HANDLER: func voidAndErrorCompletion() async throws {} // RUN: %refactor-check-compiles -add-async-alternative -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix VOID-RESULT-HANDLER %s func voidResultCompletion(completion: @escaping (Result<Void, Error>) -> Void) {} // VOID-RESULT-HANDLER: { // VOID-RESULT-HANDLER-NEXT: Task { // VOID-RESULT-HANDLER-NEXT: do { // VOID-RESULT-HANDLER-NEXT: try await voidResultCompletion() // VOID-RESULT-HANDLER-NEXT: completion(.success(())) // VOID-RESULT-HANDLER-NEXT: } catch { // VOID-RESULT-HANDLER-NEXT: completion(.failure(error)) // VOID-RESULT-HANDLER-NEXT: } // VOID-RESULT-HANDLER-NEXT: } // VOID-RESULT-HANDLER-NEXT: } // VOID-RESULT-HANDLER: func voidResultCompletion() async throws { // 2. Check that the various ways to call a function (and the positions the // refactoring is called from) are handled correctly class MyClass {} func simpleClassParam(completion: @escaping (MyClass) -> Void) { } // TODO: We cannot check that the refactored code compiles because 'simple' and // friends aren't refactored when only invoking the refactoring on this function. // TODO: When changing this line to %refactor-check-compiles, 'swift-refactor' // is crashing in '-dump-rewritten'. This is because // 'swift-refactor -dump-rewritten' is removing 'RUN' lines. After removing // those lines, we are trying to remove the function body, using its length // before the 'RUN' lines were removed, thus pointing past the end of the // rewritten buffer. // RUN: %refactor -convert-to-async -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=CALL %s func testSimple() { // RUN: %refactor -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+4):3 | %FileCheck -check-prefix=CALL %s // RUN: not %refactor -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+3):10 // RUN: not %refactor -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+2):24 // RUN: not %refactor -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+1):28 simple(completion: { str in // RUN: not %refactor -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+1):5 print("with label") }) } // CALL: let str = await simple(){{$}} // CALL-NEXT: // // CALL-NEXT: {{^}} print("with label") // RUN: %refactor -convert-to-async -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=CALL-NOLABEL %s func testSimpleWithoutLabel() { // RUN: %refactor -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+1):3 | %FileCheck -check-prefix=CALL-NOLABEL %s simpleWithoutLabel({ str in print("without label") }) } // CALL-NOLABEL: let str = await simpleWithoutLabel(){{$}} // CALL-NOLABEL-NEXT: {{^}}print("without label") // RUN: %refactor -convert-to-async -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=CALL-WRAPPED %s func testWrapped() { // RUN: %refactor -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+2):3 | %FileCheck -check-prefix=CALL-WRAPPED %s // RUN: %refactor -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+1):5 | %FileCheck -check-prefix=CALL-WRAPPED %s ((simple))(completion: { str in print("wrapped call") }) } // CALL-WRAPPED: let str = await ((simple))(){{$}} // CALL-WRAPPED-NEXT: {{^}}print("wrapped call") // RUN: %refactor -convert-to-async -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=TRAILING %s func testTrailing() { // RUN: %refactor -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+2):3 | %FileCheck -check-prefix=TRAILING %s // RUN: not %refactor -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+1):12 simple { str in print("trailing") } } // TRAILING: let str = await simple(){{$}} // TRAILING-NEXT: {{^}}print("trailing") // RUN: %refactor -convert-to-async -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=TRAILING-PARENS %s func testTrailingParens() { // RUN: %refactor -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+1):3 | %FileCheck -check-prefix=TRAILING-PARENS %s simple() { str in print("trailing with parens") } } // TRAILING-PARENS: let str = await simple(){{$}} // TRAILING-PARENS-NEXT: {{^}}print("trailing with parens") // RUN: %refactor -convert-to-async -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefixes=TRAILING-WRAPPED %s func testTrailingWrapped() { // RUN: %refactor -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+1):5 | %FileCheck -check-prefix=TRAILING-WRAPPED %s ((simple)) { str in print("trailing with wrapped call") } } // TRAILING-WRAPPED: let str = await ((simple))(){{$}} // TRAILING-WRAPPED-NEXT: {{^}}print("trailing with wrapped call") // RUN: %refactor -convert-to-async -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=CALL-ARG %s func testCallArg() { // RUN: %refactor -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+3):3 | %FileCheck -check-prefix=CALL-ARG %s // RUN: not %refactor -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+2):17 // RUN: not %refactor -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+1):20 simpleWithArg(a: 10) { str in print("with arg") } } // CALL-ARG: let str = await simpleWithArg(a: 10){{$}} // CALL-ARG-NEXT: {{^}}print("with arg") // RUN: %refactor -convert-to-async -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefixes=MANY-CALL %s func testMany() { // RUN: %refactor -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+1):3 | %FileCheck -check-prefix=MANY-CALL %s many { str, num in print("many") } } // MANY-CALL: let (str, num) = await many(){{$}} // MANY-CALL-NEXT: {{^}}print("many") // RUN: %refactor -convert-to-async -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=MEMBER-CALL %s func testMember() { // RUN: %refactor -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+2):15 | %FileCheck -check-prefix=MEMBER-CALL %s // RUN: %refactor -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+1):3 | %FileCheck -check-prefix=MEMBER-CALL %s retStruct().publicMember { str in print("call on member") } } // MEMBER-CALL: let str = await retStruct().publicMember(){{$}} // MEMBER-CALL-NEXT: {{^}}print("call on member") // RUN: %refactor -convert-to-async -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=MEMBER-CALL2 %s func testMember2() { // RUN: %refactor -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+1):25 | %FileCheck -check-prefix=MEMBER-CALL2 %s retStruct().retSelf().publicMember { str in print("call on member 2") } } // MEMBER-CALL2: let str = await retStruct().retSelf().publicMember(){{$}} // MEMBER-CALL2-NEXT: {{^}}print("call on member 2") // RUN: %refactor -convert-to-async -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=MEMBER-PARENS %s func testMemberParens() { // RUN: %refactor -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+3):3 | %FileCheck -check-prefix=MEMBER-PARENS %s // RUN: %refactor -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+2):5 | %FileCheck -check-prefix=MEMBER-PARENS %s // RUN: %refactor -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+1):15 | %FileCheck -check-prefix=MEMBER-PARENS %s (((retStruct().retSelf()).publicMember)) { str in print("call on member parens") } } // MEMBER-PARENS: let str = await (((retStruct().retSelf()).publicMember))(){{$}} // MEMBER-PARENS-NEXT: {{^}}print("call on member parens") // RUN: %refactor -convert-to-async -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefixes=SKIP-ASSIGN-FUNC %s func testSkipAssign() { // RUN: not %refactor -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+1):13 let _: Void = simple { str in print("assigned") } } // SKIP-ASSIGN-FUNC: {{^}}func testSkipAssign() async { // SKIP-ASSIGN-FUNC: let _: Void = simple { str in{{$}} // SKIP-ASSIGN-FUNC-NEXT: print("assigned"){{$}} // SKIP-ASSIGN-FUNC-NEXT: }{{$}} // Same as noParamAutoclosure defined above, but used just for the test below. // This avoids a compiler error when converting noParamAutoclosure to async. func noParamAutoclosure2(completion: @escaping @autoclosure () -> Void) {} // RUN: %refactor -convert-to-async -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefixes=SKIP-AUTOCLOSURE-FUNC %s func testSkipAutoclosure() { // RUN: not %refactor -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+1):3 noParamAutoclosure2(completion: print("autoclosure")) } // SKIP-AUTOCLOSURE-FUNC: {{^}}func testSkipAutoclosure() async { // SKIP-AUTOCLOSURE-FUNC: noParamAutoclosure2(completion: print("autoclosure")){{$}} // RUN: %refactor -convert-to-async -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=EMPTY-CAPTURE %s func testEmptyCapture() { // RUN: %refactor -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+1):3 | %FileCheck -check-prefix=EMPTY-CAPTURE %s simple { [] str in print("closure with empty capture list") } } // EMPTY-CAPTURE: let str = await simple(){{$}} // EMPTY-CAPTURE-NEXT: {{^}}print("closure with empty capture list") // RUN: %refactor -convert-to-async -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=CAPTURE %s func testCapture() { // RUN: %refactor -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+2):3 | %FileCheck -check-prefix=CAPTURE %s let myClass = MyClass() simpleClassParam { [unowned myClass] str in print("closure with capture list \(myClass)") } } // CAPTURE: let str = await simpleClassParam(){{$}} // CAPTURE-NEXT: {{^}}print("closure with capture list \(myClass)") // RUN: %refactor -convert-to-async -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefixes=NOT-HANDLER-FUNC %s func testNotCompletionHandler() { // RUN: %refactor -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+1):3 | %FileCheck -check-prefix=NOT-HANDLER %s otherName(execute: { str in print("otherName") }) } // NOT-HANDLER-FUNC: otherName(execute: { str in{{$}} // NOT-HANDLER-FUNC-NEXT: print("otherName"){{$}} // NOT-HANDLER-FUNC-NEXT: }){{$}} // NOT-HANDLER: let str = await otherName(){{$}} // NOT-HANDLER-NEXT: {{^}}print("otherName") // RUN: %refactor -convert-to-async -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=DEFAULT-ARGS-MISSING %s func testDefaultArgsMissing() { // RUN: %refactor -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+1):3 | %FileCheck -check-prefix=DEFAULT-ARGS-MISSING %s defaultArgs(a: 1) { str in print("defaultArgs missing") } } // DEFAULT-ARGS-MISSING: let str = await defaultArgs(a: 1){{$}} // DEFAULT-ARGS-MISSING-NEXT: {{^}}print("defaultArgs missing") // RUN: %refactor -convert-to-async -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=DEFAULT-ARGS-CALL %s func testDefaultArgs() { // RUN: %refactor -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+1):3 | %FileCheck -check-prefix=DEFAULT-ARGS-CALL %s defaultArgs(a: 1, b: 2) { str in print("defaultArgs") } } // DEFAULT-ARGS-CALL: let str = await defaultArgs(a: 1, b: 2){{$}} // DEFAULT-ARGS-CALL-NEXT: {{^}}print("defaultArgs") // RUN: %refactor -convert-to-async -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=BLOCK-CONVENTION-CALL %s func testBlockConvention() { // RUN: %refactor -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+1):3 | %FileCheck -check-prefix=BLOCK-CONVENTION-CALL %s blockConvention { print("blockConvention") } } // BLOCK-CONVENTION-CALL: await blockConvention(){{$}} // BLOCK-CONVENTION-CALL-NEXT: {{^}}print("blockConvention") // RUN: %refactor -convert-to-async -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=C-CONVENTION-CALL %s func testCConvention() { // RUN: %refactor -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+1):3 | %FileCheck -check-prefix=C-CONVENTION-CALL %s cConvention { print("cConvention") } } // C-CONVENTION-CALL: await cConvention(){{$}} // C-CONVENTION-CALL-NEXT: {{^}}print("cConvention") // RUN: %refactor -convert-to-async -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=VOID-AND-ERROR-CALL %s func testVoidAndError() { // RUN: %refactor -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+1):3 | %FileCheck -check-prefix=VOID-AND-ERROR-CALL %s optVoidAndErrorCompletion { v, err in print("opt void and error completion \(String(describing: v))") } } // VOID-AND-ERROR-CALL: try await optVoidAndErrorCompletion(){{$}} // VOID-AND-ERROR-CALL-NEXT: {{^}}print("opt void and error completion \(String(describing: <#v#>))"){{$}} // RUN: %refactor -convert-to-async -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=VOID-AND-ERROR-CALL2 %s func testVoidAndError2() { // RUN: %refactor -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+1):3 | %FileCheck -check-prefix=VOID-AND-ERROR-CALL2 %s optVoidAndErrorCompletion { _, err in print("opt void and error completion 2") } } // VOID-AND-ERROR-CALL2: try await optVoidAndErrorCompletion(){{$}} // VOID-AND-ERROR-CALL2-NEXT: {{^}}print("opt void and error completion 2"){{$}} // RUN: %refactor -convert-to-async -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=VOID-AND-ERROR-CALL3 %s func testVoidAndError3() { // RUN: %refactor -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+1):3 | %FileCheck -check-prefix=VOID-AND-ERROR-CALL3 %s tooMuchVoidAndErrorCompletion { v, v1, err in print("void and error completion 3") } } // VOID-AND-ERROR-CALL3: try await tooMuchVoidAndErrorCompletion(){{$}} // VOID-AND-ERROR-CALL3-NEXT: {{^}}print("void and error completion 3"){{$}} // RUN: %refactor -convert-to-async -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=VOID-AND-ERROR-CALL4 %s func testVoidAndError4() { // RUN: %refactor -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+1):3 | %FileCheck -check-prefix=VOID-AND-ERROR-CALL4 %s voidAndErrorCompletion { v, err in print("void and error completion \(v)") } } // VOID-AND-ERROR-CALL4: try await voidAndErrorCompletion(){{$}} // VOID-AND-ERROR-CALL4-NEXT: {{^}}print("void and error completion \(<#v#>)"){{$}} func testPreserveComments() { // RUN: %refactor -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+1):3 | %FileCheck -check-prefix=PRESERVE-COMMENTS %s simpleWithArg(/*hello*/ a: /*a*/5) { str in // b1 // b2 print("1") // c print("2") /* d1 d2 */ if .random() { // e } /* f1 */ /* f2 */} // don't pick this up } // PRESERVE-COMMENTS: let str = await simpleWithArg(/*hello*/ a: /*a*/5) // PRESERVE-COMMENTS-NEXT: // b1 // PRESERVE-COMMENTS-NEXT: // b2 // PRESERVE-COMMENTS-NEXT: print("1") // PRESERVE-COMMENTS-NEXT: // c // PRESERVE-COMMENTS-NEXT: print("2") // PRESERVE-COMMENTS-NEXT: /* // PRESERVE-COMMENTS-NEXT: d1 // PRESERVE-COMMENTS-NEXT: d2 // PRESERVE-COMMENTS-NEXT: */ // PRESERVE-COMMENTS-NEXT: if .random() { // PRESERVE-COMMENTS-NEXT: // e // PRESERVE-COMMENTS-NEXT: } // PRESERVE-COMMENTS-NEXT: /* f1 */ // PRESERVE-COMMENTS-NEXT: /* f2 */{{$}} // PRESERVE-COMMENTS-NOT: }{{$}} // RUN: %refactor -convert-to-async -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=PRESERVE-COMMENTS-ERROR %s func testPreserveComments2() { // RUN: %refactor -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+1):3 | %FileCheck -check-prefix=PRESERVE-COMMENTS-ERROR %s errorOnly { err in // a if err != nil { // b print("oh no") // c /* d */ return /* e */ } if err != nil { // f print("fun") // g } // h print("good times") // i } } // PRESERVE-COMMENTS-ERROR: do { // PRESERVE-COMMENTS-ERROR-NEXT: try await errorOnly() // PRESERVE-COMMENTS-ERROR-NEXT: // a // PRESERVE-COMMENTS-ERROR-NEXT: // h // PRESERVE-COMMENTS-ERROR-NEXT: print("good times") // PRESERVE-COMMENTS-ERROR-NEXT: // i // PRESERVE-COMMENTS-ERROR: } catch let err { // PRESERVE-COMMENTS-ERROR-NEXT: // b // PRESERVE-COMMENTS-ERROR-NEXT: print("oh no") // PRESERVE-COMMENTS-ERROR-NEXT: // c // PRESERVE-COMMENTS-ERROR-NEXT: /* d */ // PRESERVE-COMMENTS-ERROR-NEXT: /* e */ // PRESERVE-COMMENTS-ERROR-NEXT: // f // PRESERVE-COMMENTS-ERROR-NEXT: print("fun") // PRESERVE-COMMENTS-ERROR-NEXT: // g // PRESERVE-COMMENTS-ERROR-NEXT: } // RUN: %refactor -convert-to-async -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=PRESERVE-TRAILING-COMMENT-FN %s func testPreserveComments3() { // RUN: %refactor -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+1):3 | %FileCheck -check-prefix=PRESERVE-TRAILING-COMMENT-CALL %s simple { s in print(s) } // make sure we pickup this trailing comment if we're converting the function, but not the call } // PRESERVE-TRAILING-COMMENT-FN: func testPreserveComments3() async { // PRESERVE-TRAILING-COMMENT-FN-NEXT: // // PRESERVE-TRAILING-COMMENT-FN-NEXT: let s = await simple() // PRESERVE-TRAILING-COMMENT-FN-NEXT: print(s) // PRESERVE-TRAILING-COMMENT-FN-NEXT: // make sure we pickup this trailing comment if we're converting the function, but not the call // PRESERVE-TRAILING-COMMENT-FN-NEXT: } // PRESERVE-TRAILING-COMMENT-CALL: let s = await simple() // PRESERVE-TRAILING-COMMENT-CALL-NEXT: print(s) // PRESERVE-TRAILING-COMMENT-CALL-NOT: // make sure we pickup this trailing comment if we're converting the function, but not the call class TestConvertFunctionWithCallToFunctionsWithSpecialName { required init() {} subscript(index: Int) -> Int { return index } // RUN: %refactor -convert-to-async -dump-text -source-filename %s -pos=%(line+1):3 static func example() -> Self { let x = self.init() _ = x[1] return x } } // rdar://78781061 // RUN: %refactor -convert-to-async -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=FOR-IN-WHERE %s func testForInWhereRefactoring() { let arr: [String] = [] for str in arr where str.count != 0 { simple { res in print(res) } } } // FOR-IN-WHERE: func testForInWhereRefactoring() async { // FOR-IN-WHERE-NEXT: let arr: [String] = [] // FOR-IN-WHERE-NEXT: for str in arr where str.count != 0 { // FOR-IN-WHERE-NEXT: let res = await simple() // FOR-IN-WHERE-NEXT: print(res) // FOR-IN-WHERE-NEXT: } // FOR-IN-WHERE-NEXT: }
apache-2.0
ecee4495fc15c9a285bd5a9afdb73c65
49.195039
165
0.69472
3.141396
false
false
false
false
asp2insp/Twittercism
Twittercism/Reactor.swift
3
2616
// // Reactor.swift // Nuclear // // Created by Josiah Gaskin on 5/9/15. // Copyright (c) 2015 Josiah Gaskin. All rights reserved. // import Foundation public class Reactor { public var debug : Bool = false private var stateMap = Immutable.toState([:]) private var stores : [String:Store] = [:] private var changeObserver : ChangeObserver! init() { changeObserver = ChangeObserver(reactor: self) } // Dispatch an action to the appropriate handlers func dispatch(action: String, payload: Any) { // Let each core handle the action for (id, store) in self.stores { let prevState = self.stateMap.getIn([id]) let newState = store.handle(prevState, action: action, payload: payload) self.stateMap = self.stateMap.setIn([id], withValue: newState) } if self.debug { NSLog("Reacting to \(action)") } self.changeObserver.notifyObservers(self.stateMap) } // Add a new store to the reactor func registerStore(id: String, store: Store) { self.stores[id] = store self.stateMap = self.stateMap.setIn([id], withValue: store.getInitialState()) self.changeObserver.notifyObservers(self.stateMap) } // Observe the given getter. The result of the getter will be passed // to the handler, which will be invoked every time there's a new value. func observe(getter: Getter, handler: ((Immutable.State) -> ())) -> UInt { return self.changeObserver.onChange(getter, handler: handler) } // Unobserve the handlers bound to the given IDs. func unobserve(ids : [UInt]) { for id in ids { self.changeObserver.removeHandler(id) } } // Restore all registered stores to their initial state func reset() { for (id, store) in self.stores { let prevState = self.stateMap.getIn([id]) let resetState = store.handleReset(prevState) self.stateMap = self.stateMap.setIn([id], withValue: resetState) } changeObserver.handleReset() } // Evaluate the given getter and return the immutable state func evaluate(getter: Getter) -> Immutable.State { return Evaluator.evaluate(self.stateMap, withGetter: getter) } // Evaluate the given getter and return the swift native representation func evaluateToSwift(getter: Getter) -> Any? { return evaluate(getter).toSwift() } // TODO Add binding // TODO Add autobinding // TODO Add caching for autobinding }
mit
96d9b4c7f6ecbfe085e2db024dd7ff05
32.538462
85
0.630352
4.288525
false
false
false
false
djfitz/SFFontFeatures
SFFontFeaturesDemo/SFFontFeaturesDemo/SFFontFeaturesTableViewController.swift
1
6525
// // SFFontFeaturesTableViewController.swift // SFFontFeaturesDemo // // Created by Doug Hill on 12/8/16. // Copyright © 2016 doughill. All rights reserved. // import UIKit class SFFontFeaturesTableViewController: UITableViewController { override func viewDidLoad() { super.viewDidLoad() self.tableView.estimatedRowHeight = 50 } // MARK: - Table view data source override func numberOfSections(in tableView: UITableView) -> Int { return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 11 } override func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat { return UITableView.automaticDimension } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: FeatureTableViewCell.cellID, for: indexPath) as! FeatureTableViewCell // Reset any previous default traits from the reused cell. // Contextual alternatives encapsulate a number of font features, often dependent on the character string, so turn this feature // off so it doesn't affect the results in the table. cell.regularLabel.font = UIFont.systemFont(ofSize: cell.regularLabel.font.pointSize, weight: .regular).withTraits( SFFontFeatureTraits.withContextualAlternativeDisabled() ) cell.featuredLabel.font = UIFont.systemFont(ofSize: cell.featuredLabel.font.pointSize, weight: .regular).withTraits( SFFontFeatureTraits.withContextualAlternativeDisabled() ) // Show one font feature for each row switch indexPath.row { case 0: cell.descLabel.text = "Straight-sided six and nine" cell.regularLabel.text = "6 9" cell.featuredLabel.text = "6 9" cell.featuredLabel.font = cell.featuredLabel.font.withTraits(SFFontFeatureTraits.withStraightSidedSixAndNineEnabled()) case 1: cell.descLabel.text = "Open 4" cell.regularLabel.text = "1234" cell.featuredLabel.text = "1234" cell.featuredLabel.font = cell.featuredLabel.font.withTraits(SFFontFeatureTraits.withOpenFourEnabled()) case 2: cell.descLabel.text = "High Legibility" cell.regularLabel.text = "labcd0123456789 11:15" cell.featuredLabel.text = "labcd0123456789 11:15" let traits = SFFontFeatureTraits() traits.highLegibility = TriState.on cell.featuredLabel.font = cell.featuredLabel.font.withTraits(SFFontFeatureTraits.withHighLegibilityEnabled()) case 3: cell.descLabel.text = "Vertically Centered Colon" cell.regularLabel.text = ":21" let regTraits = SFFontFeatureTraits() regTraits.contextualAlternatives = TriState.off cell.regularLabel.font = cell.featuredLabel.font.withTraits(regTraits) cell.featuredLabel.text = ":21" cell.featuredLabel.font = cell.featuredLabel.font.withTraits(SFFontFeatureTraits.withVerticallyCenteredColonEnabled()) case 4: cell.descLabel.text = "One Story A" cell.regularLabel.text = "a" cell.featuredLabel.text = "a" cell.featuredLabel.font = cell.featuredLabel.font.withTraits(SFFontFeatureTraits.withOneStoryAEnabled()) case 5: cell.descLabel.text = "Upper Case Small Capitals" cell.regularLabel.text = "abcdefghABCDEFGH" cell.featuredLabel.text = "abcdefghABCDEFGH" cell.featuredLabel.font = cell.featuredLabel.font.withTraits( SFFontFeatureTraits.withUpperCaseSmallCapitalsEnabled() ) case 6: cell.descLabel.text = "Lower Case Small Capitals" cell.regularLabel.text = "abcdefghABCDEFGH" cell.featuredLabel.text = "abcdefghABCDEFGH" cell.featuredLabel.font = cell.featuredLabel.font.withTraits( SFFontFeatureTraits.withLowerCaseSmallCapitalsEnabled() ) case 7: cell.descLabel.text = "Contextual Fractional Form" cell.regularLabel.text = "99/100" cell.featuredLabel.text = "99/100" cell.featuredLabel.font = cell.featuredLabel.font.withTraits( SFFontFeatureTraits.withContextualFractionalFormsEnabled() ) case 8: cell.descLabel.text = "Monospaced vs. Proportional Numbers" cell.regularHeaderLabel.text = "  Proportional Numbers" cell.regularLabel.text = "0123456789" cell.regularLabel.font = cell.featuredLabel.font.withTraits( SFFontFeatureTraits.withProportionallySpacedNumbersEnabled() ) cell.featuredHeaderLabel.text = "Monospaced Numbers" cell.featuredLabel.text = "0123456789" cell.featuredLabel.font = cell.featuredLabel.font.withTraits( SFFontFeatureTraits.withMonospacedNumbersEnabled() ) case 9: cell.descLabel.text = "Superior Positions (Superscript)" cell.regularLabel.text = "See alsoibid" let pref = NSMutableAttributedString(string: "See also") pref.append( NSMutableAttributedString( string: "ibid", attributes: [ .font : cell.regularLabel.font?.withTraits( SFFontFeatureTraits.withSuperiorPositionsEnabled()) as Any ] )) cell.featuredLabel.attributedText = pref case 10: cell.descLabel.text = "Inferior Positions (Subscript)" cell.regularLabel.text = "C1H2O3S" cell.featuredLabel.text = "C1H2O3S" cell.featuredLabel.font = cell.featuredLabel.font.withTraits( SFFontFeatureTraits.withInferiorPositionsEnabled() ) default: cell.descLabel.text = "Dunno about this one" cell.regularLabel.text = "1 maybe 2" cell.featuredLabel.text = "1 or 2" } return cell } }
mit
d0518f5332243c591921b9c7c0c6b0a2
44.291667
182
0.622815
4.778022
false
false
false
false
jianghongbing/APIReferenceDemo
WebKit/WKUserContentController/WKUserContentController/ViewController.swift
1
5950
// // ViewController.swift // WKUserContentController // // Created by pantosoft on 2018/12/25. // Copyright © 2018 jianghongbing. All rights reserved. // import UIKit import WebKit class ViewController: UIViewController { lazy var webView: WKWebView = { let configuration = WKWebViewConfiguration() //WKUseContentController:主要用于添加脚本给webView和在js中发送消息给webView,实现webView和js之间的交互 let userContentController = WKUserContentController() configuration.userContentController = userContentController let webView = WKWebView(frame: self.view.bounds.insetBy(dx: 0, dy: 100), configuration: configuration) webView.autoresizingMask = .flexibleWidth self.view.addSubview(webView) return webView }() override func viewDidLoad() { super.viewDidLoad() addMessageHandlers() addUserScripts() loadLocalHTML() } private func loadLocalHTML() { let path = Bundle.main.path(forResource: "index", ofType: "html") let url = URL(fileURLWithPath: path!) webView.loadFileURL(url, allowingReadAccessTo: url) } // private func addMessageHandlers() { let aUserContentController = AUserContentController(with: self) //添加messageHandler,可以在js中window.webKit.name.postmessage的方式发送消息给webView //没有参数,js发送不带参数的消息给webView webView.configuration.userContentController.add(aUserContentController, name: "funcA") //带有参数,js发送带有参数的消息给webView webView.configuration.userContentController.add(aUserContentController, name: "funcB") } private func removeMessageHandlers() { webView.configuration.userContentController.removeScriptMessageHandler(forName: "funcA") webView.configuration.userContentController.removeScriptMessageHandler(forName: "funcB") } //添加脚本到网页中 private func addUserScripts() { //创建用户脚本,source:js脚本; injecttionTiem:脚本注入时间,atDocumentStart:在document创建之后,所有资源加载完成之前注入,atDocumentEnd,在document创建之后,其他子资源加载完成之前注入; forMainFrameOnly:是否只注入到主frame,如果为false,脚本会注入到网页中的所有frame中 let scriptOne = WKUserScript(source: "function scriptOne() {let p = document.createElement(\"p\");p.textContent = \"script add by native\";document.body.appendChild(p);}", injectionTime: .atDocumentEnd, forMainFrameOnly: true) //注入脚本 webView.configuration.userContentController.addUserScript(scriptOne) } //移除网页到脚本中 private func removeUserScripts() { webView.configuration.userContentController.removeAllUserScripts() } deinit { removeMessageHandlers() removeUserScripts() } private func funcA() { alert(with: "执行了funcA", message: nil) } private func funcB(a:Int, b:Int) { alert(with: "执行了funcB", message: "参数: a=\(a),b=\(b)") } @IBAction func excuteJSFunction1(_ sender: Any) { //执行js脚本,闭包回调的参数,result:是执行js函数后返回的结构,error是执行函数过程发生的错误 webView.evaluateJavaScript("funcOne()") { (result, error) in if let error = error { print("error:\(error)") }else if let result = result { print("result:\(result)") } } } @IBAction func excuteJSFunction2(_ sender: Any) { webView.evaluateJavaScript("funcTwo(5, 6)") { (result, error) in if let error = error { print("error:\(error)") }else if let result = result { print("result:\(result)") } } } @IBAction func excuteJSFunction3(_ sender: Any) { webView.evaluateJavaScript("funcThree(5, 6)") { (result, error) in if let error = error { print("error:\(error)") }else if let result = result { print("result:\(result)") } } } @IBAction func checkAllRuleList(_ sender: Any) { let ruleListStore = WKContentRuleListStore(url: webView.url!) ruleListStore?.getAvailableContentRuleListIdentifiers{ if let identifiers = $0 { identifiers.forEach{ print("identifier:\($0)") } } } } @IBAction func addRuleList(_ sender: Any) { } } extension ViewController: WKScriptMessageHandler { func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) { //发送消息的名称,也就是在添加messageHandler时的名称 let title = message.name //发送消息的数据,相当于函数的参数 let body = message.body //添加messageHandler的所在的webView // let webView = message.webView //发送消息给messageHanadler的网页的相关信息 // let frameInfo = message.frameInfo if title == "funcA" { funcA() }else if (title == "funcB") { if let parameters = body as? Dictionary<String, Int>, let a = parameters["A"], let b = parameters["B"] { funcB(a: a, b: b) } } } } extension ViewController { private func alert(with title: String?, message: String?) { let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert) let action = UIAlertAction(title: "OK", style: .default, handler: nil) alertController.addAction(action) present(alertController, animated: true, completion: nil) } }
mit
33245bdc73593ced06cc7613d2a8339b
35.059603
234
0.633609
4.511185
false
true
false
false
banjun/SwiftBeaker
Examples/12. Advanced Action.swift
1
5669
import Foundation import APIKit import URITemplate protocol URITemplateContextConvertible: Encodable {} extension URITemplateContextConvertible { var context: [String: String] { return ((try? JSONSerialization.jsonObject(with: JSONEncoder().encode(self))) as? [String: String]) ?? [:] } } public enum RequestError: Error { case encode } public enum ResponseError: Error { case undefined(Int, String?) case invalidData(Int, String?) } struct RawDataParser: DataParser { var contentType: String? {return nil} func parse(data: Data) -> Any { return data } } struct TextBodyParameters: BodyParameters { let contentType: String let content: String func buildEntity() throws -> RequestBodyEntity { guard let r = content.data(using: .utf8) else { throw RequestError.encode } return .data(r) } } public protocol APIBlueprintRequest: Request {} extension APIBlueprintRequest { public var dataParser: DataParser {return RawDataParser()} func contentMIMEType(in urlResponse: HTTPURLResponse) -> String? { return (urlResponse.allHeaderFields["Content-Type"] as? String)?.components(separatedBy: ";").first?.trimmingCharacters(in: .whitespaces) } func data(from object: Any, urlResponse: HTTPURLResponse) throws -> Data { guard let d = object as? Data else { throw ResponseError.invalidData(urlResponse.statusCode, contentMIMEType(in: urlResponse)) } return d } func string(from object: Any, urlResponse: HTTPURLResponse) throws -> String { guard let s = String(data: try data(from: object, urlResponse: urlResponse), encoding: .utf8) else { throw ResponseError.invalidData(urlResponse.statusCode, contentMIMEType(in: urlResponse)) } return s } func decodeJSON<T: Decodable>(from object: Any, urlResponse: HTTPURLResponse) throws -> T { return try JSONDecoder().decode(T.self, from: data(from: object, urlResponse: urlResponse)) } public func intercept(object: Any, urlResponse: HTTPURLResponse) throws -> Any { return object } } protocol URITemplateRequest: Request { static var pathTemplate: URITemplate { get } associatedtype PathVars: URITemplateContextConvertible var pathVars: PathVars { get } } extension URITemplateRequest { // reconstruct URL to use URITemplate.expand. NOTE: APIKit does not support URITemplate format other than `path + query` public func intercept(urlRequest: URLRequest) throws -> URLRequest { var req = urlRequest req.url = URL(string: baseURL.absoluteString + type(of: self).pathTemplate.expand(pathVars.context))! return req } } /// indirect Codable Box-like container for recursive data structure definitions public class Indirect<V: Codable>: Codable { public var value: V public init(_ value: V) { self.value = value } public required init(from decoder: Decoder) throws { self.value = try V(from: decoder) } public func encode(to encoder: Encoder) throws { try value.encode(to: encoder) } } // MARK: - Transitions struct List_All_Tasks: APIBlueprintRequest { let baseURL: URL var method: HTTPMethod {return .get} var path: String {return "/tasks/tasks{?status,priority}"} enum Responses { case http200_application_json(Void) } func response(from object: Any, urlResponse: HTTPURLResponse) throws -> Responses { let contentType = contentMIMEType(in: urlResponse) switch (urlResponse.statusCode, contentType) { case (200, "application/json"?): return .http200_application_json(try decodeJSON(from: object, urlResponse: urlResponse)) default: throw ResponseError.undefined(urlResponse.statusCode, contentType) } } } /// This is a state transition to another resource. struct Retrieve_Task: APIBlueprintRequest, URITemplateRequest { let baseURL: URL var method: HTTPMethod {return .get} let path = "" // see intercept(urlRequest:) static let pathTemplate: URITemplate = "/task/{id}" var pathVars: PathVars struct PathVars: URITemplateContextConvertible { /// var id: String } enum Responses { case http200_application_json(Void) } func response(from object: Any, urlResponse: HTTPURLResponse) throws -> Responses { let contentType = contentMIMEType(in: urlResponse) switch (urlResponse.statusCode, contentType) { case (200, "application/json"?): return .http200_application_json(try decodeJSON(from: object, urlResponse: urlResponse)) default: throw ResponseError.undefined(urlResponse.statusCode, contentType) } } } struct Delete_Task: APIBlueprintRequest, URITemplateRequest { let baseURL: URL var method: HTTPMethod {return .delete} let path = "" // see intercept(urlRequest:) static let pathTemplate: URITemplate = "/task/{id}" var pathVars: PathVars struct PathVars: URITemplateContextConvertible { /// var id: String } enum Responses { case http204_(Void) } func response(from object: Any, urlResponse: HTTPURLResponse) throws -> Responses { let contentType = contentMIMEType(in: urlResponse) switch (urlResponse.statusCode, contentType) { case (204, _): return .http204_(try decodeJSON(from: object, urlResponse: urlResponse)) default: throw ResponseError.undefined(urlResponse.statusCode, contentType) } } } // MARK: - Data Structures
mit
6ea35c619998a1ad88166b1c345b5491
30.670391
145
0.679132
4.594003
false
false
false
false
quaderno/quaderno-ios
Tests/ResourceTests.swift
2
18937
// // ResourceTests.swift // // Copyright (c) 2015 Recrea (http://recreahq.com/) // // 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 @testable import Quaderno final class ResourceTests: TestCase { // MARK: CRUD private let crudResources: [CRUDResource.Type] = [ Contact.self, Receipt.self, Invoice.self, Credit.self, Expense.self, Estimate.self, Recurring.self, Item.self, Webhook.self, Evidence.self, ] func testThatResourcesCanBeCreated() { crudResources.forEach { let request = $0.request(.create(["name": "John Doe"])) XCTAssert(request.method == .post) XCTAssert(request.parameters?.count == 1) XCTAssert(request.parameters?["name"] as? String == "John Doe") let path: String? switch $0 { case is Contact.Type: path = "/contacts.json" case is Receipt.Type: path = "/receipts.json" case is Invoice.Type: path = "/invoices.json" case is Credit.Type: path = "/credits.json" case is Expense.Type: path = "/expenses.json" case is Estimate.Type: path = "/estimates.json" case is Recurring.Type: path = "/recurring.json" case is Item.Type: path = "/items.json" case is Webhook.Type: path = "/webhooks.json" case is Evidence.Type: path = "/evidences.json" default: path = nil } if let resourcePath = path { XCTAssert(uri(for: request) == uri(byAppendingPathToBaseURL: resourcePath)) } else { XCTFail("CRUD resource not tested: \($0)") } } } func testThatResourcesCanBeListed() { crudResources.forEach { let request = $0.request(.list) XCTAssert(request.method == .get) XCTAssertNil(request.parameters) let path: String? switch $0 { case is Contact.Type: path = "/contacts.json" case is Receipt.Type: path = "/receipts.json" case is Invoice.Type: path = "/invoices.json" case is Credit.Type: path = "/credits.json" case is Expense.Type: path = "/expenses.json" case is Estimate.Type: path = "/estimates.json" case is Recurring.Type: path = "/recurring.json" case is Item.Type: path = "/items.json" case is Webhook.Type: path = "/webhooks.json" case is Evidence.Type: path = "/evidences.json" default: path = nil } if let resourcePath = path { XCTAssert(uri(for: request) == uri(byAppendingPathToBaseURL: resourcePath)) } else { XCTFail("CRUD resource not tested: \($0)") } } } func testThatResourcesCanBeRead() { crudResources.forEach { let identifier = generateResourceIdentifier() let request = $0.request(.read(identifier)) XCTAssert(request.method == .get) XCTAssertNil(request.parameters) let path: String? switch $0 { case is Contact.Type: path = "/contacts/\(identifier).json" case is Receipt.Type: path = "/receipts/\(identifier).json" case is Invoice.Type: path = "/invoices/\(identifier).json" case is Credit.Type: path = "/credits/\(identifier).json" case is Expense.Type: path = "/expenses/\(identifier).json" case is Estimate.Type: path = "/estimates/\(identifier).json" case is Recurring.Type: path = "/recurring/\(identifier).json" case is Item.Type: path = "/items/\(identifier).json" case is Webhook.Type: path = "/webhooks/\(identifier).json" case is Evidence.Type: path = "/evidences/\(identifier).json" default: path = nil } if let resourcePath = path { XCTAssert(uri(for: request) == uri(byAppendingPathToBaseURL: resourcePath)) } else { XCTFail("CRUD resource not tested: \($0)") } } } func testThatResourcesCanBeUpdated() { crudResources.forEach { let identifier = generateResourceIdentifier() let request = $0.request(.update(identifier, ["name": "John Doe"])) XCTAssert(request.method == .put) XCTAssert(request.parameters?.count == 1) XCTAssert(request.parameters?["name"] as? String == "John Doe") let path: String? switch $0 { case is Contact.Type: path = "/contacts/\(identifier).json" case is Receipt.Type: path = "/receipts/\(identifier).json" case is Invoice.Type: path = "/invoices/\(identifier).json" case is Credit.Type: path = "/credits/\(identifier).json" case is Expense.Type: path = "/expenses/\(identifier).json" case is Estimate.Type: path = "/estimates/\(identifier).json" case is Recurring.Type: path = "/recurring/\(identifier).json" case is Item.Type: path = "/items/\(identifier).json" case is Webhook.Type: path = "/webhooks/\(identifier).json" case is Evidence.Type: path = "/evidences/\(identifier).json" default: path = nil } if let resourcePath = path { XCTAssert(uri(for: request) == uri(byAppendingPathToBaseURL: resourcePath)) } else { XCTFail("CRUD resource not tested: \($0)") } } } func testThatResourcesCanBeDeleted() { crudResources.forEach { let identifier = generateResourceIdentifier() let request = $0.request(.delete(identifier)) XCTAssert(request.method == .delete) XCTAssertNil(request.parameters) let path: String? switch $0 { case is Contact.Type: path = "/contacts/\(identifier).json" case is Receipt.Type: path = "/receipts/\(identifier).json" case is Invoice.Type: path = "/invoices/\(identifier).json" case is Credit.Type: path = "/credits/\(identifier).json" case is Expense.Type: path = "/expenses/\(identifier).json" case is Estimate.Type: path = "/estimates/\(identifier).json" case is Recurring.Type: path = "/recurring/\(identifier).json" case is Item.Type: path = "/items/\(identifier).json" case is Webhook.Type: path = "/webhooks/\(identifier).json" case is Evidence.Type: path = "/evidences/\(identifier).json" default: path = nil } if let resourcePath = path { XCTAssert(uri(for: request) == uri(byAppendingPathToBaseURL: resourcePath)) } else { XCTFail("CRUD resource not tested: \($0)") } } } // MARK: Deliverable func testThatReceiptsCanBeDelivered() { let receiptIdentifier = generateResourceIdentifier() let request = Receipt.request(.deliver(receiptIdentifier)) XCTAssert(request.method == .get) XCTAssert(request.parameters == nil) XCTAssert(uri(for: request) == uri(byAppendingPathToBaseURL: "/receipts/\(receiptIdentifier)/deliver.json")) } func testThatInvoicesCanBeDelivered() { let invoiceIdentifier = generateResourceIdentifier() let request = Invoice.request(.deliver(invoiceIdentifier)) XCTAssert(request.method == .get) XCTAssert(request.parameters == nil) XCTAssert(uri(for: request) == uri(byAppendingPathToBaseURL: "/invoices/\(invoiceIdentifier)/deliver.json")) } func testThatCreditsCanBeDelivered() { let creditIdentifier = generateResourceIdentifier() let request = Credit.request(.deliver(creditIdentifier)) XCTAssert(request.method == .get) XCTAssert(request.parameters == nil) XCTAssert(uri(for: request) == uri(byAppendingPathToBaseURL: "/credits/\(creditIdentifier)/deliver.json")) } func testThatEstimatesCanBeDelivered() { let estimateIdentifier = generateResourceIdentifier() let request = Estimate.request(.deliver(estimateIdentifier)) XCTAssert(request.method == .get) XCTAssert(request.parameters == nil) XCTAssert(uri(for: request) == uri(byAppendingPathToBaseURL: "/estimates/\(estimateIdentifier)/deliver.json")) } // MARK: Payable func testThatInvoicesCanBePaid() { let invoiceIdentifier = generateResourceIdentifier() let instructions = PaymentInstructions(amount: 12.3, method: .creditCard, date: nil) let request = Invoice.request(.pay(invoiceIdentifier, with: instructions)) XCTAssert(request.method == .post) XCTAssert(uri(for: request) == uri(byAppendingPathToBaseURL: "/invoices/\(invoiceIdentifier)/payments.json")) XCTAssert(request.parameters?.count == 2) XCTAssert(request.parameters?["amount"] as? String == "12.3") XCTAssert(request.parameters?["payment_method"] as? String == "credit_card") } func testThatExpensesCanBePaid() { let paymentDate = Date() let expenseIdentifier = generateResourceIdentifier() let instructions = PaymentInstructions(amount: 12.3, method: .creditCard, date: paymentDate) let request = Expense.request(.pay(expenseIdentifier, with: instructions)) XCTAssert(request.method == .post) XCTAssert(uri(for: request) == uri(byAppendingPathToBaseURL: "/expenses/\(expenseIdentifier)/payments.json")) XCTAssert(request.parameters?.count == 3) XCTAssert(request.parameters?["amount"] as? String == "12.3") XCTAssert(request.parameters?["payment_method"] as? String == "credit_card") let dateComponents = Calendar.current.dateComponents([.year, .month, .day], from: paymentDate) let expectedDate = String(format: "%04zd-%02zd-%02zd", dateComponents.year!, dateComponents.month!, dateComponents.day!) XCTAssert(request.parameters?["date"] as? String == expectedDate) } func testThatPaymentsCanBeMadeForEachPaymentMethod() { let paymentMethods: [PaymentInstructions.Method: String] = [ .creditCard: "credit_card", .cash: "cash", .wireTransfer: "wire_transfer", .directDebit: "direct_debit", .check: "check", .promissoryNote: "promissory_note", .iou: "iou", .payPal: "paypal", .other: "other", ] paymentMethods.forEach { method, expectedValue in let paymentInstructions = PaymentInstructions(amount: 12.3, method: method, date: nil) let request = Invoice.request(.pay(1, with: paymentInstructions)) XCTAssert(request.parameters?["payment_method"] as? String == expectedValue) } } func testThatInvoicePaymentsCanBeListed() { let invoiceIdentifier = generateResourceIdentifier() let request = Invoice.request(.list(from: invoiceIdentifier)) XCTAssert(request.method == .get) XCTAssert(request.parameters == nil) XCTAssert(uri(for: request) == uri(byAppendingPathToBaseURL: "/invoices/\(invoiceIdentifier)/payments.json")) } func testThatExpensePaymentsCanBeListed() { let expenseIdentifier = generateResourceIdentifier() let request = Expense.request(.list(from: expenseIdentifier)) XCTAssert(request.method == .get) XCTAssert(request.parameters == nil) XCTAssert(uri(for: request) == uri(byAppendingPathToBaseURL: "/expenses/\(expenseIdentifier)/payments.json")) } func testThatInvoicePaymentsCanBeRead() { let invoiceIdentifier = generateResourceIdentifier() let paymentIdentifier = generateResourceIdentifier() let request = Invoice.request(.read(paymentIdentifier, from: invoiceIdentifier)) XCTAssert(request.method == .get) XCTAssert(request.parameters == nil) XCTAssert(uri(for: request) == uri(byAppendingPathToBaseURL: "/invoices/\(invoiceIdentifier)/payments/\(paymentIdentifier).json")) } func testThatExpensePaymentsCanBeRead() { let expenseIdentifier = generateResourceIdentifier() let paymentIdentifier = generateResourceIdentifier() let request = Expense.request(.read(paymentIdentifier, from: expenseIdentifier)) XCTAssert(request.method == .get) XCTAssert(request.parameters == nil) XCTAssert(uri(for: request) == uri(byAppendingPathToBaseURL: "/expenses/\(expenseIdentifier)/payments/\(paymentIdentifier).json")) } func testThatInvoicePaymentsCanBeDeleted() { let invoiceIdentifier = generateResourceIdentifier() let paymentIdentifier = generateResourceIdentifier() let request = Invoice.request(.delete(paymentIdentifier, from: invoiceIdentifier)) XCTAssert(request.method == .delete) XCTAssert(request.parameters == nil) XCTAssert(uri(for: request) == uri(byAppendingPathToBaseURL: "/invoices/\(invoiceIdentifier)/payments/\(paymentIdentifier).json")) } func testThatExpensePaymentsCanBeDeleted() { let expenseIdentifier = generateResourceIdentifier() let paymentIdentifier = generateResourceIdentifier() let request = Expense.request(.delete(paymentIdentifier, from: expenseIdentifier)) XCTAssert(request.method == .delete) XCTAssert(request.parameters == nil) XCTAssert(uri(for: request) == uri(byAppendingPathToBaseURL: "/expenses/\(expenseIdentifier)/payments/\(paymentIdentifier).json")) } // MARK: Taxes func testThatTaxesCanBeCalculated() { let transaction1 = Transaction(country: "ES") let request1 = Tax.request(.calculate(for: transaction1)) XCTAssert(request1.method == .get) XCTAssert(uri(for: request1) == uri(byAppendingPathToBaseURL: "/taxes/calculate.json")) XCTAssert(request1.parameters?.count == 1) XCTAssert(request1.parameters?["country"] as? String == "ES") let transaction2 = Transaction(country: "ES", postalCode: "35018") let request2 = Tax.request(.calculate(for: transaction2)) XCTAssert(request2.method == .get) XCTAssert(uri(for: request2) == uri(byAppendingPathToBaseURL: "/taxes/calculate.json")) XCTAssert(request2.parameters?.count == 2) XCTAssert(request2.parameters?["country"] as? String == "ES") XCTAssert(request2.parameters?["postal_code"] as? String == "35018") let transaction3 = Transaction(country: "ES", postalCode: "35018", vatNumber: "98765432X") let request3 = Tax.request(.calculate(for: transaction3)) XCTAssert(request3.method == .get) XCTAssert(uri(for: request3) == uri(byAppendingPathToBaseURL: "/taxes/calculate.json")) XCTAssert(request3.parameters?.count == 3) XCTAssert(request3.parameters?["country"] as? String == "ES") XCTAssert(request3.parameters?["postal_code"] as? String == "35018") XCTAssert(request3.parameters?["vat_number"] as? String == "98765432X") let transaction4 = Transaction(country: "ES", postalCode: "35018", vatNumber: "98765432X", category: .service) let request4 = Tax.request(.calculate(for: transaction4)) XCTAssert(request4.method == .get) XCTAssert(uri(for: request4) == uri(byAppendingPathToBaseURL: "/taxes/calculate.json")) XCTAssert(request4.parameters?.count == 4) XCTAssert(request4.parameters?["country"] as? String == "ES") XCTAssert(request4.parameters?["postal_code"] as? String == "35018") XCTAssert(request4.parameters?["vat_number"] as? String == "98765432X") XCTAssert(request4.parameters?["transaction_type"] as? String == "eservice") } func testThatTaxesCanBeCalculatedForEachTransactionTypes() { let transactionTypes: [Transaction.Category: String] = [ .service: "eservice", .book: "ebook", .standard: "standard", ] transactionTypes.forEach { category, expectedValue in let transaction = Transaction(country: "ES", category: category) let request = Tax.request(.calculate(for: transaction)) XCTAssert(request.parameters?["transaction_type"] as? String == expectedValue) } } func testThatTaxesCanBeValidated() { let request = Tax.request(.validate(vat: "98765432X", country: "ES")) XCTAssert(request.method == .get) XCTAssert(uri(for: request) == uri(byAppendingPathToBaseURL: "/taxes/validate.json")) XCTAssert(request.parameters?.count == 2) XCTAssert(request.parameters?["country"] as? String == "ES") XCTAssert(request.parameters?["vat_number"] as? String == "98765432X") } }
mit
0f93b07e8b1e9c35b8aa8c77b553412e
41.459641
138
0.604689
4.681582
false
true
false
false
jakarmy/swift-summary
The Swift Summary Book.playground/Pages/05 Control Flow.xcplaygroundpage/Contents.swift
1
2503
// |=------------------------------------------------------=| // Copyright (c) 2016 Juan Antonio Karmy. // Licensed under MIT License // // See https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/ for Swift Language Reference // // See Juan Antonio Karmy - http://karmy.co | http://twitter.com/jkarmy // // |=------------------------------------------------------=| //Index is implicitly declared for index in 1...5 { print("Index is \(index)") } //In this case, we don't care about the value. for _ in 1..<6 { print("No value") } //Use tuples let dictionary = ["one": 1, "two": 2, "three": 3] for (numberName, numberValue) in dictionary { print("\(numberName) is \(numberValue)") } //Go through a string var char = "e" for char in "Yes".characters { print("\(char)") } //Switches // No need for break, and every case must have some code. let someChar = "e" switch someChar { case "a", "e", "i", "o", "u": print("\(someChar) is a vowel") default: print("\(someChar) is a consonant") } //There can also be range matching let count = 3_000_000_000_000 let countedThings = "stars" switch count { case 0...9: print("a few") case 10...10_000: print("many") default: print("a lot of") } //Use tuples let coord = (1,1) switch coord { case (0,0): print("Origin") case (_, 0): print("x axis") case (0, _): print("y axis") case (-2...2, -3...3): print("within boundries") default: print("out of bounds") } //Value binding: Assign temp values to variables inside the cases. let anotherPoint = (0, 0) switch anotherPoint { case (let x, 0): print("on the y-axis with an x value of \(x)") case (0, let y): print("on the x-axis with a y value of \(y)") case let (z, w): //This acts as the default case. Since it is only assigning a tuple, any value matches. print("somewhere else at (\(z), \(w))") } // Bind both values, plus test a condition. switch anotherPoint { case let (x, y) where x == y: print("x = y : \(x) = \(y)") default: break } // The fallthrough line forces the switch statement to fall into the default case after a previous case. switch anotherPoint { case let (x, y) where x == y: print("x = y") fallthrough default: print(" are equal") } //Nesting while, for and switches can be confusing sometimes //Use labels to better use the break and continue statements master: while true { loop: for rats in 1...5{ continue master } }
mit
c3f70e391e5de8ca0225dc5bd4f4ae8b
21.348214
135
0.60847
3.346257
false
false
false
false
MichaelSelsky/TheBeatingAtTheGates
Carthage/Checkouts/VirtualGameController/Source/Framework/VgcMotion.swift
1
13922
// // VgcMotionManager.swift // // // Created by Rob Reuss on 10/4/15. // // import Foundation #if !(os(tvOS)) && !(os(OSX)) import CoreMotion public class VgcMotionManager: NSObject { #if os(iOS) private let elements = VgcManager.elements var controller: VgcController! #endif #if os(watchOS) public var watchConnectivity: VgcWatchConnectivity! public var elements: Elements! #endif public var deviceSupportsMotion: Bool! public let manager = CMMotionManager() public var active: Bool = false /// /// Don't enable these unless they are really needed because they produce /// tons of data to be transmitted and clog the channels. /// public var enableUserAcceleration = true public var enableRotationRate = true public var enableAttitude = true public var enableGravity = true public var enableLowPassFilter = true public var enableAdaptiveFilter = true public var cutOffFrequency: Double = 5.0 var filterConstant: Double! /// /// System can handle 60 updates/sec but only if a subset of motion factors are enabled, /// not all four. If all four inputs are needed, update frequency should be reduced. /// public var updateInterval = 1.0 / 60 { didSet { manager.deviceMotionUpdateInterval = updateInterval setupFilterConstant() } } func setupFilterConstant() { let dt = updateInterval let RC = 1.0 / cutOffFrequency filterConstant = dt / (dt + RC) } public func start() { #if os(iOS) || os(watchOS) vgcLogDebug("Attempting to start motion detection") #if os(iOS) if !deviceIsTypeOfBridge() { if VgcManager.peripheral.haveConnectionToCentral == false { vgcLogDebug("Not starting motion because no connection") return } } if VgcManager.appRole == .EnhancementBridge { if VgcController.enhancedController.peripheral.haveConnectionToCentral == false { vgcLogDebug("Not starting motion because no connection") return } } #endif // No need to start if already active if manager.deviceMotionActive { vgcLogDebug("Not starting motion because already active") return } vgcLogDebug("Device supports: \(self.deviceSupportsMotion), motion available: \(self.manager.deviceMotionAvailable), accelerometer available: \(self.manager.accelerometerAvailable)") if deviceIsTypeOfBridge() || self.deviceSupportsMotion == true { active = true // iOS supports device motion, but the watch only supports direct accelerometer data if self.manager.deviceMotionAvailable { setupFilterConstant() //let motionQueue = NSOperationQueue() vgcLogDebug("Starting device motion updating") manager.deviceMotionUpdateInterval = NSTimeInterval(updateInterval) manager.startDeviceMotionUpdatesToQueue(NSOperationQueue.mainQueue(), withHandler: { (deviceMotionData, error) -> Void in if error != nil { vgcLogDebug("Got device motion error: \(error)") } var x, y, z, w: Double // Send data on the custom accelerometer channels if self.enableAttitude { (x, y, z, w) = self.filterX(((deviceMotionData?.attitude.quaternion.x)!), y: ((deviceMotionData?.attitude.quaternion.y)!), z: ((deviceMotionData?.attitude.quaternion.z)!), w: ((deviceMotionData?.attitude.quaternion.w)!)) //vgcLogDebug("Old double: \(deviceMotionData?.attitude.quaternion.x), new float: \(x)") self.elements.motionAttitudeX.value = Float(x) self.elements.motionAttitudeY.value = Float(y) self.elements.motionAttitudeZ.value = Float(z) self.elements.motionAttitudeW.value = Float(w) self.sendElementState(self.elements.motionAttitudeY) self.sendElementState(self.elements.motionAttitudeX) self.sendElementState(self.elements.motionAttitudeZ) self.sendElementState(self.elements.motionAttitudeW) } // Send data on the custom accelerometer channels if self.enableUserAcceleration { (x, y, z, w) = self.filterX(((deviceMotionData?.userAcceleration.x)!), y: ((deviceMotionData?.userAcceleration.y)!), z: ((deviceMotionData?.userAcceleration.z)!), w: 0) self.elements.motionUserAccelerationX.value = Float(x) self.elements.motionUserAccelerationY.value = Float(y) self.elements.motionUserAccelerationZ.value = Float(z) self.sendElementState(self.elements.motionUserAccelerationX) self.sendElementState(self.elements.motionUserAccelerationY) self.sendElementState(self.elements.motionUserAccelerationZ) } // Gravity if self.enableGravity { (x, y, z, w) = self.filterX(((deviceMotionData?.gravity.x)!), y: ((deviceMotionData?.gravity.y)!), z: ((deviceMotionData?.gravity.z)!), w: 0) self.elements.motionGravityX.value = Float(x) self.elements.motionGravityY.value = Float(y) self.elements.motionGravityZ.value = Float(z) self.sendElementState(self.elements.motionGravityX) self.sendElementState(self.elements.motionGravityY) self.sendElementState(self.elements.motionGravityZ) } // Rotation Rate if self.enableRotationRate { (x, y, z, w) = self.filterX(((deviceMotionData?.rotationRate.x)!), y: ((deviceMotionData?.rotationRate.y)!), z: ((deviceMotionData?.rotationRate.z)!), w: 0) self.elements.motionRotationRateX.value = Float(x) self.elements.motionRotationRateY.value = Float(y) self.elements.motionRotationRateZ.value = Float(z) self.sendElementState(self.elements.motionRotationRateX) self.sendElementState(self.elements.motionRotationRateY) self.sendElementState(self.elements.motionRotationRateZ) } }) } else if self.manager.accelerometerAvailable { vgcLogDebug("Starting accelerometer detection (for the Watch)") self.manager.accelerometerUpdateInterval = NSTimeInterval(self.updateInterval) self.manager.startAccelerometerUpdatesToQueue(NSOperationQueue.mainQueue(), withHandler: { (accelerometerData, error) -> Void in /* //vgcLogDebug("Device Motion: \(deviceMotionData!)") motionAttitudeY.value = Float((deviceMotionData?.attitude.quaternion.y)!) motionAttitudeX.value = Float((deviceMotionData?.attitude.quaternion.x)!) motionAttitudeZ.value = Float((deviceMotionData?.attitude.quaternion.z)!) motionAttitudeW.value = Float((deviceMotionData?.attitude.quaternion.w)!) // Send data on the custom accelerometer channels if enableAttitude { self.sendElementValueToBridge(motionAttitudeY) self.sendElementValueToBridge(motionAttitudeX) self.sendElementValueToBridge(motionAttitudeZ) self.sendElementValueToBridge(motionAttitudeW) } */ self.elements.motionUserAccelerationX.value = Float((accelerometerData?.acceleration.x)!) self.elements.motionUserAccelerationY.value = Float((accelerometerData?.acceleration.y)!) self.elements.motionUserAccelerationZ.value = Float((accelerometerData?.acceleration.z)!) vgcLogDebug("Sending accelerometer: \(accelerometerData?.acceleration.x) \(accelerometerData?.acceleration.y) \(accelerometerData?.acceleration.z)") // Send data on the custom accelerometer channels //if VgcManager.peripheral.motion.enableUserAcceleration { self.sendElementState(self.elements.motionUserAccelerationX) self.sendElementState(self.elements.motionUserAccelerationY) self.sendElementState(self.elements.motionUserAccelerationZ) //} /* // Rotation Rate motionRotationRateX.value = Float((deviceMotionData?.rotationRate.x)!) motionRotationRateY.value = Float((deviceMotionData?.rotationRate.y)!) motionRotationRateZ.value = Float((deviceMotionData?.rotationRate.z)!) vgcLogDebug("Rotation: X \( Float((deviceMotionData?.rotationRate.x)!)), Y: \(Float((deviceMotionData?.rotationRate.y)!)), Z: \(Float((deviceMotionData?.rotationRate.z)!))") if enableRotationRate { self.sendElementValueToBridge(motionRotationRateX) self.sendElementValueToBridge(motionRotationRateY) self.sendElementValueToBridge(motionRotationRateZ) } // Gravity motionGravityX.value = Float((deviceMotionData?.gravity.x)!) motionGravityY.value = Float((deviceMotionData?.gravity.y)!) motionGravityZ.value = Float((deviceMotionData?.gravity.z)!) if enableGravity { self.sendElementValueToBridge(motionGravityX) self.sendElementValueToBridge(motionGravityY) self.sendElementValueToBridge(motionGravityZ) } */ }) } } #endif // End of block out of motion for tvOS and OSX } public func stop() { #if os(iOS) || os(watchOS) vgcLogDebug("Stopping motion detection") manager.stopDeviceMotionUpdates() active = false #endif } func sendElementState(element: Element) { #if os(iOS) if deviceIsTypeOfBridge() { controller.peripheral.sendElementState(element) } else { VgcManager.peripheral.sendElementState(element) } #endif #if os(watchOS) watchConnectivity.sendElementState(element) #endif } // Filter functions func Norm(x: Double, y: Double, z: Double) -> Double { return sqrt(x * x + y * y + z * z); } func Clamp(v: Double, min: Double, max: Double) -> Double { if(v > max) { return max } else if (v < min) { return min } else { return v } } let kAccelerometerMinStep = 0.02 let kAccelerometerNoiseAttenuation = 3.0 func filterX(x: Double, y: Double, z: Double, w: Double) -> (Double, Double, Double, Double) { if enableLowPassFilter { var alpha = filterConstant; if enableAdaptiveFilter { let d = Clamp(fabs(Norm(x, y: y, z: z) - Norm(x, y: y, z: z)) / kAccelerometerMinStep - 1.0, min: 0.0, max: 1.0) alpha = (1.0 - d) * filterConstant / kAccelerometerNoiseAttenuation + d * filterConstant } return (x * alpha + x * (1.0 - alpha), y * alpha + y * (1.0 - alpha), z * alpha + z * (1.0 - alpha), w) } else { return (x, y, z, w) } } } #endif
mit
e1ed13243c1f2629873f933d7c90b596
44.348534
248
0.507973
5.844668
false
false
false
false
hq7781/MoneyBook
MoneyBook/Controller/Record/AccountViewController.swift
1
2730
// // AccountViewController.swift // MoneyBook // // Created by HongQuan on 2017/05/01. // Copyright © 2017年 Roan.Hong. All rights reserved. // import UIKit let D_fromAccVC_name = "AccountVC" let k_CELLNAME_AccountTableViewCell: String = "cellChose" class AccountViewController: UIViewController { //MARK: - ========== var define ========== var delegate : RecordsViewControllerDelegate? = nil @IBOutlet var tableView: UITableView! //var data = DB.share().queryAccount() //MARK: - ========== override methods ========== 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: - ========== IBACtions ========== @IBAction func addAccountButton(_ sender: UIButton) { } /* // 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. } */ } /// MARK: - , UITableViewDelegate, UITableViewDataSource extension AccountViewController: UITableViewDelegate, UITableViewDataSource { //MARK: - ========== UITableViewDelegate ========== func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 6 //data.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: k_CELLNAME_AccountTableViewCell, for: indexPath) as? AccountTableViewCell cell?.imgAcc.image = nil //UIImage(named: data[indexPath.row].image) cell?.lblMoney.text = "Value" //"Value: \(data[indexPath.row].money) Yen" cell?.lblNameAcc.text = "name" // data[indexPath.row].nameAcc return cell! } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let indexPath = tableView.indexPathForSelectedRow // let currentCell = tableView.cellForRow(at: indexPath!)! as! AccountTableViewCell _ = tableView.cellForRow(at: indexPath!)! as! AccountTableViewCell } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return self.view.frame.size.height / 12 } }
mit
0934356cfcebaa9c0d0aec1e065ed781
33.961538
138
0.657499
4.843694
false
false
false
false
nicopuri/CrossNavigation
Swift/CrossNavigation/InteractiveTransition/Transioning/CNInteractiveTransition.swift
3
6325
// // CNInteractiveTransition.swift // CrossNavigationDemo // // Created by Nicolas Purita on 11/5/14. // // import UIKit class CNInteractiveTransition: UIPercentDrivenInteractiveTransition, UIViewControllerTransitioningDelegate { // private vars private var appearanceTransitioning: CNTransitioning? private var disappearanceTransitioning: CNTransitioning? private var transitionContext: UIViewControllerContextTransitioning? // read-only private(set) var fromViewController: CNViewController? private(set) var toViewController: CNViewController? private(set) var containerView: UIView? private(set) var recentPercentComplete: CGFloat = 0 // public var var interactive: Bool = true var finishingDuration: CGFloat = CGFloat(CNTransitioning().duration) var direction: CNDirection { didSet { self.appearanceTransitioning = CNTranstioningFactory.Transitioning(direction, present: true) self.disappearanceTransitioning = CNTranstioningFactory.Transitioning(direction, present: false) } } override init() { self.direction = .None } // MARK: Interactive Transtioning override func startInteractiveTransition(transitionContext: UIViewControllerContextTransitioning) -> () { self.transitionContext = transitionContext self.containerView = self.transitionContext!.containerView() let containerFrame = self.containerView!.bounds // from View Controller self.fromViewController = self.transitionContext!.viewControllerForKey(UITransitionContextFromViewControllerKey) as? CNViewController self.fromViewController!.view.frame = self.appearanceTransitioning!.fromViewStartFrameWithContainerFrame(containerFrame) self.containerView!.addSubview(self.fromViewController!.view) // to View Controller self.toViewController = self.transitionContext!.viewControllerForKey(UITransitionContextToViewControllerKey) as? CNViewController self.toViewController!.view.frame = self.appearanceTransitioning!.toViewStartFrameWithContainerFrame(containerFrame) self.containerView!.addSubview(self.toViewController!.view) } func updateinteractiveTransition(percentComplete: CGFloat) -> () { let containerFrame = self.containerView!.bounds // normalization var mutatedPercentComplete = percentComplete mutatedPercentComplete = max(0.0, mutatedPercentComplete) mutatedPercentComplete = min(1.0, mutatedPercentComplete) self.recentPercentComplete = mutatedPercentComplete // update fromViewController's frame self.fromViewController!.view.frame = CGRect.Transform(self.appearanceTransitioning!.fromViewStartFrameWithContainerFrame(containerFrame), finalRect: self.appearanceTransitioning!.fromViewEndFrameWithContainerFrame(containerFrame), rate: self.recentPercentComplete) // update toViewController's frame self.toViewController!.view.frame = CGRect.Transform(self.appearanceTransitioning!.toViewStartFrameWithContainerFrame(containerFrame), finalRect: self.appearanceTransitioning!.toViewEndFrameWithContainerFrame(containerFrame), rate: self.recentPercentComplete) } func finishInteractiveTranstion() -> () { self.finishInteractiveTransition(true) } func cancelInteractiveTranstion() -> () { self.finishInteractiveTransition(false) } // MARK: Private methods private func finishInteractiveTransition(didComplete: Bool) -> () { if let containerFrame = self.containerView?.bounds { let transform = self.containerView!.transform let duration: NSTimeInterval = NSTimeInterval(self.finishingDuration) UIView.animateWithDuration(duration, animations: { () -> Void in if didComplete { self.fromViewController!.view.frame = self.appearanceTransitioning!.fromViewEndFrameWithContainerFrame(containerFrame) self.toViewController!.view.frame = self.appearanceTransitioning!.toViewEndFrameWithContainerFrame(containerFrame) } else { self.fromViewController!.view.frame = self.appearanceTransitioning!.fromViewStartFrameWithContainerFrame(containerFrame) self.toViewController!.view.frame = self.appearanceTransitioning!.toViewStartFrameWithContainerFrame(containerFrame) } }) { (completion: Bool) -> Void in self.transitionContext!.completeTransition(didComplete) self.transitionContext = nil self.containerView = nil if didComplete { self.toViewController!.view.transform = transform self.toViewController!.view.frame = self.toViewController!.view.superview!.bounds } else { self.fromViewController!.view.transform = transform self.fromViewController!.view.frame = self.fromViewController!.view.superview!.bounds } } } } // MARK: UIViewControllerTransitioningDelegate func animationControllerForPresentedController(presented: UIViewController, presentingController presenting: UIViewController, sourceController source: UIViewController) -> UIViewControllerAnimatedTransitioning? { return self.appearanceTransitioning } func animationControllerForDismissedController(dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? { return self.disappearanceTransitioning } func interactionControllerForPresentation(animator: UIViewControllerAnimatedTransitioning) -> UIViewControllerInteractiveTransitioning? { return self.interactive ? self : nil } func interactionControllerForDismissal(animator: UIViewControllerAnimatedTransitioning) -> UIViewControllerInteractiveTransitioning? { return self.interactive ? self : nil } }
mit
e4ccd0d5796c7a225a4bcbd5d9092a7b
44.503597
217
0.694545
6.414807
false
false
false
false
richard92m/three.bar
ThreeBar/ThreeBar/Laser.swift
1
1290
// // Laser.swift // ThreeBar // // Created by Marquez, Richard A on 12/18/14. // Copyright (c) 2014 Richard Marquez. All rights reserved. // import Foundation import SpriteKit class Laser: Projectile { init() { super.init(sprite: _magic.get("laserSprite") as String, size: _magic.get("laserSize") as CGFloat) zPosition = CGFloat(ZIndex.Laser.rawValue) name = "laserNode" physicsBody?.categoryBitMask = PhysicsCategory.Laser } func move() { let magicDistance = _magic.get("projectileDistance") as CGFloat let magicSpeed = NSTimeInterval(_magic.get("projectileSpeed") as Float) let moveAction = moveActionInDirection(facing, distance: magicDistance, speed: magicSpeed) runAction(moveAction) } func comeBack(hero: Hero) { physicsBody?.categoryBitMask = PhysicsCategory.ReturnLaser texture = SKTexture(imageNamed: _magic.get("laserBackSprite") as String) moveBack(hero) } func moveBack(hero: Hero) { facing = (hero.position - position).normalized() move() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
gpl-3.0
a7f71995c5ccfb02bf96a36f58b259d4
25.346939
105
0.620155
4.328859
false
false
false
false
KittenYang/A-GUIDE-TO-iOS-ANIMATION
Swift Version/DynamicActionBlockDemo-Swift/DynamicActionBlockDemo-Swift/DynamicView.swift
1
7324
// // DynamicView.swift // DynamicActionBlockDemo-Swift // // Created by Kitten Yang on 1/2/16. // Copyright © 2016 Kitten Yang. All rights reserved. // import UIKit class DynamicView: UIView { private var panView: UIView? private var ballImageView: UIImageView? private var topView: UIView? private var middleView: UIView? private var bottomView: UIView? private var animator: UIDynamicAnimator? private var panGravity: UIGravityBehavior? private var viewsGravity: UIGravityBehavior? private var shapeLayer: CAShapeLayer? override init(frame: CGRect) { super.init(frame: frame) setUpViews() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } private func setUpViews(){ panView = UIView(frame: CGRect(x: 0, y: 0, width: bounds.width, height: bounds.height/2)) panView?.alpha = 0.5 addSubview(panView!) panView?.layer.shadowOffset = CGSize(width: -1, height: 2) panView?.layer.shadowOpacity = 0.5 panView?.layer.shadowRadius = 5.0 panView?.layer.shadowColor = UIColor.blackColor().CGColor panView?.layer.masksToBounds = false panView?.layer.shadowPath = UIBezierPath(rect: (panView?.bounds)!).CGPath let pan = UIPanGestureRecognizer(target: self, action: "handlePanGesture:") panView?.addGestureRecognizer(pan) let grd = CAGradientLayer() grd.frame = (panView?.frame)! grd.colors = [UIColor(red: 0.0, green: 191/255.0, blue: 255/255.0, alpha: 1.0).CGColor,UIColor.whiteColor().CGColor] panView?.layer.addSublayer(grd) ballImageView = UIImageView(frame: CGRect(x: bounds.width/2 - 30, y: bounds.height/1.5, width: 60, height: 60)) ballImageView?.image = UIImage(named: "ball") addSubview(ballImageView!) ballImageView?.layer.shadowOffset = CGSize(width: -4, height: 4) ballImageView?.layer.shadowOpacity = 0.5 ballImageView?.layer.shadowRadius = 5.0 ballImageView?.layer.shadowColor = UIColor.blackColor().CGColor ballImageView?.layer.masksToBounds = false // middleView middleView = UIView(frame: CGRect(x: (ballImageView?.center.x)!-15, y: 200, width: 30, height: 30)) middleView?.backgroundColor = UIColor.grayColor() addSubview(middleView!) middleView?.center = CGPoint(x: (middleView?.center.x)!, y: (ballImageView?.center.y)! - (panView?.center.y)! + 15) // topView topView = UIView(frame: CGRect(x: (ballImageView?.center.x)! - 15, y: 200, width: 30, height: 30)) topView?.backgroundColor = UIColor.grayColor() addSubview(topView!) topView?.center = CGPoint(x: (topView?.center.x)!, y: (middleView?.center.y)! - (panView?.center.y)! + (panView?.center.y)!/2) // bottomView bottomView = UIView(frame: CGRect(x: (ballImageView?.center.x)! - 15, y: 200, width: 30, height: 30)) bottomView?.backgroundColor = UIColor.grayColor() addSubview(bottomView!) bottomView?.center = CGPoint(x: (bottomView?.center.x)!, y: (middleView?.center.y)! - (panView?.center.y)! + (panView?.center.y)! * 1.5) setUpBehaviors() } private func setUpBehaviors(){ animator = UIDynamicAnimator(referenceView: self) panGravity = UIGravityBehavior(items: [panView!]) animator?.addBehavior(panGravity!) viewsGravity = UIGravityBehavior(items: [ballImageView!,topView!,bottomView!]) animator?.addBehavior(viewsGravity!) viewsGravity?.action = { [weak self] () in print("Acton!") if let strongSelf = self{ let path = UIBezierPath() path.moveToPoint((strongSelf.panView?.center)!) path.addCurveToPoint((strongSelf.ballImageView?.center)!, controlPoint1: (strongSelf.topView?.center)!, controlPoint2: (strongSelf.bottomView?.center)!) if strongSelf.shapeLayer == nil{ strongSelf.shapeLayer = CAShapeLayer() strongSelf.shapeLayer?.fillColor = UIColor.clearColor().CGColor strongSelf.shapeLayer?.strokeColor = UIColor(red: 224.0/255.0, green: 0.0, blue: 35.0/255.0, alpha: 1.0).CGColor strongSelf.shapeLayer?.lineWidth = 5.0 strongSelf.shapeLayer?.shadowOffset = CGSize(width: -1, height: 2) strongSelf.shapeLayer?.shadowOpacity = 0.5 strongSelf.shapeLayer?.shadowRadius = 5.0 strongSelf.shapeLayer?.shadowColor = UIColor.blackColor().CGColor strongSelf.shapeLayer?.masksToBounds = false strongSelf.layer.insertSublayer(strongSelf.shapeLayer!, below: strongSelf.ballImageView?.layer) } strongSelf.shapeLayer?.path = path.CGPath } } // MARK : UICollisionBehavior let collision = UICollisionBehavior(items: [panView!]) collision.addBoundaryWithIdentifier("Left", fromPoint: CGPoint(x: -1, y: 0), toPoint: CGPoint(x: -1, y: bounds.size.height)) collision.addBoundaryWithIdentifier("Right", fromPoint: CGPoint(x: bounds.width+1, y: 0), toPoint:CGPoint(x: bounds.width+1, y: bounds.height)) collision.addBoundaryWithIdentifier("Middle", fromPoint: CGPoint(x: 0, y: bounds.height/2), toPoint: CGPoint(x: bounds.width, y: bounds.height/2)) animator?.addBehavior(collision) // MARK : UIAttachmentBehaviors let attach1 = UIAttachmentBehavior(item: panView!, attachedToItem: topView!) animator?.addBehavior(attach1) let attach2 = UIAttachmentBehavior(item: topView!, attachedToItem: bottomView!) animator?.addBehavior(attach2) let attach3 = UIAttachmentBehavior(item: bottomView!, offsetFromCenter: UIOffset(horizontal: 0, vertical: 0), attachedToItem: ballImageView!, offsetFromCenter: UIOffset(horizontal: 0, vertical: -ballImageView!.bounds.height/2)) animator?.addBehavior(attach3) // MARK : UIDynamicItemBehavior let panItem = UIDynamicItemBehavior(items: [panView!,topView!,bottomView!,ballImageView!]) panItem.elasticity = 0.5 animator?.addBehavior(panItem) } @objc private func handlePanGesture(gesture: UIPanGestureRecognizer){ let translation = gesture.translationInView(gesture.view) if !((gesture.view?.center.y)! + translation.y > bounds.height/2 - (gesture.view?.bounds.height)!/2){ gesture.view?.center = CGPoint(x: (gesture.view?.center.x)!, y: (gesture.view?.center.y)! + translation.y) gesture.setTranslation(CGPoint(x:0, y:0), inView: gesture.view) } if let animator = animator{ switch gesture.state { case .Began: animator.removeBehavior(panGravity!) case .Changed:break; case .Ended: animator.addBehavior(panGravity!) default:break } animator.updateItemUsingCurrentState(gesture.view!) } } }
gpl-2.0
2f78b37907eb68e99eb98b93ec741671
45.348101
235
0.629523
4.537175
false
false
false
false
yahua/YAHCharts
Source/Charts/Renderers/LineChartRenderer.swift
1
27668
// // LineChartRenderer.swift // Charts // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/Charts // import Foundation import CoreGraphics #if !os(OSX) import UIKit #endif open class LineChartRenderer: LineRadarRenderer { open weak var dataProvider: LineChartDataProvider? public init(dataProvider: LineChartDataProvider?, animator: Animator?, viewPortHandler: ViewPortHandler?) { super.init(animator: animator, viewPortHandler: viewPortHandler) self.dataProvider = dataProvider } open override func drawData(context: CGContext) { guard let lineData = dataProvider?.lineData else { return } for i in 0 ..< lineData.dataSetCount { guard let set = lineData.getDataSetByIndex(i) else { continue } if set.isVisible { if !(set is ILineChartDataSet) { fatalError("Datasets for LineChartRenderer must conform to ILineChartDataSet") } drawDataSet(context: context, dataSet: set as! ILineChartDataSet) } } } open func drawDataSet(context: CGContext, dataSet: ILineChartDataSet) { if dataSet.entryCount < 1 { return } context.saveGState() context.setLineWidth(dataSet.lineWidth) if dataSet.lineDashLengths != nil { context.setLineDash(phase: dataSet.lineDashPhase, lengths: dataSet.lineDashLengths!) } else { context.setLineDash(phase: 0.0, lengths: []) } // if drawing cubic lines is enabled switch dataSet.mode { case .linear: fallthrough case .stepped: drawLinear(context: context, dataSet: dataSet) case .cubicBezier: drawCubicBezier(context: context, dataSet: dataSet) case .horizontalBezier: drawHorizontalBezier(context: context, dataSet: dataSet) } context.restoreGState() } open func drawCubicBezier(context: CGContext, dataSet: ILineChartDataSet) { guard let dataProvider = dataProvider, let animator = animator else { return } let trans = dataProvider.getTransformer(forAxis: dataSet.axisDependency) let phaseY = animator.phaseY _xBounds.set(chart: dataProvider, dataSet: dataSet, animator: animator) // get the color that is specified for this position from the DataSet let drawingColor = dataSet.colors.first! let intensity = dataSet.cubicIntensity // the path for the cubic-spline let cubicPath = CGMutablePath() let valueToPixelMatrix = trans.valueToPixelMatrix if _xBounds.range >= 1 { var prevDx: CGFloat = 0.0 var prevDy: CGFloat = 0.0 var curDx: CGFloat = 0.0 var curDy: CGFloat = 0.0 // Take an extra point from the left, and an extra from the right. // That's because we need 4 points for a cubic bezier (cubic=4), otherwise we get lines moving and doing weird stuff on the edges of the chart. // So in the starting `prev` and `cur`, go -2, -1 // And in the `lastIndex`, add +1 var firstIndex = _xBounds.min + 1 var lastIndex = _xBounds.min + _xBounds.range if dataSet.removeFirstEnd { firstIndex += 1 lastIndex -= 1; } var prevPrev: ChartDataEntry! = nil var prev: ChartDataEntry! = dataSet.entryForIndex(max(firstIndex - 2, 0)) var cur: ChartDataEntry! = dataSet.entryForIndex(max(firstIndex - 1, 0)) var next: ChartDataEntry! = cur var nextIndex: Int = -1 if cur == nil { return } // let the spline start cubicPath.move(to: CGPoint(x: CGFloat(cur.x), y: CGFloat(cur.y * phaseY)), transform: valueToPixelMatrix) for j in stride(from: firstIndex, through: lastIndex, by: 1) { prevPrev = prev prev = cur cur = nextIndex == j ? next : dataSet.entryForIndex(j) nextIndex = j + 1 < dataSet.entryCount ? j + 1 : j next = dataSet.entryForIndex(nextIndex) if next == nil { break } prevDx = CGFloat(cur.x - prevPrev.x) * intensity prevDy = CGFloat(cur.y - prevPrev.y) * intensity curDx = CGFloat(next.x - prev.x) * intensity curDy = CGFloat(next.y - prev.y) * intensity cubicPath.addCurve( to: CGPoint( x: CGFloat(cur.x), y: CGFloat(cur.y) * CGFloat(phaseY)), control1: CGPoint( x: CGFloat(prev.x) + prevDx, y: (CGFloat(prev.y) + prevDy) * CGFloat(phaseY)), control2: CGPoint( x: CGFloat(cur.x) - curDx, y: (CGFloat(cur.y) - curDy) * CGFloat(phaseY)), transform: valueToPixelMatrix) } } context.saveGState() if dataSet.isDrawFilledEnabled { // Copy this path because we make changes to it let fillPath = cubicPath.mutableCopy() drawCubicFill(context: context, dataSet: dataSet, spline: fillPath!, matrix: valueToPixelMatrix, bounds: _xBounds) } context.beginPath() context.addPath(cubicPath) context.setStrokeColor(drawingColor.cgColor) context.strokePath() context.restoreGState() } open func drawHorizontalBezier(context: CGContext, dataSet: ILineChartDataSet) { guard let dataProvider = dataProvider, let animator = animator else { return } let trans = dataProvider.getTransformer(forAxis: dataSet.axisDependency) let phaseY = animator.phaseY _xBounds.set(chart: dataProvider, dataSet: dataSet, animator: animator) // get the color that is specified for this position from the DataSet let drawingColor = dataSet.colors.first! // the path for the cubic-spline let cubicPath = CGMutablePath() let valueToPixelMatrix = trans.valueToPixelMatrix if _xBounds.range >= 1 { var prev: ChartDataEntry! = dataSet.entryForIndex(_xBounds.min) var cur: ChartDataEntry! = prev if cur == nil { return } // let the spline start cubicPath.move(to: CGPoint(x: CGFloat(cur.x), y: CGFloat(cur.y * phaseY)), transform: valueToPixelMatrix) for j in stride(from: (_xBounds.min + 1), through: _xBounds.range + _xBounds.min, by: 1) { prev = cur cur = dataSet.entryForIndex(j) let cpx = CGFloat(prev.x + (cur.x - prev.x) / 2.0) cubicPath.addCurve( to: CGPoint( x: CGFloat(cur.x), y: CGFloat(cur.y * phaseY)), control1: CGPoint( x: cpx, y: CGFloat(prev.y * phaseY)), control2: CGPoint( x: cpx, y: CGFloat(cur.y * phaseY)), transform: valueToPixelMatrix) } } context.saveGState() if dataSet.isDrawFilledEnabled { // Copy this path because we make changes to it let fillPath = cubicPath.mutableCopy() drawCubicFill(context: context, dataSet: dataSet, spline: fillPath!, matrix: valueToPixelMatrix, bounds: _xBounds) } context.beginPath() context.addPath(cubicPath) context.setStrokeColor(drawingColor.cgColor) context.strokePath() context.restoreGState() } open func drawCubicFill( context: CGContext, dataSet: ILineChartDataSet, spline: CGMutablePath, matrix: CGAffineTransform, bounds: XBounds) { guard let dataProvider = dataProvider else { return } if bounds.range <= 0 { return } let fillMin = dataSet.fillFormatter?.getFillLinePosition(dataSet: dataSet, dataProvider: dataProvider) ?? 0.0 var pt1 = CGPoint(x: CGFloat(dataSet.entryForIndex(bounds.min + bounds.range)?.x ?? 0.0), y: fillMin) var pt2 = CGPoint(x: CGFloat(dataSet.entryForIndex(bounds.min)?.x ?? 0.0), y: fillMin) pt1 = pt1.applying(matrix) pt2 = pt2.applying(matrix) spline.addLine(to: pt1) spline.addLine(to: pt2) spline.closeSubpath() if dataSet.fill != nil { drawFilledPath(context: context, path: spline, fill: dataSet.fill!, fillAlpha: dataSet.fillAlpha) } else { drawFilledPath(context: context, path: spline, fillColor: dataSet.fillColor, fillAlpha: dataSet.fillAlpha) } } fileprivate var _lineSegments = [CGPoint](repeating: CGPoint(), count: 2) open func drawLinear(context: CGContext, dataSet: ILineChartDataSet) { guard let dataProvider = dataProvider, let animator = animator, let viewPortHandler = self.viewPortHandler else { return } let trans = dataProvider.getTransformer(forAxis: dataSet.axisDependency) let valueToPixelMatrix = trans.valueToPixelMatrix let entryCount = dataSet.entryCount let isDrawSteppedEnabled = dataSet.mode == .stepped let pointsPerEntryPair = isDrawSteppedEnabled ? 4 : 2 let phaseY = animator.phaseY _xBounds.set(chart: dataProvider, dataSet: dataSet, animator: animator) // if drawing filled is enabled if dataSet.isDrawFilledEnabled && entryCount > 0 { drawLinearFill(context: context, dataSet: dataSet, trans: trans, bounds: _xBounds) } context.saveGState() context.setLineCap(dataSet.lineCapType) // more than 1 color if dataSet.colors.count > 1 { if _lineSegments.count != pointsPerEntryPair { // Allocate once in correct size _lineSegments = [CGPoint](repeating: CGPoint(), count: pointsPerEntryPair) } for j in stride(from: _xBounds.min, through: _xBounds.range + _xBounds.min, by: 1) { var e: ChartDataEntry! = dataSet.entryForIndex(j) if e == nil { continue } _lineSegments[0].x = CGFloat(e.x) _lineSegments[0].y = CGFloat(e.y * phaseY) if j < _xBounds.max { e = dataSet.entryForIndex(j + 1) if e == nil { break } if isDrawSteppedEnabled { _lineSegments[1] = CGPoint(x: CGFloat(e.x), y: _lineSegments[0].y) _lineSegments[2] = _lineSegments[1] _lineSegments[3] = CGPoint(x: CGFloat(e.x), y: CGFloat(e.y * phaseY)) } else { _lineSegments[1] = CGPoint(x: CGFloat(e.x), y: CGFloat(e.y * phaseY)) } } else { _lineSegments[1] = _lineSegments[0] } for i in 0..<_lineSegments.count { _lineSegments[i] = _lineSegments[i].applying(valueToPixelMatrix) } if (!viewPortHandler.isInBoundsRight(_lineSegments[0].x)) { break } // make sure the lines don't do shitty things outside bounds if !viewPortHandler.isInBoundsLeft(_lineSegments[1].x) || (!viewPortHandler.isInBoundsTop(_lineSegments[0].y) && !viewPortHandler.isInBoundsBottom(_lineSegments[1].y)) { continue } // get the color that is set for this line-segment context.setStrokeColor(dataSet.color(atIndex: j).cgColor) context.strokeLineSegments(between: _lineSegments) } } else { // only one color per dataset var e1: ChartDataEntry! var e2: ChartDataEntry! e1 = dataSet.entryForIndex(_xBounds.min) if e1 != nil { context.beginPath() var firstPoint = true for x in stride(from: _xBounds.min, through: _xBounds.range + _xBounds.min, by: 1) { e1 = dataSet.entryForIndex(x == 0 ? 0 : (x - 1)) e2 = dataSet.entryForIndex(x) if e1 == nil || e2 == nil { continue } let pt = CGPoint( x: CGFloat(e1.x), y: CGFloat(e1.y * phaseY) ).applying(valueToPixelMatrix) if firstPoint { context.move(to: pt) firstPoint = false } else { context.addLine(to: pt) } if isDrawSteppedEnabled { context.addLine(to: CGPoint( x: CGFloat(e2.x), y: CGFloat(e1.y * phaseY) ).applying(valueToPixelMatrix)) } context.addLine(to: CGPoint( x: CGFloat(e2.x), y: CGFloat(e2.y * phaseY) ).applying(valueToPixelMatrix)) } if !firstPoint { context.setStrokeColor(dataSet.color(atIndex: 0).cgColor) context.strokePath() } } } context.restoreGState() } open func drawLinearFill(context: CGContext, dataSet: ILineChartDataSet, trans: Transformer, bounds: XBounds) { guard let dataProvider = dataProvider else { return } let filled = generateFilledPath( dataSet: dataSet, fillMin: dataSet.fillFormatter?.getFillLinePosition(dataSet: dataSet, dataProvider: dataProvider) ?? 0.0, bounds: bounds, matrix: trans.valueToPixelMatrix) if dataSet.fill != nil { drawFilledPath(context: context, path: filled, fill: dataSet.fill!, fillAlpha: dataSet.fillAlpha) } else { drawFilledPath(context: context, path: filled, fillColor: dataSet.fillColor, fillAlpha: dataSet.fillAlpha) } } /// Generates the path that is used for filled drawing. fileprivate func generateFilledPath(dataSet: ILineChartDataSet, fillMin: CGFloat, bounds: XBounds, matrix: CGAffineTransform) -> CGPath { let phaseY = animator?.phaseY ?? 1.0 let isDrawSteppedEnabled = dataSet.mode == .stepped let matrix = matrix var e: ChartDataEntry! let filled = CGMutablePath() e = dataSet.entryForIndex(bounds.min) if e != nil { filled.move(to: CGPoint(x: CGFloat(e.x), y: fillMin), transform: matrix) filled.addLine(to: CGPoint(x: CGFloat(e.x), y: CGFloat(e.y * phaseY)), transform: matrix) } // create a new path for x in stride(from: (bounds.min + 1), through: bounds.range + bounds.min, by: 1) { guard let e = dataSet.entryForIndex(x) else { continue } if isDrawSteppedEnabled { guard let ePrev = dataSet.entryForIndex(x-1) else { continue } filled.addLine(to: CGPoint(x: CGFloat(e.x), y: CGFloat(ePrev.y * phaseY)), transform: matrix) } filled.addLine(to: CGPoint(x: CGFloat(e.x), y: CGFloat(e.y * phaseY)), transform: matrix) } // close up e = dataSet.entryForIndex(bounds.range + bounds.min) if e != nil { filled.addLine(to: CGPoint(x: CGFloat(e.x), y: fillMin), transform: matrix) } filled.closeSubpath() return filled } open override func drawValues(context: CGContext) { guard let dataProvider = dataProvider, let lineData = dataProvider.lineData, let animator = animator, let viewPortHandler = self.viewPortHandler else { return } if isDrawingValuesAllowed(dataProvider: dataProvider) { var dataSets = lineData.dataSets let phaseY = animator.phaseY var pt = CGPoint() for i in 0 ..< dataSets.count { guard let dataSet = dataSets[i] as? ILineChartDataSet else { continue } if !shouldDrawValues(forDataSet: dataSet) { continue } let valueFont = dataSet.valueFont guard let formatter = dataSet.valueFormatter else { continue } let trans = dataProvider.getTransformer(forAxis: dataSet.axisDependency) let valueToPixelMatrix = trans.valueToPixelMatrix let iconsOffset = dataSet.iconsOffset // make sure the values do not interfear with the circles var valOffset = Int(dataSet.circleRadius * 1.75) if !dataSet.isDrawCirclesEnabled { valOffset = valOffset / 2 } _xBounds.set(chart: dataProvider, dataSet: dataSet, animator: animator) for j in stride(from: _xBounds.min, through: min(_xBounds.min + _xBounds.range, _xBounds.max), by: 1) { guard let e = dataSet.entryForIndex(j) else { break } pt.x = CGFloat(e.x) pt.y = CGFloat(e.y * phaseY) pt = pt.applying(valueToPixelMatrix) if (!viewPortHandler.isInBoundsRight(pt.x)) { break } if (!viewPortHandler.isInBoundsLeft(pt.x) || !viewPortHandler.isInBoundsY(pt.y)) { continue } if dataSet.isDrawValuesEnabled { ChartUtils.drawText( context: context, text: formatter.stringForValue( e.y, entry: e, dataSetIndex: i, viewPortHandler: viewPortHandler), point: CGPoint( x: pt.x, y: pt.y - CGFloat(valOffset) - valueFont.lineHeight), align: .center, attributes: [NSFontAttributeName: valueFont, NSForegroundColorAttributeName: dataSet.valueTextColorAt(j)]) } if let icon = e.icon, dataSet.isDrawIconsEnabled { ChartUtils.drawImage(context: context, image: icon, x: pt.x + iconsOffset.x, y: pt.y + iconsOffset.y, size: icon.size) } } } } } open override func drawExtras(context: CGContext) { drawCircles(context: context) } fileprivate func drawCircles(context: CGContext) { guard let dataProvider = dataProvider, let lineData = dataProvider.lineData, let animator = animator, let viewPortHandler = self.viewPortHandler else { return } let phaseY = animator.phaseY let dataSets = lineData.dataSets var pt = CGPoint() var rect = CGRect() context.saveGState() for i in 0 ..< dataSets.count { guard let dataSet = lineData.getDataSetByIndex(i) as? ILineChartDataSet else { continue } if !dataSet.isVisible || !dataSet.isDrawCirclesEnabled || dataSet.entryCount == 0 { continue } let trans = dataProvider.getTransformer(forAxis: dataSet.axisDependency) let valueToPixelMatrix = trans.valueToPixelMatrix _xBounds.set(chart: dataProvider, dataSet: dataSet, animator: animator) let circleRadius = dataSet.circleRadius let circleDiameter = circleRadius * 2.0 let circleHoleRadius = dataSet.circleHoleRadius let circleHoleDiameter = circleHoleRadius * 2.0 let drawCircleHole = dataSet.isDrawCircleHoleEnabled && circleHoleRadius < circleRadius && circleHoleRadius > 0.0 let drawTransparentCircleHole = drawCircleHole && (dataSet.circleHoleColor == nil || dataSet.circleHoleColor == NSUIColor.clear) for j in stride(from: _xBounds.min, through: _xBounds.range + _xBounds.min, by: 1) { guard let e = dataSet.entryForIndex(j) else { break } pt.x = CGFloat(e.x) pt.y = CGFloat(e.y * phaseY) pt = pt.applying(valueToPixelMatrix) if (!viewPortHandler.isInBoundsRight(pt.x)) { break } // make sure the circles don't do shitty things outside bounds if (!viewPortHandler.isInBoundsLeft(pt.x) || !viewPortHandler.isInBoundsY(pt.y)) { continue } context.setFillColor(dataSet.getCircleColor(atIndex: j)!.cgColor) rect.origin.x = pt.x - circleRadius rect.origin.y = pt.y - circleRadius rect.size.width = circleDiameter rect.size.height = circleDiameter if drawTransparentCircleHole { // Begin path for circle with hole context.beginPath() context.addEllipse(in: rect) // Cut hole in path rect.origin.x = pt.x - circleHoleRadius rect.origin.y = pt.y - circleHoleRadius rect.size.width = circleHoleDiameter rect.size.height = circleHoleDiameter context.addEllipse(in: rect) // Fill in-between context.fillPath(using: .evenOdd) } else { context.fillEllipse(in: rect) if drawCircleHole { context.setFillColor(dataSet.circleHoleColor!.cgColor) // The hole rect rect.origin.x = pt.x - circleHoleRadius rect.origin.y = pt.y - circleHoleRadius rect.size.width = circleHoleDiameter rect.size.height = circleHoleDiameter context.fillEllipse(in: rect) } } } } context.restoreGState() } open override func drawHighlighted(context: CGContext, indices: [Highlight]) { guard let dataProvider = dataProvider, let lineData = dataProvider.lineData, let animator = animator else { return } let chartXMax = dataProvider.chartXMax context.saveGState() for high in indices { guard let set = lineData.getDataSetByIndex(high.dataSetIndex) as? ILineChartDataSet , set.isHighlightEnabled else { continue } guard let e = set.entryForXValue(high.x, closestToY: high.y) else { continue } if !isInBoundsX(entry: e, dataSet: set) { continue } context.setStrokeColor(set.highlightColor.cgColor) context.setLineWidth(set.highlightLineWidth) if set.highlightLineDashLengths != nil { context.setLineDash(phase: set.highlightLineDashPhase, lengths: set.highlightLineDashLengths!) } else { context.setLineDash(phase: 0.0, lengths: []) } let x = high.x // get the x-position let y = high.y * Double(animator.phaseY) if x > chartXMax * animator.phaseX { continue } let trans = dataProvider.getTransformer(forAxis: set.axisDependency) let pt = trans.pixelForValues(x: x, y: y) high.setDraw(pt: pt) // draw the lines drawHighlightLines(context: context, point: pt, set: set) } context.restoreGState() } }
mit
ec9078d15088b504e7cdc9527fabbbaf
34.793014
155
0.487278
5.7762
false
false
false
false
tokyovigilante/CesiumKit
CesiumKit/Core/GeometryAttribute.swift
1
5183
// // GeometryAttribute.swift // CesiumKit // // Created by Ryan Walklin on 21/06/14. // Copyright (c) 2014 Test Toast. All rights reserved. // import Foundation /** * Values and type information for geometry attributes. A {@link Geometry} * generally contains one or more attributes. All attributes together form * the geometry's vertices. * * @alias GeometryAttribute * @constructor * * @param {Object} [options] Object with the following properties: * @param {ComponentDatatype} [options.componentDatatype] The datatype of each component in the attribute, e.g., individual elements in values. * @param {Number} [options.componentsPerAttribute] A number between 1 and 4 that defines the number of components in an attributes. * @param {Boolean} [options.normalize=false] When <code>true</code> and <code>componentDatatype</code> is an integer format, indicate that the components should be mapped to the range [0, 1] (unsigned) or [-1, 1] (signed) when they are accessed as floating-point for rendering. * @param {Number[TypedArray]} [options.values] The values for the attributes stored in a typed array. * * @exception {DeveloperError} options.componentsPerAttribute must be between 1 and 4. * * @see Geometry * * @example * var geometry = new Cesium.Geometry({ * attributes : { * position : new Cesium.GeometryAttribute({ * componentDatatype : Cesium.ComponentDatatype.FLOAT, * componentsPerAttribute : 3, * values : new Float32Array([ * 0.0, 0.0, 0.0, * 7500000.0, 0.0, 0.0, * 0.0, 7500000.0, 0.0 * ] * }) * }, * primitiveType : Cesium.PrimitiveType.LINE_LOOP * }); */ class GeometryAttribute { /** * The datatype of each component in the attribute, e.g., individual elements in * {@link GeometryAttribute#values}. * * @type ComponentDatatype * * @default undefined */ var componentDatatype: ComponentDatatype /** * A number between 1 and 4 that defines the number of components in an attributes. * For example, a position attribute with x, y, and z components would have 3 as * shown in the code example. * * @type Number * * @default undefined * * @example * attribute.componentDatatype : Cesium.ComponentDatatype.FLOAT, * attribute.componentsPerAttribute : 3, * attribute.values = new Float32Array([ * 0.0, 0.0, 0.0, * 7500000.0, 0.0, 0.0, * 0.0, 7500000.0, 0.0 * ]); */ var componentsPerAttribute: Int { didSet { assert(componentsPerAttribute >= 1 && componentsPerAttribute <= 4,"options.componentsPerAttribute must be between 1 and 4") } } /** * When <code>true</code> and <code>componentDatatype</code> is an integer format, * indicate that the components should be mapped to the range [0, 1] (unsigned) * or [-1, 1] (signed) when they are accessed as floating-point for rendering. * <p> * var is commonly used when storing colors using {@link ComponentDatatype.UNSIGNED_BYTE}. * </p> * * @type Boolean * * @default false * * @example * attribute.componentDatatype : Cesium.ComponentDatatype.UNSIGNED_BYTE, * attribute.componentsPerAttribute : 4, * attribute.normalize = true; * attribute.values = new Uint8Array([ * Cesium.Color.floatToByte(color.red) * Cesium.Color.floatToByte(color.green) * Cesium.Color.floatToByte(color.blue) * Cesium.Color.floatToByte(color.alpha) * ]); */ var normalize: Bool = false /** * The values for the attributes stored in a typed array. In the code example, * every three elements in <code>values</code> defines one attributes since * <code>componentsPerAttribute</code> is 3. * * @type Array * * @default undefined * * @example * attribute.componentDatatype : Cesium.ComponentDatatype.FLOAT, * attribute.componentsPerAttribute : 3, * attribute.values = new Float32Array([ * 0.0, 0.0, 0.0, * 7500000.0, 0.0, 0.0, * 0.0, 7500000.0, 0.0 * ]); */ var values: Buffer? = nil /** Optional name for custom attributes */ var name: String var vertexCount: Int { if values == nil { return 0 } return values!.count / componentsPerAttribute } var vertexArraySize: Int { if values == nil { return 0 } return values!.length } /** Gets individual attribute size in bytes. - returns: Attribute size */ var size: Int { return componentDatatype.elementSize * componentsPerAttribute } init(componentDatatype: ComponentDatatype, componentsPerAttribute: Int, normalize: Bool = false, values: Buffer? = nil) { assert(componentsPerAttribute >= 1 && componentsPerAttribute <= 4,"options.componentsPerAttribute must be between 1 and 4") self.componentDatatype = componentDatatype self.componentsPerAttribute = componentsPerAttribute self.normalize = normalize self.values = values self.name = "unknown" } }
apache-2.0
7ba8a7ba512d508dc0b5b51cb3d2d317
30.412121
277
0.646537
3.968606
false
false
false
false
sbcmadn1/swift
swiftweibo05/GZWeibo05/Class/Library/PhotoBrowser/CZPhotoBrowserCell.swift
1
6323
// // CZPhotoBrowserCell.swift // GZWeibo05 // // Created by zhangping on 15/11/7. // Copyright © 2015年 zhangping. All rights reserved. // import UIKit /// 自定义cell class CZPhotoBrowserCell: UICollectionViewCell { // MARK: - 属性 /// 要显示图片的url地址 var url: NSURL? { didSet { // 下载图片 guard let imageURL = url else { print("imageURL 为空") return } // 将imageView图片设置为nil,防止cell重用 imageView.image = nil // 显示下载指示器 indicator.startAnimating() // 使用sd去下载 self.imageView.sd_setImageWithURL(imageURL) { (image, error, _, _) -> Void in // 关闭指示器 self.indicator.stopAnimating() if error != nil { print("下载大图片出错:error: \(error), url:\(imageURL)") return } // 下载成功, 设置imageView的大小 print("下载成功") self.layoutImageView(image) } } } // private func testAfter() { // // 模拟网络延时 // dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(1 * NSEC_PER_SEC)), dispatch_get_main_queue()) { () -> Void in // // 使用sd去下载 // self.imageView.sd_setImageWithURL(imageURL) { (image, error, _, _) -> Void in // // 关闭指示器 // self.indicator.stopAnimating() // if error != nil { // print("下载大图片出错:error: \(error), url:\(imageURL)") // return // } // // // 下载成功, 设置imageView的大小 // print("下载成功") // self.layoutImageView(image) // } // } // } /* 等比例缩放到宽度等于屏幕的宽度后: 1.高度大于等于屏幕的高度 -> 长图 2.高度小于屏幕的高度 -> 短图 */ /// 根据长短图,重新布局imageView private func layoutImageView(image: UIImage) { // 获取等比例缩放后的图片大小 let size = displaySize(image) // 判断长短图 if size.height < UIScreen.height() { // 短图, 居中显示 let offestY = (UIScreen.height() - size.height) * 0.5 imageView.frame = CGRect(x: 0, y: offestY, width: size.width, height: size.height) } else { // 长图, 顶部显示 imageView.frame = CGRect(origin: CGPointZero, size: size) // 设置滚动 scrollView.contentSize = size } } /* 将图片等比例缩放, 缩放到图片的宽度等屏幕的宽度 */ private func displaySize(image: UIImage) -> CGSize { // 新的高度 / 新的宽度 = 原来的高度 / 原来的宽度 // 新的宽度 let newWidth = UIScreen.width() // 新的高度 let newHeight = newWidth * image.size.height / image.size.width let newSize = CGSize(width: newWidth, height: newHeight) return newSize } // MARK: - 构造函数 required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override init(frame: CGRect) { super.init(frame: frame) prepareUI() } private func prepareUI() { // 添加子控件 contentView.addSubview(scrollView) // 提示 scrollView.addSubview(imageView) contentView.addSubview(indicator) // 设置scrollView的缩放 scrollView.maximumZoomScale = 2 scrollView.minimumZoomScale = 0.5 scrollView.delegate = self // scrollView.backgroundColor = UIColor.redColor() // 添加约束 scrollView.translatesAutoresizingMaskIntoConstraints = false indicator.translatesAutoresizingMaskIntoConstraints = false contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[sv]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["sv" : scrollView])) contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[sv]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["sv" : scrollView])) // imageView的大小不固定.等获取到图片来计算 // 进度指示器 contentView.addConstraint(NSLayoutConstraint(item: indicator, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: contentView, attribute: NSLayoutAttribute.CenterX, multiplier: 1, constant: 0)) contentView.addConstraint(NSLayoutConstraint(item: indicator, attribute: NSLayoutAttribute.CenterY, relatedBy: NSLayoutRelation.Equal, toItem: contentView, attribute: NSLayoutAttribute.CenterY, multiplier: 1, constant: 0)) } // MARK: - 懒加载 /// scrollView private lazy var scrollView = UIScrollView() /// imageView private lazy var imageView = UIImageView() /// 下载图片提示 private lazy var indicator = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.WhiteLarge) } // MARK: - 扩展CZPhotoBrowserCell 实现 UIScrollViewDelegate 协议 extension CZPhotoBrowserCell: UIScrollViewDelegate { /// 返回需要缩放的view func viewForZoomingInScrollView(scrollView: UIScrollView) -> UIView? { return imageView } /* print("imageView.frame:\(imageView.frame)") print("imageView.bounds:\(imageView.bounds)") 缩放后frame会改变.bounds不会改变 */ /// scrollView缩放完毕调用 func scrollViewDidEndZooming(scrollView: UIScrollView, withView view: UIView?, atScale scale: CGFloat) { print("缩放完毕") } /// scrollView缩放时调用 func scrollViewDidZoom(scrollView: UIScrollView) { print("缩放时") } }
mit
72f5a199988dd40257d97895ac6f841e
30.882022
230
0.564857
4.752094
false
false
false
false
yanyin1986/LYVideoRangeSlider
LYVideoRangeSlider/LYVideoRangeSlider.swift
1
18940
// // LYVideoRangeSlider.swift // LYVideoRangeSlider // // Created by Leon.yan on 2/22/16. // Copyright © 2016 V+I. All rights reserved. // import AVFoundation import UIKit protocol LVVideoRangeSliderDelegate : NSObjectProtocol { func timeRangeDidChanged(timeRange : CMTimeRange) func timeRangeDidConfirm(timeRange : CMTimeRange) } class LYVideoRangeSlider: UIView, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout { /** delegate */ weak var delegate : LVVideoRangeSliderDelegate? /** min value for clip duration */ var minClipDuration : Float64 = -1 /** max value for clip duration */ var maxClipDuration : Float64 = -1 /** min clip Width */ private var _minClipWidth : CGFloat = -1 /** max clip Width */ private var _maxClipWidth : CGFloat = -1 // MARK: proerty for asset private var _videoAsset : AVAsset? private var _videoDuration : Float64 = -1 /** time range */ private var timeRange : CMTimeRange = kCMTimeRangeInvalid // MARK: property for collectionView private var _collectionView : UICollectionView? private var _normallCellSize : CGSize = CGSizeZero private var _lastCellSize : CGSize = CGSizeZero private var _imageGenerator : AVAssetImageGenerator? private var _images : [UIImage] = [UIImage]() private var _imageCount : Int = 0 private var _leftCover : UIView? private var _leftSlider : UIView? private var _rightCover : UIView? private var _rightSlider : UIView? private var _rangeView : UIView? private var _leftPanStartPoint : CGPoint = CGPointZero private var _rightPanStartPoint : CGPoint = CGPointZero private var _rangePanStartPoint : CGPoint = CGPointZero override init(frame: CGRect) { super.init(frame: frame) _commonInit() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } deinit { // stop image generation when deinit if _imageGenerator != nil { _imageGenerator!.cancelAllCGImageGeneration() } } // MARK: public methods func setupVideoAsset(videoAsset : AVAsset) { if videoAsset.hasVideoTrack() { let track = videoAsset.aVideoTrack() let timeRange = track!.timeRange setupVideoAsset(videoAsset, timeRange: timeRange, minClipDuration : -1, maxClipDuration: -1) } } func reset() { timeRange = kCMTimeRangeInvalid _imageCount = 0 _images.removeAll() maxClipDuration = -1 _maxClipWidth = -1 minClipDuration = -1 _minClipWidth = -1 } func setupVideoAsset(videoAsset : AVAsset, timeRange : CMTimeRange, minClipDuration : Float64, maxClipDuration : Float64) { if (_videoAsset == nil) || (_videoAsset != nil && !_videoAsset!.isEqual(videoAsset)) { reset() _videoAsset = videoAsset _videoDuration = CMTimeGetSeconds(videoAsset.timeRange.duration) // adjust timeRange if (minClipDuration > 0 || maxClipDuration > 0) && minClipDuration < maxClipDuration { self.minClipDuration = minClipDuration self.maxClipDuration = maxClipDuration var duration = CMTimeGetSeconds(timeRange.duration) let widthPerSeconds = self.frame.size.width / CGFloat(_videoDuration) if self.maxClipDuration > 0 && duration > self.maxClipDuration { duration = self.maxClipDuration _maxClipWidth = CGFloat(self.maxClipDuration) * widthPerSeconds } if self.minClipDuration > 0 && duration > self.minClipDuration { duration = self.minClipDuration _minClipWidth = CGFloat(self.minClipDuration) * widthPerSeconds } self.timeRange = CMTimeRangeMake(timeRange.start, CMTimeMakeWithSeconds(duration, timeRange.duration.timescale)) } else { self.timeRange = timeRange } _setupSlider() } } override func awakeFromNib() { _commonInit() } override func layoutSubviews() { if _collectionView != nil && !CGRectEqualToRect(_collectionView!.frame, self.bounds) { // do frame setting _collectionView!.frame = self.bounds _changeRangeView() _adjustStartAndLength() } } //MARK: UICollectionViewDataSource internal func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return _imageCount } internal func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCellWithReuseIdentifier("Cell", forIndexPath: indexPath) as! _LYVideoCell return cell } //MARK: UICollectionViewDelegateFlowLayout internal func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAtIndex section: Int) -> CGFloat { return 0 } internal func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAtIndex section: Int) -> CGFloat { return 0 } internal func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize { if _imageCount > 0 { if indexPath.row >= 0 && indexPath.row < _imageCount - 1 { return _normallCellSize } else { return _lastCellSize } } return CGSizeZero } // MARK: private methods private func _commonInit() { let collectionViewLayout = UICollectionViewFlowLayout() collectionViewLayout.minimumInteritemSpacing = 0 collectionViewLayout.minimumLineSpacing = 0 collectionViewLayout.scrollDirection = .Horizontal _collectionView = UICollectionView(frame: self.bounds, collectionViewLayout: collectionViewLayout) _collectionView!.dataSource = self _collectionView!.delegate = self _collectionView!.registerClass(_LYVideoCell.self, forCellWithReuseIdentifier: "Cell") // add initial for these views _leftCover = UIView(frame: CGRectMake(0, 0, 0, self.bounds.size.height)) _leftSlider = UIView(frame: CGRectMake(0, 0, 10, self.bounds.size.height)) _rangeView = UIView(frame: CGRectMake(0, 0, self.bounds.size.width - 10, self.bounds.size.height)) _rightSlider = UIView(frame: CGRectMake(self.bounds.size.width - 10, 0, 10, self.bounds.size.height)) _rightCover = UIView(frame: CGRectMake(self.bounds.size.width, 0, 0, self.bounds.size.height)) // _leftCover!.hidden = true _leftSlider!.hidden = true _rangeView!.hidden = true _rightSlider!.hidden = true _rightCover!.hidden = true _leftSlider!.addGestureRecognizer(UIPanGestureRecognizer(target: self, action: "_leftSliderMoved:")) _leftSlider!.userInteractionEnabled = true _rightSlider!.addGestureRecognizer(UIPanGestureRecognizer(target: self, action: "_rightSliderMoved:")) _rightSlider!.userInteractionEnabled = true _rangeView!.addGestureRecognizer(UIPanGestureRecognizer(target: self, action: "_rangeViewMoved:")) _rangeView!.userInteractionEnabled = true _leftSlider!.backgroundColor = UIColor(red: 0xaa, green: 0xaa, blue: 0xaa, alpha: 0.8) _rightSlider!.backgroundColor = UIColor(red: 0xaa, green: 0xaa, blue: 0xaa, alpha: 0.8) _rangeView!.backgroundColor = UIColor(red: 0xff, green: 0xff, blue: 0xff, alpha: 0.5) _leftCover!.backgroundColor = UIColor(red: 0x00, green: 0x00, blue: 0x00, alpha: 0.5) _rightCover!.backgroundColor = UIColor(red: 0x00, green: 0x00, blue: 0x00, alpha: 0.5) // add collection view first self.addSubview(_collectionView!) // then rangeView self.addSubview(_rangeView!) // self.addSubview(_leftSlider!) self.addSubview(_rightSlider!) self.addSubview(_leftCover!) self.addSubview(_rightCover!) } private func _setupSlider() { if let asset = _videoAsset { if !asset.hasVideoTrack() { // NO video track return } if let videoTrack = asset.aVideoTrack() { _changeRangeView() _adjustStartAndLength() _changeViewsVisibility(false) let preferredSize = videoTrack.videoSize let thumbnailSize = CGSizeMake(preferredSize.width * (self.bounds.size.height / preferredSize.height), self.bounds.size.height) let imageCount = Int(ceil(self.bounds.size.width / thumbnailSize.width)) precondition(imageCount >= 0) _imageCount = imageCount _normallCellSize = thumbnailSize _lastCellSize = CGSizeMake(self.bounds.size.width - CGFloat(imageCount - 1) * thumbnailSize.width, self.bounds.size.height); _collectionView!.reloadData() // let imageGenerator = AVAssetImageGenerator(asset: asset) imageGenerator.maximumSize = thumbnailSize imageGenerator.appliesPreferredTrackTransform = true var requestedTimes = [NSValue]() var time = videoTrack.timeRange.start let duration = CMTimeGetSeconds(videoTrack.timeRange.duration) let clipTime = CMTimeMakeWithSeconds(duration / Float64(imageCount), videoTrack.naturalTimeScale) for _ in 0 ..< imageCount { requestedTimes.append(NSValue(CMTime : time)) time = CMTimeAdd(time, clipTime) } imageGenerator.generateCGImagesAsynchronouslyForTimes(requestedTimes, completionHandler: { (requestedTime, cgimage, actucalTime, result, error) -> Void in if cgimage != nil { let image = UIImage(CGImage: cgimage!) dispatch_async(dispatch_get_main_queue(), {() -> Void in if let index = requestedTimes.indexOf(NSValue(CMTime : requestedTime)) { //print("index->\(index) -- \(requestedTime)\n") let indexPath = NSIndexPath(forRow: index, inSection: 0) if let cell = self._collectionView!.cellForItemAtIndexPath(indexPath) { let c = cell as! _LYVideoCell c.imageView?.image = image } } }) } }) } } } private func _changeRangeView() { if _videoDuration > 0 { let startSeconds = CMTimeGetSeconds(timeRange.start) let duration = CMTimeGetSeconds(timeRange.duration) let widthPerSecond = self.bounds.size.width / CGFloat(_videoDuration) let startX = CGFloat(startSeconds) * widthPerSecond let durationWidth = CGFloat(duration) * widthPerSecond _rangeView!.frame = CGRectMake(startX, 0, durationWidth, self.bounds.size.height) } } private func _changeViewsVisibility(hidden : Bool) { _leftCover!.hidden = hidden _leftSlider!.hidden = hidden _rangeView!.hidden = hidden _rightSlider!.hidden = hidden _rightCover!.hidden = hidden } private func _adjustStartAndLength() { let rangeViewFrame = _rangeView!.frame let x = rangeViewFrame.origin.x let width = rangeViewFrame.size.width let startTime = CMTimeMakeWithSeconds(Float64(x / self.frame.size.width) * _videoDuration, 600) let durationTime = CMTimeMakeWithSeconds(Float64(width / self.frame.size.width) * _videoDuration, 600) timeRange = CMTimeRangeMake(startTime, durationTime) _leftSlider!.frame = CGRectMake(rangeViewFrame.origin.x, 0, _leftSlider!.frame.size.width, _leftSlider!.frame.size.height) _rightSlider!.frame = CGRectMake(rangeViewFrame.origin.x + rangeViewFrame.size.width - _rightSlider!.frame.size.width, 0, _rightSlider!.frame.size.width, _rightSlider!.frame.size.height) _leftCover!.frame = CGRectMake(0, 0, _leftSlider!.frame.origin.x, self.frame.size.height) _rightCover!.frame = CGRectMake(rangeViewFrame.origin.x + rangeViewFrame.size.width, 0, self.frame.size.width - (rangeViewFrame.origin.x + rangeViewFrame.size.width), self.frame.size.height) } private func _notiRangeChanged() { if delegate != nil && delegate!.respondsToSelector("timeRangeDidChanged:") { delegate!.timeRangeDidChanged(timeRange) } } private func _notiRangeConfirm() { if delegate != nil && delegate!.respondsToSelector("timeRangeDidConfirm:") { delegate!.timeRangeDidConfirm(timeRange) } } func _leftSliderMoved(pan : UIPanGestureRecognizer) { switch(pan.state) { case .Began: _leftPanStartPoint = pan.locationInView(self) break case .Changed: let curr = pan.locationInView(self) let offsetX = curr.x - _leftPanStartPoint.x _leftPanStartPoint = curr var newX = _rangeView!.frame.origin.x + offsetX if newX < 0 { newX = 0 } var newWidth = _rangeView!.frame.origin.x + _rangeView!.frame.size.width - newX if _maxClipWidth > 0 && _maxClipWidth > _minClipWidth { if newWidth > _maxClipWidth { newWidth = _maxClipWidth } } let minWidth = max(_minClipWidth, _leftSlider!.bounds.size.width + _rightSlider!.bounds.size.width) if newWidth < minWidth { newWidth = minWidth } if newX + newWidth > self.frame.size.width { newWidth = self.frame.size.width - newX if newWidth < minWidth { newWidth = minWidth newX = self.frame.size.width - newWidth } } _rangeView!.frame = CGRectMake(newX, 0, newWidth, _rangeView!.frame.size.height) _adjustStartAndLength() _notiRangeChanged() break case .Ended, .Cancelled, .Failed: _leftPanStartPoint = CGPointZero _notiRangeConfirm() break default: break } } func _rightSliderMoved(pan: UIPanGestureRecognizer) { switch(pan.state) { case .Began: _rightPanStartPoint = pan.locationInView(self) break case .Changed: let curr = pan.locationInView(self) var offsetX = curr.x - _rightPanStartPoint.x _rightPanStartPoint = curr var right = _rangeView!.frame.origin.x + _rangeView!.frame.size.width + offsetX if right > self.frame.size.width { offsetX -= (right - self.frame.size.width) right = self.frame.size.width } var width = _rangeView!.frame.size.width + offsetX if width > _maxClipWidth { width = _maxClipWidth } let minWidth = max(_minClipWidth, _leftSlider!.bounds.size.width + _rightSlider!.bounds.size.width) if width < minWidth { width = minWidth } var newX = right - width if newX < 0 { newX = 0 right = width } _rangeView!.frame = CGRectMake(newX, _rangeView!.frame.origin.y, width, _rangeView!.frame.size.height) _adjustStartAndLength() _notiRangeChanged() break case .Ended, .Cancelled, .Failed: _rightPanStartPoint = CGPointZero _notiRangeConfirm() break default: break } } func _rangeViewMoved(pan : UIPanGestureRecognizer) { switch(pan.state) { case .Began: _rangePanStartPoint = pan.locationInView(self) break case .Changed: let curr = pan.locationInView(self) let offsetX = curr.x - _rangePanStartPoint.x _rangePanStartPoint = curr _rangeView!.center = CGPointMake(_rangeView!.center.x + offsetX, _rangeView!.center.y) if _rangeView!.frame.origin.x < 0 { _rangeView!.frame = CGRectMake(0, 0, _rangeView!.frame.size.width, _rangeView!.frame.size.height) } if _rangeView!.frame.origin.x + _rangeView!.frame.size.width > self.frame.size.width { _rangeView!.frame = CGRectMake(self.frame.size.width - _rangeView!.frame.size.width, 0, _rangeView!.frame.size.width, _rangeView!.frame.size.height) } _adjustStartAndLength() _notiRangeChanged() break case .Ended, .Cancelled, .Failed: _rangePanStartPoint = CGPointZero _notiRangeConfirm() break default: break } } } // private class _LYVideoCell : UICollectionViewCell { var imageView : UIImageView? private func _initCommont() { if imageView == nil { imageView = UIImageView(frame: self.contentView.bounds) // make the image align with imageView's left side imageView!.contentMode = .Left self.contentView.addSubview(imageView!) } } override init(frame: CGRect) { super.init(frame: frame) _initCommont() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override func awakeFromNib() { _initCommont() } }
mit
86fba25ddb9c222fad6b6b77a6ea6d12
39.040169
198
0.586831
5.106228
false
false
false
false
nifty-swift/Nifty
Sources/swap.swift
2
1907
/*************************************************************************************************** * swap.swift * * This file provides functionality for swapping elements of vectors, matrices, or tensors. * * Author: Philip Erickson * Creation Date: 25 Dec 2016 * * 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. * * Copyright 2016 Philip Erickson **************************************************************************************************/ // TODO: extend this to allow swapping of vector elements, columns of matrices as well as rows, and // 2D tensors in 3D tensors, etc. #if NIFTY_XCODE_BUILD import Accelerate #else import CBlas #endif // Swap two rows in a given matrix. /// /// - Parameters: /// - rows: exactly two numbers, corresponding to the zero-indexed rows to swap /// - A: the matrix in which to swap rows public func swap<T>(rows: Int..., in A: Matrix<T>) -> Matrix<T> { // FIXME: do this faster using BLAS DSWAP // see https://software.intel.com/en-us/node/520744 for better doc precondition(rows.count == 2, "Swap requires exactly 2 rows to be specified") var Aswap = A let temp = Aswap[rows[0], 0..<Aswap.columns] Aswap[rows[0], 0..<Aswap.columns] = Aswap[rows[1], 0..<Aswap.columns] Aswap[rows[1], 0..<Aswap.columns] = temp if let nameA = A.name { Aswap.name = "swap(rows: \(rows[0]), \(rows[1]), in: \(nameA))" } return Aswap }
apache-2.0
b49ed8e61bcd9159af33c4026a6e0b87
33.053571
101
0.62559
3.739216
false
false
false
false
kdawgwilk/vapor
Sources/Vapor/Validation/Validators.swift
2
3228
/* The MIT License (MIT) Copyright (c) 2016 Benjamin Encz 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. */ /** The core validator, used for validations that require parameters. For example, a string length validator that uses a dynamic value to evaluate by. public enum StringLength: Validator { case min(Int) case max(Int) case containedIn(Range<Int>) public func validate(input value: String) throws { let length = value.characters.count switch self { case .min(let m) where length >= m: break case .max(let m) where length <= m: break case .containedIn(let range) where range ~= length: break default: throw error(with: value) } } } And used like: let validated = try "string".validated(by: StringLength.min(4)) */ public protocol Validator { /** The type of value that this validator is capable of evaluating */ associatedtype InputType: Validatable /** Used to validate a given input. Should throw error if validation fails using: throw error(with: value) A function that does not throw will be considered a pass. */ func validate(input value: InputType) throws } public protocol ValidationSuite: Validator { /** The type of value that this validator is capable of evaluating */ associatedtype InputType: Validatable /** Used to validate a given input. Should throw error if validation fails using: throw error(with: value) A function that does not throw will be considered a pass. */ static func validate(input value: InputType) throws } extension ValidationSuite { /** ValidationSuite objects automatically conform to Validator by invoking the static validation - parameter value: input value to validate - throws: an error if validation fails */ public func validate(input value: InputType) throws { try self.dynamicType.validate(input: value) } }
mit
1bb81891c350f026c6434715badc9bc1
31.938776
97
0.664188
5.075472
false
false
false
false
patrick-sheehan/cwic
Source/AuthService.swift
1
3055
// // AuthService.swift // CWIC // // Created by Patrick Sheehan on 12/11/17. // Copyright © 2017 Síocháin Solutions. All rights reserved. // import Foundation class AuthService { static let URL_STR_LOGIN = "\(ApiService.BaseURL)/auth/login/" static let URL_STR_REGISTER = "\(ApiService.BaseURL)/auth/register/" class var authKey: String? { get { return UserDefaults.standard.string(forKey: "auth_key") } set { UserDefaults.standard.set(newValue, forKey: "auth_key") } } class var csrftoken: String? { get { return UserDefaults.standard.string(forKey: "csrftoken") } set { UserDefaults.standard.set(newValue, forKey: "csrftoken") } } class var shouldPromptProfileUpdate: Bool { get { return UserDefaults.standard.bool(forKey: "shouldPromptProfileUpdate") } set { UserDefaults.standard.set(newValue, forKey: "shouldPromptProfileUpdate") } } class func hasSavedCredentials() -> Bool { return authKey != nil && csrftoken != nil } class func deleteCredentials() { self.authKey = nil self.csrftoken = nil } class func login(_ params: [String: Any], completion: @escaping () -> Void) { ApiService.authRequest(urlString: URL_STR_LOGIN, params: params, completion) } class func register(_ params: [String: Any], completion: @escaping () -> Void) { ApiService.authRequest(urlString: URL_STR_REGISTER, params: params, completion) } class func logout() { deleteCredentials() ApiService.clearCookies() } } /* class var authKey: String? { get { return UserDefaults.standard.string(forKey: "auth_key") } set { UserDefaults.standard.set(newValue, forKey: "auth_key") } } class var csrftoken: String? { get { return UserDefaults.standard.string(forKey: "csrftoken") } set { UserDefaults.standard.set(newValue, forKey: "csrftoken") } } class func didAuthenticate(json: [String: Any], _ completion: () -> Void) { if let key = json["key"] as? String { print("did authenticate with key: \(key)") authKey = key completion() } } class func login(_ username: String, _ password: String, completion: @escaping () -> Void) { let params = ["username": username, "password": password] API.loginRequest(params, completion) } class func register(_ username: String, email: String, password1: String, password2: String, completion: @escaping () -> Void) { let url = "\(API.BaseURL)/auth/register/" let params = ["username": username, "email": email, "password1": password1, "password2": password2] API.request("POST", url, params) { self.didAuthenticate(json: $0, completion) } } class func logout(completion: @escaping () -> Void) { let url = "\(API.BaseURL)/auth/logout/" API.request("POST", url, nil) { _ in self.authKey = nil completion() } } } */
gpl-3.0
5280f80fdc2a04498201cf4cddc3aa71
27
103
0.620249
3.994764
false
false
false
false
itouch2/LeetCode
LeetCode/PathSum2.swift
1
1051
// // PathSum2.swift // LeetCode // // Created by You Tu on 2017/9/23. // Copyright © 2017年 You Tu. All rights reserved. // /* Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum. For example: Given the below binary tree and sum = 22, 5 / \ 4 8 / / \ 11 13 4 / \ / \ 7 2 5 1 return [ [5,4,11,2], [5,8,4,5] ] */ import Cocoa class PathSum2: NSObject { func pathSum(_ root: TreeNode?, _ sum: Int) -> [[Int]] { pathSum(root, sum, 0, []) return res } func pathSum(_ node: TreeNode?, _ sum: Int, _ total: Int, _ cur: [Int]) { if node == nil { return } let value = total + (node?.val)! var t = cur t.append((node?.val)!) if value == sum && node?.left == nil && node?.right == nil { res.append(t) } pathSum(node?.left, sum, value, t) pathSum(node?.right, sum, value, t) } var res:[[Int]] = [] }
mit
42c11448aa3669551fb19f401e9c5e05
18.407407
103
0.491412
3.175758
false
false
false
false
paulopr4/quaddro-mm
AprendendoSwift/AprendendoSwift-parte5-ControleDeFluxo.playground/Contents.swift
1
1655
//: Quaddro - noun: a place where people can learn //Declaramos os dias da semana let diasSemana = ["Seg", "Ter", "Qua", "Qui", "Sex", "Sab", "Dom"] //Percorremos os dias da semana for dia in diasSemana{ print("Hoje é \(dia)") switch dia { case "Seg": print("É difícil de acordar.") case "Ter": print("Começo oficial da semana.") case "Qua": print("Meio da semana do mal") case "Qui": print("Tá chegando o fds") case "Sex": print("Chegou a sexta! Vamos sair?") case "Sab": print("Ressaca :(") case "Dom": print("Gols do fantástico. Acabou :(") default: print("Que planeta você vive?") } } //Percorremos de 1 a 10 no loop for var num = 1; num <= 10; num += 1 { //Verificamos se o número é par ou impar if num % 2 == 0{ print("O numero \(num) é par") }else{ print("O numero \(num) é impar") } } //Também podemos percorrer um array com o for let carros = ["La Ferrari", "BMW M3", "Mustang", "McLaren P1"] for var index = 0; index < carros.count; index += 1 { print("Conheça meu carro. \(carros[index])") } var n = 2 while n < 1000 { n = n * 2 print("N vale \(n)") } var xwhile = 1 while xwhile <= 10 { if xwhile % 2 == 0{ print("O número \(xwhile) é par!") }else{ print("O número \(xwhile) é par!") } xwhile += 1 } var velocidade = 10 repeat{ if velocidade == 10 { print("Velocidade inicial garantida em \(velocidade)") } print( "Minha velocidade é \(velocidade)") velocidade = velocidade + 10 }while velocidade < 100
apache-2.0
879ced91129102d342b8f6c346ee514e
18.488095
66
0.563225
2.933692
false
false
false
false
luckyx1/flicks
flicks/MovieCollectionViewController.swift
1
2871
// // MovieCollectionViewController.swift // flicks // // Created by Rob Hernandez on 1/16/17. // Copyright © 2017 Robert Hernandez. All rights reserved. // import UIKit import AFNetworking import MBProgressHUD class MovieCollectionViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout { @IBOutlet weak var flowLayout: UICollectionViewFlowLayout! @IBOutlet weak var collectionView: UICollectionView! // Hold the data locally from the API call var movies: [NSDictionary]? override func viewDidLoad() { super.viewDidLoad() collectionView.delegate = self collectionView.dataSource = self flowLayout.scrollDirection = .vertical flowLayout.minimumLineSpacing = 0 flowLayout.minimumInteritemSpacing = 0 flowLayout.sectionInset = UIEdgeInsetsMake(0, 0, 0, 0) } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int{ return self.movies?.count ?? 0 } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell{ let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "movieCollectCell", for: indexPath) as! MovieCollectionCell let movie = self.movies![indexPath.row] let title = movie["title"] as! String cell.titleLabel.text = title // Attempt to get the poster_path and set into the cell if let posterPath = movie["poster_path"] as? String{ let baseUrl = "https://image.tmdb.org/t/p/w500/" let imageUrl = NSURL(string: baseUrl + posterPath) self.fadeInImage(url: imageUrl!, poster: cell.movieImage) } return cell } // Fade in code func fadeInImage(url: NSURL, poster: UIImageView){ let imageRequest = NSURLRequest(url: url as URL) poster.setImageWith(imageRequest as URLRequest, placeholderImage: nil, success: { (imageRequest, imageResponse, image) -> Void in // imageResponse will be nil if the image is cached if imageResponse != nil { print("Image was NOT cached, fade in image") poster.alpha = 0.0 poster.image = image UIView.animate(withDuration: 0.4, animations: { () -> Void in poster.alpha = 2.0 }) } else { print("Image was cached so just update the image") poster.image = image } }, failure: { (imageRequest, imageResponse, error) -> Void in // do something for the failure condition poster.image = nil }) } }
mit
fb0691426e33aa82362cf9d93fa4420a
31.988506
145
0.624042
5.324675
false
false
false
false
emilstahl/swift
validation-test/compiler_crashers/27298-swift-modulefile-gettype.swift
9
2349
// RUN: not --crash %target-swift-frontend %s -parse // Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing var b class A<T where g }}struct c<T where j:A{class A<T.g:a=0 as a=(f=e? struct c{}func a<T where j:T>:A<T where g = b class b<T{class d let a=(f import n{class d=0 as a{class B<I{ class x{class A struct d struct b{class B<H }}} class A{var b<T:AnyObject class B<d class A<d{struct A{}struct S{class n var f }let h=0.g:A{class B<T where j:d=b class d{ struct c{let h=e? var d{class A<T where g struct A} struct S{enum S<S:a{class A{let a=B{ var f:a{}struct S{class a<T where g = b{}let e=b println{class A{let a=B{ protocol b class A:T{class B<S{{{ class A func<T where H var f=e? struct d=0.g struct S{}let a=0.b class B<T where g func<T where g:a{ println{func a{}struct A:A:A<T.b var _=e? class x{ let e=c<T where T{ struct d var _=e=0 as a=e=0.h=b if true{}let e=b{func c<d{class A{struct A:A{{class A{let a=B{ " class A}struct A<S:AnyObject class n class A}let a{struct B{}struct B{let a{} struct S:d<T{var:A{let C class b{struct c{var f=b<{class x{class A }func c<T>:d if true{class A{let a=B{ println{let a struct c{}let a var d var d<T{ struct d=c<T where H "" import n{{ class n{}func c{class A{let a=B{ "" if true{var:AnyObject var f=0.g:A{class B<T where g:T{struct B<T where j:A{struct S:d{struct B<d{var _=(f var d=0.h:A{class A{struct B<T{{class n var _=0.g class A{} class d=0.g:d class A{var f class A:A{struct b<d class a{ func<I{class A:A:A{{{struct B<d func<H=(f=B<T where k:AnyObject struct A{class A<S{ if true{class A{let a=B{ struct B<T where g = b class a let e=e=0.h:T{enum S<T.h=e? protocol b class B<T where T{struct c<S<T where j:T{class n{ var b{ let h=0 as a{ struct c<T where g = b class A{ class n{}let a{let a{var f:AnyObject var _=Int class d println{}let e? """" var f:A<T where j:A:A}}func c<d{ }let a=B<T.b import n if true{{let a<T where T>:A<I{{class B<T where T:d{struct d{class A class B<S{{enum S:A{ func<I{class B<T where g:A:T.h:A:A{ class A<T>:a<I{let a{func c{ import n{}}}let a{let a{class A{let a=B{ struct B{let C if true{}struct S:T:T{ class A<I{let a<T{class A{let a=B{ if true{func a{{class A{class d{let h:T{struct B<T.b{}let a<I{let C class B<T:T.b{ import n{ " if true{
apache-2.0
2b7a098665cf32895778d93b109ea081
21.371429
87
0.673904
2.21813
false
false
false
false
anasmeister/nRF-Coventry-University
Pods/iOSDFULibrary/iOSDFULibrary/Classes/Implementation/GenericDFU/DFUExecutor.swift
1
6301
/* * Copyright (c) 2016, Nordic Semiconductor * 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 CoreBluetooth internal protocol BaseExecutorAPI : class, BasePeripheralDelegate, DFUController { /** Starts the DFU operation. */ func start() } internal protocol BaseDFUExecutor : BaseExecutorAPI { associatedtype DFUPeripheralType : BaseDFUPeripheralAPI /// Target peripheral object var peripheral:DFUPeripheralType { get } /// The DFU Service Initiator instance that was used to start the service. var initiator:DFUServiceInitiator { get } /// If an error occurred it is set as this variable. It will be reported to the user when the device gets disconnected. var error:(error:DFUError, message:String)? { set get } } extension BaseDFUExecutor { /// The service delegate will be informed about status changes and errors. internal var delegate:DFUServiceDelegate? { // The delegate may change during DFU operation (by setting a new one in the initiator). Let's always use the current one. return initiator.delegate } /// The progress delegate will be informed about current upload progress. internal var progressDelegate:DFUProgressDelegate? { // The delegate may change during DFU operation (by setting a new one in the initiator). Let's always use the current one. return initiator.progressDelegate } func start() { self.error = nil peripheral.start() } // MARK: - DFU Controller API func pause() -> Bool { return peripheral.pause() } func resume() -> Bool { return peripheral.resume() } func abort() -> Bool { return peripheral.abort() } // MARK: - BasePeripheralDelegate API func peripheralDidFailToConnect() { DispatchQueue.main.async(execute: { self.delegate?.dfuError(.failedToConnect, didOccurWithMessage: "Device failed to connect") }) // Release the cyclic reference peripheral.destroy() } func peripheralDidDisconnect() { // The device is now disconnected. Check if there was an error that needs to be reported now DispatchQueue.main.async(execute: { if let error = self.error { self.delegate?.dfuError(error.error, didOccurWithMessage: error.message) } else { self.delegate?.dfuError(.deviceDisconnected, didOccurWithMessage: "Device disconnected unexpectedly") } }) // Release the cyclic reference peripheral.destroy() } func peripheralDidDisconnect(withError error: Error) { DispatchQueue.main.async(execute: { self.delegate?.dfuError(.deviceDisconnected, didOccurWithMessage: "\(error.localizedDescription) (code: \((error as NSError).code))") }) // Release the cyclic reference peripheral.destroy() } func peripheralDidDisconnectAfterAborting() { DispatchQueue.main.async(execute: { self.delegate?.dfuStateDidChange(to: .aborted) }) // Release the cyclic reference peripheral.destroy() } func error(_ error:DFUError, didOccurWithMessage message:String) { // Save the error. It will be reported when the device disconnects if self.error == nil { self.error = (error, message) peripheral.resetDevice() } } // MARK: - Helper functions func logWith(_ level: LogLevel, message: String) { initiator.logger?.logWith(level, message: message) } } // MARK: - internal protocol DFUExecutorAPI : BaseExecutorAPI { /// Required constructor init(_ initiator:DFUServiceInitiator) } internal protocol DFUExecutor : DFUExecutorAPI, BaseDFUExecutor, DFUPeripheralDelegate { associatedtype DFUPeripheralType : DFUPeripheralAPI /// The firmware to be sent over-the-air var firmware:DFUFirmware { get } } extension DFUExecutor { // MARK: - BasePeripheralDelegate API func peripheralDidDisconnectAfterFirmwarePartSent() { // Check if there is another part of the firmware that has to be sent if firmware.hasNextPart() { firmware.switchToNextPart() DispatchQueue.main.async(execute: { self.delegate?.dfuStateDidChange(to: .connecting) }) peripheral.switchToNewPeripheralAndConnect() return } // If not, we are done here. Congratulations! DispatchQueue.main.async(execute: { // If no, the DFU operation is complete self.delegate?.dfuStateDidChange(to: .completed) }) // Release the cyclic reference peripheral.destroy() } }
bsd-3-clause
8144f0b1450fa6f8a04b39b0de2c31dd
37.420732
145
0.679416
5.065113
false
false
false
false
mrdepth/Neocom
Legacy/Neocom/Neocom/MailViewController.swift
2
2151
// // MailViewController.swift // Neocom // // Created by Artem Shimanski on 11/2/18. // Copyright © 2018 Artem Shimanski. All rights reserved. // import Foundation import TreeController import Futures class MailViewController: PageViewController, ContentProviderView { typealias Presenter = MailPresenter lazy var presenter: Presenter! = Presenter(view: self) var unwinder: Unwinder? override func viewDidLoad() { super.viewDidLoad() presenter.configure() navigationController?.isToolbarHidden = false navigationItem.rightBarButtonItem = editButtonItem } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) presenter.viewWillAppear(animated) } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) presenter.viewDidAppear(animated) } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) presenter.viewWillDisappear(animated) } override func viewDidDisappear(_ animated: Bool) { super.viewDidDisappear(animated) presenter.viewDidDisappear(animated) } func present(_ content: Presenter.Presentation, animated: Bool) -> Future<Void> { var pages = viewControllers as? [MailPageViewController] ?? [] errorLabel = nil viewControllers = content.value.labels?.map { i -> UIViewController in let controller: MailPageViewController if let i = pages.firstIndex(where: {$0.input?.labelID == i.labelID}) { controller = pages.remove(at: i) } else { controller = try! MailPage.default.instantiate(i).get() } controller.updateTitle() return controller } return .init(()) } func fail(_ error: Error) { errorLabel = TableViewBackgroundLabel(error: error) } private var errorLabel: UILabel? { didSet { oldValue?.removeFromSuperview() if let label = errorLabel { view.addSubview(label) if #available(iOS 11.0, *) { label.frame = view.bounds.inset(by: view.safeAreaInsets) } else { label.frame = view.bounds.inset(by: UIEdgeInsets(top: topLayoutGuide.length, left: 0, bottom: bottomLayoutGuide.length, right: 0)) } } } } }
lgpl-2.1
bd79ef20d764ef6cbc31caee07654628
24
135
0.72
3.909091
false
false
false
false
alexsanderkhitev/ImagePickerSheetController
ImagePickerSheetController/ImagePickerSheetController/Sheet/SheetPreviewCollectionViewCell.swift
1
1670
// // SheetPreviewCollectionViewCell.swift // ImagePickerSheetController // // Created by Laurin Brandner on 06/09/14. // Copyright (c) 2014 Laurin Brandner. All rights reserved. // import UIKit class SheetPreviewCollectionViewCell: SheetCollectionViewCell { var collectionView: UICollectionView? { willSet { if let collectionView = collectionView { collectionView.removeFromSuperview() } if let collectionView = newValue { collectionView.translatesAutoresizingMaskIntoConstraints = false addSubview(collectionView) } } } // MARK: - Flags private var isDidSetupConstraints = false // MARK: - Other Methods override func prepareForReuse() { isDidSetupConstraints = false collectionView = nil } // MARK: - Layout override func layoutSubviews() { super.layoutSubviews() setupUIElementsPositions() // collectionView?.frame = UIEdgeInsetsInsetRect(bounds, backgroundInsets) } private func setupUIElementsPositions() { if isDidSetupConstraints == false { collectionView?.rightAnchor.constraint(equalTo: rightAnchor, constant: -20).isActive = true collectionView?.leftAnchor.constraint(equalTo: leftAnchor, constant: 20).isActive = true collectionView?.topAnchor.constraint(equalTo: topAnchor, constant: 10).isActive = true collectionView?.heightAnchor.constraint(equalToConstant: 100).isActive = true isDidSetupConstraints = true } } }
mit
6e388545dd3bb719ef27fb9686c06106
29.363636
103
0.639521
5.921986
false
false
false
false
tavultesoft/keymanweb
ios/keyman/Keyman/Keyman/Classes/MainViewController/ActivityItemProvider.swift
1
1989
// // ActivityItemProvider.swift // Keyman // // Created by Gabriel Wong on 2017-09-04. // Copyright © 2017 SIL International. All rights reserved. // import UIKit private let htmlMailFormat = """ <html><head><style type=\"text/css\">pre {font-family:\"%@\";font-size:%@;}</style> </head><body><pre>%@</pre>%@</body></html> """ private let mailFooterTextForPad = "<br><br>Sent from&nbsp;<a href=\"https://keyman.com/ipad\">Keyman for iPad</a>" private let mailFooterTextForPhone = "<br><br>Sent from&nbsp;<a href=\"https://keyman.com/iphone\">Keyman for iPhone</a>" private let fbText = "Can't read this? Help at https://keyman.com/fonts" // Prepares the share text class ActivityItemProvider: UIActivityItemProvider { private let text: String private let font: UIFont init(text: String, font: UIFont?) { self.text = text self.font = font ?? UIFont.systemFont(ofSize: UIFont.systemFontSize) super.init(placeholderItem: text) } override var item: Any { switch activityType { case UIActivity.ActivityType.mail?: return htmlMail(withText: text, font: font) case UIActivity.ActivityType.postToFacebook?: return "\(text)\n\n\(fbText)" case UIActivity.ActivityType.postToTwitter?: return text.prefix(140) default: return text } } private func htmlMail(withText text: String, font: UIFont) -> String { let mailText = text.replacingOccurrences(of: "&", with: "&amp;") .replacingOccurrences(of: "<", with: "&lt;") .replacingOccurrences(of: ">", with: "&gt;") let familyName = font.familyName let fontSize = String(Int(font.pointSize)) let footerText: String if UIDevice.current.userInterfaceIdiom == .pad { footerText = mailFooterTextForPad } else { footerText = mailFooterTextForPhone } // html mail format: family-name, font-size, text, footer-text return String(format: htmlMailFormat, familyName, fontSize, mailText, footerText) } }
apache-2.0
defa844e009fc1a0839fce6ec1a35830
32.133333
88
0.677565
3.867704
false
false
false
false
evering7/iSpeak8
iSpeak8/Data_GlobalPlay.swift
1
2266
// // Data_GlobalPlay.swift // iSpeak8 // // Created by JianFei Li on 15/08/2017. // Copyright © 2017 JianFei Li. All rights reserved. // import Foundation import AVFoundation import UIKit import CoreData //import CoreStore let globalPlayData = GlobalPlayData() class GlobalPlayData: NSObject { var speechSynthesizer: AVSpeechSynthesizer override init() { let str = "Start speaking soon." //just some string here speechSynthesizer = AVSpeechSynthesizer() let utterance = AVSpeechUtterance(string: str) utterance.rate = AVSpeechUtteranceDefaultSpeechRate let lang = "en-US" utterance.voice = AVSpeechSynthesisVoice(language: lang) super.init() speechSynthesizer.speak(utterance) } func prepareAudioSession(){ let audioSession = AVAudioSession.sharedInstance() // audioSession.delegate = self do { try audioSession.setCategory(AVAudioSessionCategoryPlayAndRecord, with:[.allowBluetooth, .defaultToSpeaker, .mixWithOthers]) try audioSession.setActive(true) }catch { printLog("The audio Session can't be established") } // second part of audio session UIApplication.shared.beginReceivingRemoteControlEvents() NotificationCenter.default.addObserver(self, selector: #selector(globalPlayData.onAudioSessionEvent), name: NSNotification.Name(rawValue: AVAudioSessionInterruptionTypeKey), object: nil) } // func prepareAudioSession() 2017 July 27th func onAudioSessionEvent(){ printLog("Enter audio session event") } func beginInterruption() { printLog( "Enter speech interruption, pause the speech") speechSynthesizer.pauseSpeaking(at: .immediate) } func endInterruption(withFlags flags: Int) { printLog( "Enter speech resume ") speechSynthesizer.continueSpeaking() } } // class GlobalPlayData: NSObject 2017.8.15
mit
21f00f87ca3358aec4fb6f7f963b520d
29.2
118
0.604857
5.734177
false
false
false
false
qinting513/SwiftNote
PullToRefreshKit-master 自定义刷新控件/PullToRefreshKit/ConfigHeaderFooterController.swift
1
2727
// // ConfigDefaultHeaderFooterController.swift // PullToRefreshKit // // Created by huangwenchen on 16/7/13. // Copyright © 2016年 Leo. All rights reserved. // import UIKit class ConfigDefaultHeaderFooterController: UITableViewController { var models = [1,2,3,4,5,6,7,8,9,10] override func viewDidLoad() { super.viewDidLoad() self.tableView.tableFooterView = UIView(frame: CGRect.zero) //Header _ = self.tableView.setUpHeaderRefresh { [weak self] in delay(1.5, closure: { self?.models = (self?.models.map({_ in random100()}))! self?.tableView.reloadData() self?.tableView.endHeaderRefreshing(.success,delay: 0.3) }) }.SetUp { (header) in header.setText("Pull to refresh", mode: .pullToRefresh) header.setText("Release to refresh", mode: .releaseToRefresh) header.setText("Success", mode: .refreshSuccess) header.setText("Refreshing...", mode: .refreshing) header.setText("Failed", mode: .refreshFailure) header.textLabel.textColor = UIColor.orange header.durationWhenHide = 0.4 } //Footer _ = self.tableView.setUpFooterRefresh { [weak self] in delay(1.5, closure: { self?.models.append(random100()) self?.tableView.reloadData() self?.tableView.endFooterRefreshing() }) }.SetUp { (footer) in footer.setText("Pull up to refresh", mode: RefreshKitFooterText.pullToRefresh) footer.setText("No data any more", mode: RefreshKitFooterText.noMoreData) footer.setText("Refreshing...", mode: RefreshKitFooterText.refreshing) footer.setText("Tap to load more", mode: RefreshKitFooterText.tapToRefresh) footer.textLabel.textColor = UIColor.orange footer.refreshMode = .tap } } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return models.count } override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 44.0 } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { var cell = tableView.dequeueReusableCell(withIdentifier: "cell") if cell == nil { cell = UITableViewCell(style: .default, reuseIdentifier: "cell") } cell?.textLabel?.text = "\(models[(indexPath as NSIndexPath).row])" return cell! } deinit{ print("Deinit of DefaultTableViewController") } }
apache-2.0
52de077e6399a1f2e823551fb048c3da
38.478261
109
0.615639
4.737391
false
false
false
false
cpmpercussion/microjam
Pods/DropDown/DropDown/helpers/DPDKeyboardListener.swift
1
1559
// // KeyboardListener.swift // DropDown // // Created by Kevin Hirsch on 30/07/15. // Copyright (c) 2015 Kevin Hirsch. All rights reserved. // import UIKit internal final class KeyboardListener { static let sharedInstance = KeyboardListener() fileprivate(set) var isVisible = false fileprivate(set) var keyboardFrame = CGRect.zero fileprivate var isListening = false deinit { stopListeningToKeyboard() } } //MARK: - Notifications extension KeyboardListener { func startListeningToKeyboard() { if isListening { return } isListening = true NotificationCenter.default.addObserver( self, selector: #selector(keyboardWillShow(_:)), name: UIResponder.keyboardWillShowNotification, object: nil) NotificationCenter.default.addObserver( self, selector: #selector(keyboardWillHide(_:)), name: UIResponder.keyboardWillHideNotification, object: nil) } func stopListeningToKeyboard() { NotificationCenter.default.removeObserver(self) } @objc fileprivate func keyboardWillShow(_ notification: Notification) { isVisible = true keyboardFrame = keyboardFrame(fromNotification: notification) } @objc fileprivate func keyboardWillHide(_ notification: Notification) { isVisible = false keyboardFrame = keyboardFrame(fromNotification: notification) } fileprivate func keyboardFrame(fromNotification notification: Notification) -> CGRect { return ((notification as NSNotification).userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue ?? CGRect.zero } }
mit
6801b813432e0885f8ba0957b4537591
21.926471
134
0.751764
4.403955
false
false
false
false
codeeu/coding-events-iOS
coding-events iOS/ViewController.swift
1
1909
// // ViewController.swift // coding-events iOS // // Created by Goran Blažič on 24/09/14. // Copyright (c) 2014 goranche.net. All rights reserved. // import UIKit import MapKit import CoreLocation class ViewController: UIViewController, NSURLConnectionDelegate, MKMapViewDelegate { lazy var data = NSMutableData() @IBOutlet weak var mapView: MKMapView! override func viewDidLoad() { super.viewDidLoad() } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) startConnection() } override func viewDidAppear(animated: Bool) { var locMgr = CLLocationManager() var auth = CLLocationManager.authorizationStatus() if (auth == CLAuthorizationStatus.NotDetermined) { locMgr.requestAlwaysAuthorization() // TODO: This no worky!!! } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } func startConnection() { let urlPath: String = "http://events.codeweek.eu/api/event/list/?format=json" var url: NSURL = NSURL(string: urlPath) var request: NSURLRequest = NSURLRequest(URL: url) var connection: NSURLConnection = NSURLConnection(request: request, delegate: self, startImmediately: false) connection.start() } func connection(connection: NSURLConnection!, didReceiveData data: NSData!){ self.data.appendData(data) } func connectionDidFinishLoading(connection: NSURLConnection!) { var err: NSError? var events = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.AllowFragments, error: &err) as Array<NSDictionary> // TODO: Show the markers from the events array // each entry is a NSDictionary, use the "geoposition" field for the markers } func mapView(mapView: MKMapView!, didUpdateUserLocation userLocation: MKUserLocation!) { var region = MKCoordinateRegionMakeWithDistance(userLocation.coordinate, 800, 800) self.mapView.setRegion(region, animated: true) } }
mit
3cb7d6c8d0770b59c684e6558fa859c7
27.893939
141
0.760357
4.136659
false
false
false
false
tkremenek/swift
test/Interpreter/objc_extensions.swift
1
1959
// REQUIRES: rdar80923668 // RUN: %target-run-simple-swift %s | %FileCheck %s // REQUIRES: executable_test // REQUIRES: objc_interop import Foundation // Category on a nested class class OuterClass { class InnerClass: NSObject {} } extension OuterClass.InnerClass { @objc static let propertyInExtension = "foo" @objc func dynamicMethod() -> String { return "bar" } } let x = OuterClass.InnerClass() // CHECK: foo print(type(of: x).propertyInExtension) // CHECK: bar print(x.dynamicMethod()) // Category on a concrete subclass of a generic base class class Base<T> { let t: T init(t: T) { self.t = t } } class Derived : Base<Int> {} extension Derived { @objc func otherMethod() -> Int { return t } } let y: AnyObject = Derived(t: 100) // CHECK: 100 // This call fails due to rdar://problem/47053588, where categories // don't attach to a dynamically initialized Swift class, on macOS 10.9 // and iOS 7. Disable it for now when testing on those versions. if #available(macOS 10.10, iOS 8, *) { print(y.otherMethod()) } else { print("100") // Hack to satisfy FileCheck. } extension NSObject { @objc func sillyMethod() -> Int { return 123 } } let z: AnyObject = NSObject() // CHECK: 123 print(z.sillyMethod()) // Category on an ObjC generic class using a type-pinning parameter, including // a cast to an existential metatype @objc protocol CacheNameDefaulting { static var defaultCacheName: String { get } } extension OuterClass.InnerClass: CacheNameDefaulting { static var defaultCacheName: String { "InnerClasses" } } extension NSCache { @objc convenience init(ofObjects objectTy: ObjectType.Type, forKeys keyTy: KeyType.Type) { self.init() if let defaultNameTy = objectTy as? CacheNameDefaulting.Type { self.name = defaultNameTy.defaultCacheName } } } let cache = NSCache(ofObjects: OuterClass.InnerClass.self, forKeys: NSString.self) // CHECK: InnerClasses print(cache.name)
apache-2.0
c2b7ab4587b2ad4c832608c93c8b7eeb
21.011236
92
0.706483
3.568306
false
false
false
false
LFL2018/swiftSmpleCode
playground_Code/Exchange_element.playground/Contents.swift
1
749
//: Playground - noun: a place where people can play import UIKit /* 场景:评论界面置顶某个回复 */ public var shouldHightModel : String! // 需要置顶的元素 fileprivate var dataArray = [String]() shouldHightModel = "666" dataArray = ["😆","稳","厉害了","可以"] if shouldHightModel != nil && dataArray.count > 0{ let indexValue = dataArray.index(of: shouldHightModel) if let valueIndex = indexValue { // 存在此元素 print("元素查找位置:\(valueIndex)") (dataArray[0],dataArray[valueIndex]) = (dataArray[valueIndex],dataArray[0]) }else{ // 不存在 print("元素不在此数组中") dataArray.insert(shouldHightModel, at: 0) } } print("handle datas\(dataArray)")
mit
d0c81cc36885c6e7b15695c747ac7259
30.047619
83
0.661043
3.395833
false
false
false
false
joerocca/GitHawk
Pods/Pageboy/Sources/Pageboy/Extensions/PageboyViewController+Transitioning.swift
1
6022
// // PageboyViewController+Transitioning.swift // Pageboy // // Created by Merrick Sapsford on 29/05/2017. // Copyright © 2017 Merrick Sapsford. All rights reserved. // import UIKit // MARK: - PageboyViewController transition configuration. public extension PageboyViewController { /// Transition for a page scroll. public struct Transition { /// Style for the transition. /// /// - push: Slide the new page in (Default). /// - fade: Fade the new page in. /// - moveIn: Move the new page in over the top of the current page. /// - reveal: Reveal the new page under the current page. public enum Style: String { case push = "push" case fade = "fade" case moveIn = "moveIn" case reveal = "reveal" } /// The style for the transition. public let style: Style /// The duration of the transition. public let duration: TimeInterval /// Default transition (Push, 0.3 second duration). public static var defaultTransition: Transition { return Transition(style: .push, duration: 0.3) } // MARK: Init /// Initialize a transition. /// /// - Parameters: /// - style: The style to use. /// - duration: The duration to transition for. public init(style: Style, duration: TimeInterval) { self.style = style self.duration = duration } } } // MARK: - Custom PageboyViewController transitioning. internal extension PageboyViewController { // MARK: Set Up fileprivate func prepareForTransition() { guard self.transitionDisplayLink == nil else { return } let transitionDisplayLink = CADisplayLink(target: self, selector: #selector(displayLinkDidTick)) transitionDisplayLink.isPaused = true transitionDisplayLink.add(to: RunLoop.main, forMode: .commonModes) self.transitionDisplayLink = transitionDisplayLink } fileprivate func clearUpAfterTransition() { self.transitionDisplayLink?.invalidate() self.transitionDisplayLink = nil } // MARK: Animation @objc func displayLinkDidTick() { self.activeTransition?.tick() } /// Perform a transition to a new page index. /// /// - Parameters: /// - from: The current index. /// - to: The new index. /// - direction: The direction of travel. /// - animated: Whether to animate the transition. /// - completion: Action on the completion of the transition. internal func performTransition(from: Int, to: Int, with direction: NavigationDirection, animated: Bool, completion: @escaping TransitionOperation.Completion) { guard animated == true else { return } guard self.activeTransition == nil else { return } guard let scrollView = self.pageViewController?.scrollView else { return } prepareForTransition() /// Calculate semantic direction for RtL languages var semanticDirection = direction if view.layoutIsRightToLeft && navigationOrientation == .horizontal { semanticDirection = semanticDirection == .forward ? .reverse : .forward } // create a transition and unpause display link let action = TransitionOperation.Action(startIndex: from, endIndex: to, direction: direction, semanticDirection: semanticDirection, orientation: self.navigationOrientation) self.activeTransition = TransitionOperation(for: self.transition, action: action, delegate: self) self.transitionDisplayLink?.isPaused = false // start transition self.activeTransition?.start(on: scrollView.layer, completion: completion) } } extension PageboyViewController: TransitionOperationDelegate { func transitionOperation(_ operation: TransitionOperation, didFinish finished: Bool) { self.transitionDisplayLink?.isPaused = true self.activeTransition = nil clearUpAfterTransition() } func transitionOperation(_ operation: TransitionOperation, didUpdateWith percentComplete: CGFloat) { let isReverse = operation.action.direction == .reverse let isVertical = operation.action.orientation == .vertical /// Take into account the diff between startIndex and endIndex let indexDiff = abs(operation.action.endIndex - operation.action.startIndex) let diff = percentComplete * CGFloat(indexDiff) let currentIndex = CGFloat(self.currentIndex ?? 0) let currentPosition = isReverse ? currentIndex - diff : currentIndex + diff let point = CGPoint(x: isVertical ? 0.0 : currentPosition, y: isVertical ? currentPosition : 0.0) self.currentPosition = point self.delegate?.pageboyViewController(self, didScrollTo: point, direction: operation.action.direction, animated: true) self.previousPagePosition = currentPosition } } internal extension PageboyViewController.Transition { func configure(transition: inout CATransition) { transition.duration = self.duration transition.type = self.style.rawValue } }
mit
0f71df0218544bf2afecd37e0994c7b8
36.63125
104
0.575652
5.857004
false
false
false
false
ngohongthai/BaseViperComponent
Example/BasePrj/BasePrj/Modules/BaseViewController/BaseViewController.swift
3
4262
// // BaseViewController.swift // BaseProject // // Created by HongThai,Ngo on 1/13/17. // Copyright © 2017 BeeSnippeter. All rights reserved. // import UIKit //import SVProgressHUD //import Toaster protocol BaseViewInterface: class { func displayNoNetwork(_ show: Bool) func onRetryCheckNetworkState() func showLoadingView() func showLoadingView(with message: String) func showSuccessHub() func showErrorHub() func hideLoadingView() } class BaseViewController: UIViewController { var basePresenter: BasePresenterInterface? var keyboardHeight: CGFloat = 0.0 override func viewDidLoad() { super.viewDidLoad() //Add notification when keyboard show and hide NotificationCenter.default.addObserver(self, selector: #selector(BaseViewController.keyboardWillShow(_:)), name: NSNotification.Name.UIKeyboardWillShow, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(BaseViewController.keyboardWillHide(_:)), name: NSNotification.Name.UIKeyboardWillHide, object: nil) } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) } override func viewDidDisappear(_ animated: Bool) { super.viewDidDisappear(animated) } deinit { NotificationCenter.default.removeObserver(self) } func keyboardWillShow(_ notification: Notification) { let userInfo = notification.userInfo! let keyboardScreenEndFrame = (userInfo[UIKeyboardFrameEndUserInfoKey] as! NSValue).cgRectValue let keyboardViewEndFrame = view.convert(keyboardScreenEndFrame, from: view.window) keyboardHeight = keyboardViewEndFrame.height } func keyboardWillHide(_ notification: Notification) { keyboardHeight = 0.0 } //MARK: - Helper functions fileprivate func showProgress() { /* main_thread { SVProgressHUD.setDefaultStyle(.dark) SVProgressHUD.setDefaultMaskType(.gradient) SVProgressHUD.show() } */ } fileprivate func showProgress(with message: String) { /* main_thread { SVProgressHUD.setDefaultStyle(.dark) SVProgressHUD.setDefaultMaskType(.gradient) SVProgressHUD.show(withStatus: message) } */ } fileprivate func showProgressError(with message: String) { /* main_thread { SVProgressHUD.setDefaultStyle(.dark) SVProgressHUD.setDefaultMaskType(.gradient) SVProgressHUD.showError(withStatus: message) SVProgressHUD.dismiss(withDelay: 1) } */ } fileprivate func showProgressSuccess(with message: String) { /* main_thread { SVProgressHUD.setDefaultStyle(.dark) SVProgressHUD.setDefaultMaskType(.gradient) SVProgressHUD.showSuccess(withStatus: message) SVProgressHUD.dismiss(withDelay: 1) } */ } fileprivate func hideProgress () { /* main_thread { SVProgressHUD.setDefaultMaskType(.gradient) SVProgressHUD.dismiss() } */ } func showToast(message: String) { /* let appearance = ToastView.appearance() appearance.backgroundColor = .lightGray appearance.textColor = .white appearance.font = UIFont.notoSansFont(ofSize: 16) appearance.textInsets = UIEdgeInsets(top: 15, left: 20, bottom: 15, right: 20) appearance.bottomOffsetPortrait = 10 appearance.cornerRadius = 10 Toast(text: message, duration: Delay.short).show() */ } } extension BaseViewController: BaseViewInterface { func displayNoNetwork(_ show: Bool) { //TODO } func onRetryCheckNetworkState() { //TODO } func showLoadingView() { self.showProgress() } func showLoadingView(with message: String) { self.showProgress(with: message) } func hideLoadingView() { self.hideProgress() } func showSuccessHub() { self.showProgressSuccess(with: "Success") } func showErrorHub() { self.showProgressError(with: "Error") } }
mit
c1a8d8e62f3abd2134f462885c8b06c7
27.218543
173
0.646797
5.09689
false
false
false
false
Evgeniy-Odesskiy/Bond
Bond/iOS/Bond+UIDatePicker.swift
1
3738
// // Bond+UIDatePicker.swift // Bond // // The MIT License (MIT) // // Copyright (c) 2015 Srdan Rasic (@srdanrasic) // // 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 DatePickerDynamicHelper { weak var control: UIDatePicker? var listener: (NSDate -> Void)? init(control: UIDatePicker) { self.control = control control.addTarget(self, action: Selector("valueChanged:"), forControlEvents: .ValueChanged) } dynamic func valueChanged(control: UIDatePicker) { self.listener?(control.date) } deinit { control?.removeTarget(self, action: nil, forControlEvents: .ValueChanged) } } class DatePickerDynamic<T>: InternalDynamic<NSDate> { let helper: DatePickerDynamicHelper init(control: UIDatePicker) { self.helper = DatePickerDynamicHelper(control: control) super.init(control.date) self.helper.listener = { [unowned self] in self.updatingFromSelf = true self.value = $0 self.updatingFromSelf = false } } } private var dateDynamicHandleUIDatePicker: UInt8 = 0; extension UIDatePicker /*: Dynamical, Bondable */ { public var dynDate: Dynamic<NSDate> { if let d: AnyObject = objc_getAssociatedObject(self, &dateDynamicHandleUIDatePicker) { return (d as? Dynamic<NSDate>)! } else { let d = DatePickerDynamic<NSDate>(control: self) let bond = Bond<NSDate>() { [weak self, weak d] v in if let s = self, d = d where !d.updatingFromSelf { s.date = v } } d.bindTo(bond, fire: false, strongly: false) d.retain(bond) objc_setAssociatedObject(self, &dateDynamicHandleUIDatePicker, d, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC) return d } } public var designatedDynamic: Dynamic<NSDate> { return self.dynDate } public var designatedBond: Bond<NSDate> { return self.dynDate.valueBond } } public func ->> (left: UIDatePicker, right: Bond<NSDate>) { left.designatedDynamic ->> right } public func ->> <U: Bondable where U.BondType == NSDate>(left: UIDatePicker, right: U) { left.designatedDynamic ->> right.designatedBond } public func ->> (left: UIDatePicker, right: UIDatePicker) { left.designatedDynamic ->> right.designatedBond } public func ->> (left: Dynamic<NSDate>, right: UIDatePicker) { left ->> right.designatedBond } public func <->> (left: UIDatePicker, right: UIDatePicker) { left.designatedDynamic <->> right.designatedDynamic } public func <->> (left: Dynamic<NSDate>, right: UIDatePicker) { left <->> right.designatedDynamic } public func <->> (left: UIDatePicker, right: Dynamic<NSDate>) { left.designatedDynamic <->> right }
mit
db0d078d2ef86c7d5a36a248c3cb5610
29.892562
129
0.702782
4.209459
false
false
false
false
Bouke/HAP
Sources/HAP/Base/Predefined/Characteristics/Characteristic.Logs.swift
1
1987
import Foundation public extension AnyCharacteristic { static func logs( _ value: Data = Data(), permissions: [CharacteristicPermission] = [.read, .events], description: String? = "Logs", format: CharacteristicFormat? = .tlv8, unit: CharacteristicUnit? = nil, maxLength: Int? = nil, maxValue: Double? = nil, minValue: Double? = nil, minStep: Double? = nil, validValues: [Double] = [], validValuesRange: Range<Double>? = nil ) -> AnyCharacteristic { AnyCharacteristic( PredefinedCharacteristic.logs( value, permissions: permissions, description: description, format: format, unit: unit, maxLength: maxLength, maxValue: maxValue, minValue: minValue, minStep: minStep, validValues: validValues, validValuesRange: validValuesRange) as Characteristic) } } public extension PredefinedCharacteristic { static func logs( _ value: Data = Data(), permissions: [CharacteristicPermission] = [.read, .events], description: String? = "Logs", format: CharacteristicFormat? = .tlv8, unit: CharacteristicUnit? = nil, maxLength: Int? = nil, maxValue: Double? = nil, minValue: Double? = nil, minStep: Double? = nil, validValues: [Double] = [], validValuesRange: Range<Double>? = nil ) -> GenericCharacteristic<Data> { GenericCharacteristic<Data>( type: .logs, value: value, permissions: permissions, description: description, format: format, unit: unit, maxLength: maxLength, maxValue: maxValue, minValue: minValue, minStep: minStep, validValues: validValues, validValuesRange: validValuesRange) } }
mit
2d9e989722c6a2a22766d7e96492df6a
31.57377
67
0.56467
5.341398
false
false
false
false
subhajitregor/SHRestClientExample
SHRestClient/ReachabilitySwift/Reachability.swift
1
11001
/* Copyright (c) 2014, Ashley Mills All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ import SystemConfiguration import Foundation public enum ReachabilityError: Error { case FailedToCreateWithAddress(sockaddr_in) case FailedToCreateWithHostname(String) case UnableToSetCallback case UnableToSetDispatchQueue } @available(*, unavailable, renamed: "Notification.Name.reachabilityChanged") public let ReachabilityChangedNotification = NSNotification.Name("ReachabilityChangedNotification") extension Notification.Name { public static let reachabilityChanged = Notification.Name("reachabilityChanged") } func callback(reachability: SCNetworkReachability, flags: SCNetworkReachabilityFlags, info: UnsafeMutableRawPointer?) { guard let info = info else { return } let reachability = Unmanaged<Reachability>.fromOpaque(info).takeUnretainedValue() reachability.reachabilityChanged() } public class Reachability { public typealias NetworkReachable = (Reachability) -> () public typealias NetworkUnreachable = (Reachability) -> () @available(*, unavailable, renamed: "Connection") public enum NetworkStatus: CustomStringConvertible { case notReachable, reachableViaWiFi, reachableViaWWAN public var description: String { switch self { case .reachableViaWWAN: return "Cellular" case .reachableViaWiFi: return "WiFi" case .notReachable: return "No Connection" } } } public enum Connection: CustomStringConvertible { case none, wifi, cellular public var description: String { switch self { case .cellular: return "Cellular" case .wifi: return "WiFi" case .none: return "No Connection" } } } public var whenReachable: NetworkReachable? public var whenUnreachable: NetworkUnreachable? @available(*, deprecated: 4.0, renamed: "allowsCellularConnection") public let reachableOnWWAN: Bool = true /// Set to `false` to force Reachability.connection to .none when on cellular connection (default value `true`) public var allowsCellularConnection: Bool // The notification center on which "reachability changed" events are being posted public var notificationCenter: NotificationCenter = NotificationCenter.default @available(*, deprecated: 4.0, renamed: "connection.description") public var currentReachabilityString: String { return "\(connection)" } @available(*, unavailable, renamed: "connection") public var currentReachabilityStatus: Connection { return connection } public var connection: Connection { guard isReachableFlagSet else { return .none } // If we're reachable, but not on an iOS device (i.e. simulator), we must be on WiFi guard isRunningOnDevice else { return .wifi } var connection = Connection.none if !isConnectionRequiredFlagSet { connection = .wifi } if isConnectionOnTrafficOrDemandFlagSet { if !isInterventionRequiredFlagSet { connection = .wifi } } if isOnWWANFlagSet { if !allowsCellularConnection { connection = .none } else { connection = .cellular } } return connection } fileprivate var previousFlags: SCNetworkReachabilityFlags? fileprivate var isRunningOnDevice: Bool = { #if targetEnvironment(simulator) return false #else return true #endif }() fileprivate var notifierRunning = false fileprivate let reachabilityRef: SCNetworkReachability fileprivate let reachabilitySerialQueue = DispatchQueue(label: "uk.co.ashleymills.reachability") fileprivate var usingHostname = false required public init(reachabilityRef: SCNetworkReachability, usingHostname: Bool = false) { allowsCellularConnection = true self.reachabilityRef = reachabilityRef self.usingHostname = usingHostname } public convenience init?(hostname: String) { guard let ref = SCNetworkReachabilityCreateWithName(nil, hostname) else { return nil } self.init(reachabilityRef: ref, usingHostname: true) } public convenience init?() { var zeroAddress = sockaddr() zeroAddress.sa_len = UInt8(MemoryLayout<sockaddr>.size) zeroAddress.sa_family = sa_family_t(AF_INET) guard let ref = SCNetworkReachabilityCreateWithAddress(nil, &zeroAddress) else { return nil } self.init(reachabilityRef: ref) } deinit { stopNotifier() } } public extension Reachability { // MARK: - *** Notifier methods *** func startNotifier() throws { guard !notifierRunning else { return } var context = SCNetworkReachabilityContext(version: 0, info: nil, retain: nil, release: nil, copyDescription: nil) context.info = UnsafeMutableRawPointer(Unmanaged<Reachability>.passUnretained(self).toOpaque()) if !SCNetworkReachabilitySetCallback(reachabilityRef, callback, &context) { stopNotifier() throw ReachabilityError.UnableToSetCallback } if !SCNetworkReachabilitySetDispatchQueue(reachabilityRef, reachabilitySerialQueue) { stopNotifier() throw ReachabilityError.UnableToSetDispatchQueue } // Perform an initial check reachabilitySerialQueue.async { self.reachabilityChanged() } notifierRunning = true } func stopNotifier() { defer { notifierRunning = false } SCNetworkReachabilitySetCallback(reachabilityRef, nil, nil) SCNetworkReachabilitySetDispatchQueue(reachabilityRef, nil) } // MARK: - *** Connection test methods *** @available(*, deprecated: 4.0, message: "Please use `connection != .none`") var isReachable: Bool { guard isReachableFlagSet else { return false } if isConnectionRequiredAndTransientFlagSet { return false } if isRunningOnDevice { if isOnWWANFlagSet && !reachableOnWWAN { // We don't want to connect when on cellular connection return false } } return true } @available(*, deprecated: 4.0, message: "Please use `connection == .cellular`") var isReachableViaWWAN: Bool { // Check we're not on the simulator, we're REACHABLE and check we're on WWAN return isRunningOnDevice && isReachableFlagSet && isOnWWANFlagSet } @available(*, deprecated: 4.0, message: "Please use `connection == .wifi`") var isReachableViaWiFi: Bool { // Check we're reachable guard isReachableFlagSet else { return false } // If reachable we're reachable, but not on an iOS device (i.e. simulator), we must be on WiFi guard isRunningOnDevice else { return true } // Check we're NOT on WWAN return !isOnWWANFlagSet } var description: String { let W = isRunningOnDevice ? (isOnWWANFlagSet ? "W" : "-") : "X" let R = isReachableFlagSet ? "R" : "-" let c = isConnectionRequiredFlagSet ? "c" : "-" let t = isTransientConnectionFlagSet ? "t" : "-" let i = isInterventionRequiredFlagSet ? "i" : "-" let C = isConnectionOnTrafficFlagSet ? "C" : "-" let D = isConnectionOnDemandFlagSet ? "D" : "-" let l = isLocalAddressFlagSet ? "l" : "-" let d = isDirectFlagSet ? "d" : "-" return "\(W)\(R) \(c)\(t)\(i)\(C)\(D)\(l)\(d)" } } fileprivate extension Reachability { func reachabilityChanged() { guard previousFlags != flags else { return } let block = connection != .none ? whenReachable : whenUnreachable DispatchQueue.main.async { if self.usingHostname { print("USING HOSTNAME ABOUT TO CALL BLOCK") } block?(self) self.notificationCenter.post(name: .reachabilityChanged, object:self) } previousFlags = flags } var isOnWWANFlagSet: Bool { #if os(iOS) return flags.contains(.isWWAN) #else return false #endif } var isReachableFlagSet: Bool { return flags.contains(.reachable) } var isConnectionRequiredFlagSet: Bool { return flags.contains(.connectionRequired) } var isInterventionRequiredFlagSet: Bool { return flags.contains(.interventionRequired) } var isConnectionOnTrafficFlagSet: Bool { return flags.contains(.connectionOnTraffic) } var isConnectionOnDemandFlagSet: Bool { return flags.contains(.connectionOnDemand) } var isConnectionOnTrafficOrDemandFlagSet: Bool { return !flags.intersection([.connectionOnTraffic, .connectionOnDemand]).isEmpty } var isTransientConnectionFlagSet: Bool { return flags.contains(.transientConnection) } var isLocalAddressFlagSet: Bool { return flags.contains(.isLocalAddress) } var isDirectFlagSet: Bool { return flags.contains(.isDirect) } var isConnectionRequiredAndTransientFlagSet: Bool { return flags.intersection([.connectionRequired, .transientConnection]) == [.connectionRequired, .transientConnection] } var flags: SCNetworkReachabilityFlags { var flags = SCNetworkReachabilityFlags() if SCNetworkReachabilityGetFlags(reachabilityRef, &flags) { print("Returning flags \(flags)") return flags } else { return SCNetworkReachabilityFlags() } } }
apache-2.0
981cd1c0f5b74a5c540a8a5497169148
33.058824
125
0.671303
5.572948
false
false
false
false
interstateone/Fresh
Fresh/Components/Main Window/MainWindowController.swift
1
1469
// // MainWindowController.swift // Fresh // // Created by Brandon Evans on 2015-12-30. // Copyright © 2015 Brandon Evans. All rights reserved. // import Cocoa class MainWindowController: NSWindowController { var presenter: MainWindowPresenter? var loginViewController: FSHLoginViewController? var listViewController: SoundListViewController? var nowPlayingViewController: NowPlayingViewController? override func windowDidLoad() { window?.title = "Fresh" presenter?.initializeView() } func revealNowPlayingView() { guard let nowPlayingViewController = nowPlayingViewController where nowPlayingViewController.parentViewController == nil else { return } window?.addTitlebarAccessoryViewController(nowPlayingViewController) window?.titleVisibility = .Hidden } func hideNowPlayingView() { guard let nowPlayingViewController = nowPlayingViewController where nowPlayingViewController.parentViewController != nil else { return } nowPlayingViewController.removeFromParentViewController() window?.titleVisibility = .Visible } func transitionToSoundList() { if let listViewController = listViewController { window?.contentView = listViewController.view } } func transitionToLogin() { if let loginViewController = loginViewController { window?.contentView = loginViewController.view } } }
mit
f6643d9872446bb4c8c8379ea54b3d2f
29.583333
144
0.718665
5.895582
false
false
false
false
mlgoogle/viossvc
viossvc/General/Extension/ButtonEx.swift
1
796
// // ButtonEx.swift // HappyTravel // // Created by 陈奕涛 on 16/10/20. // Copyright © 2016年 陈奕涛. All rights reserved. // import Foundation extension UIButton { func setImageAndTitleLeft(){ let SPACING:CGFloat = 6.0 setImageAndTitleLeft(SPACING) } //imageView在上,label在下 func setImageAndTitleLeft(spacing:CGFloat){ let imageSize = imageView?.frame.size let titleSize = titleLabel?.frame.size; let totalHeight = imageSize!.height + titleSize!.height + spacing imageEdgeInsets = UIEdgeInsetsMake(-(totalHeight - imageSize!.height), 0.0, 0.0, -titleSize!.width) titleEdgeInsets = UIEdgeInsetsMake(0, -imageSize!.width, -(totalHeight - titleSize!.height), 0.0) } }
apache-2.0
8e446db99bfeb4679e08256d82a08159
25.689655
107
0.644243
4.089947
false
false
false
false
redlock/SwiftyDeepstream
SwiftyDeepstream/Classes/deepstream/DeepstreamFactory.swift
1
3766
// // DeepstreamFactory.swift // deepstreamSwiftTest // // Created by Redlock on 4/9/17. // Copyright © 2017 JiblaTech. All rights reserved. // import Foundation import JAYSON /** * A singleton to stop you ( the developer ) from having to pass around the deepstream client reference * around the codebase, making application development easier in frameworks such android. * * * Currently self only contains a single deepstream client; */ /** * DeepstreamFactory is a map of all url connections created */ public class DeepstreamFactory { var clients: [String: DeepstreamClient] = [:] var lastUrl: String? = nil public static let instance = DeepstreamFactory() private init() { } /** * Returns the last client that was created. self is useful for most applications that * only require a single connection. The first time a client is connected however it has to be * via [DeepstreamFactory.getClient] or [DeepstreamFactory.getClient] * @return A deepstream client */ var client: DeepstreamClient? { guard let url = self.lastUrl else { return nil } return self.clients[url] } /** * Returns a client that was previous created via the same url using self method or [DeepstreamFactory.getClient]. * If one wasn't created, it creates it first and stores it for future reference. * @param url The url to connect to, also the key used to retrieve in future calls * * * @return A deepstream client * * * @throws URISyntaxException An error if the url syntax is invalid */ var onConnectionStateChange: ConnectionStateListener? public func getClient(url: String, onConnected: @escaping (_ client:DeepstreamClient) -> Void) -> DeepstreamClient { var client = self.clients[url] self.lastUrl = url if (clientDoesNotExist(client: client)) { client = DeepstreamClient(url: url,deepstreamConfig: DeepstreamConfig(), endpointFactory: SwiftEndpointFactory()) self.clients[url] = client } self.onConnectionStateChange = client?.addConnectionChangeListener(onConnectionStateChanged: { ( _ connectionState: ConnectionState) in print(connectionState) if connectionState == ConnectionState.AWAITING_AUTHENTICATION { onConnected(client!) } }) return client! } /** * Returns a client that was previous created via the same url using self method or [DeepstreamFactory.getClient]. * If one wasn't created, it creates it first and stores it for future reference. * @param url The url to connect to, also the key used to retrieve in future calls * * * @param options The options to use within the deepstream connection * * * @return A deepstream client * * * @throws URISyntaxException An error if the url syntax is invalid * * * @throws InvalidDeepstreamConfig An exception if any of the options are invalid */ func getClient(url: String, options: JAYSON) -> DeepstreamClient { var client = self.clients[url] if clientDoesNotExist(client: client) { client = DeepstreamClient(url: url,deepstreamConfig: DeepstreamConfig(props: options), endpointFactory: SwiftEndpointFactory()) self.clients[url] = client } return client! } private func clientDoesNotExist(client: DeepstreamClient?) -> Bool { return client == nil || client?.connectionState == .CLOSED || client?.connectionState == .ERROR } }
mit
6ccc7138277c45999b80bfe1ff3eadf7
32.026316
144
0.646215
4.648148
false
false
false
false
fe9lix/Protium
iOS/ProtiumTests/TestExtensions.swift
1
2724
import XCTest import RxSwift import RxCocoa @testable import Protium extension XCTestCase { // Emits the passed in elements at the specified time intervals, e.g.: // stubObservable([("", 0.1), ("cars", 0.2), ("cats", 0.3)]) // would emit "" after 0.1 seconds, "cars" after 0.2, and "cats" after 0.3. func stubObservable<Element>(_ elements: [(Element, TimeInterval)]) -> Observable<Element> { return Observable.create { observer in var remainingElements = elements if remainingElements.isEmpty { observer.on(.completed) return Disposables.create() } var scheduleTimer: (((Element, TimeInterval)) -> Cancelable)! var timerCancel: Cancelable! var previousTime: TimeInterval = 0.0 scheduleTimer = { element in let timer = DispatchSource.makeTimerSource(queue: DispatchQueue.global()) timer.scheduleOneshot(deadline: DispatchTime.now() + (element.1 - previousTime), leeway: .nanoseconds(0)) previousTime = element.1 timerCancel = Disposables.create { timer.cancel() } timer.setEventHandler { if timerCancel.isDisposed { return } observer.on(.next(element.0)) if remainingElements.isEmpty { observer.on(.completed) } else { let nextElement = remainingElements.removeFirst() timerCancel = scheduleTimer(nextElement) } } timer.resume() return timerCancel } timerCancel = scheduleTimer(remainingElements.removeFirst()) return Disposables.create { timerCancel.dispose() } } } func stubDriver<Element>(_ elements: [(Element, TimeInterval)]) -> Driver<Element> { return stubObservable(elements).asDriver(onErrorRecover: { error -> Driver<Element> in print("This can't error out.") return Driver.never() }) } } // Convenience extensions for easier Model/Presentation Model construction. extension Gif { init(_ url: URL) { self.id = "" self.url = url self.embedURL = nil self.originalStillURL = nil self.originalVideoURL = nil } } extension GifPM { init(_ id: String) { self.init(Gif(id: id)) } }
mit
7e3a541affb0fb99dcdd363f4a331816
33.05
121
0.519824
5.426295
false
false
false
false
nessBautista/iOSBackup
iOSNotebook/Pods/RxCocoa/RxCocoa/Traits/ControlEvent.swift
12
2439
// // ControlEvent.swift // RxCocoa // // Created by Krunoslav Zaher on 8/28/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // import RxSwift /// Protocol that enables extension of `ControlEvent`. public protocol ControlEventType : ObservableType { /// - returns: `ControlEvent` interface func asControlEvent() -> ControlEvent<E> } /** Trait for `Observable`/`ObservableType` that represents event on UI element. It's properties are: - it never fails - it won't send any initial value on subscription - it will `Complete` sequence on control being deallocated - it never errors out - it delivers events on `MainScheduler.instance` **The implementation of `ControlEvent` will ensure that sequence of events is being subscribed on main scheduler (`subscribeOn(ConcurrentMainScheduler.instance)` behavior).** **It is implementor's responsibility to make sure that that all other properties enumerated above are satisfied.** **If they aren't, then using this trait communicates wrong properties and could potentially break someone's code.** **In case `events` observable sequence that is being passed into initializer doesn't satisfy all enumerated properties, please don't use this trait.** */ public struct ControlEvent<PropertyType> : ControlEventType { public typealias E = PropertyType let _events: Observable<PropertyType> /// Initializes control event with a observable sequence that represents events. /// /// - parameter events: Observable sequence that represents events. /// - returns: Control event created with a observable sequence of events. public init<Ev: ObservableType>(events: Ev) where Ev.E == E { _events = events.subscribeOn(ConcurrentMainScheduler.instance) } /// Subscribes an observer to control events. /// /// - parameter observer: Observer to subscribe to events. /// - returns: Disposable object that can be used to unsubscribe the observer from receiving control events. public func subscribe<O : ObserverType>(_ observer: O) -> Disposable where O.E == E { return _events.subscribe(observer) } /// - returns: `Observable` interface. public func asObservable() -> Observable<E> { return _events } /// - returns: `ControlEvent` interface. public func asControlEvent() -> ControlEvent<E> { return self } }
cc0-1.0
68209167a14c6387a5d7af8d0d8677b1
34.333333
119
0.704676
4.935223
false
false
false
false
lucas34/SwiftQueue
Sources/SwiftQueue/Constraint+Network.swift
1
4464
// The MIT License (MIT) // // Copyright (c) 2022 Lucas Nelaupe // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. import Foundation import Network /// Kind of connectivity required for the job to run public enum NetworkType: Int, Codable { /// Job will run regardless the connectivity of the platform case any = 0 /// Requires at least cellular such as 2G, 3G, 4G, LTE or Wifi case cellular = 1 /// Device has to be connected to Wifi or Lan case wifi = 2 } internal protocol NetworkMonitor { func hasCorrectNetworkType(require: NetworkType) -> Bool func startMonitoring(networkType: NetworkType, operation: SqOperation) } internal class NWPathMonitorNetworkMonitor: NetworkMonitor { private let monitor = NWPathMonitor() func hasCorrectNetworkType(require: NetworkType) -> Bool { if monitor.currentPath.status == .satisfied { monitor.pathUpdateHandler = nil return true } else { return false } } func startMonitoring(networkType: NetworkType, operation: SqOperation) { monitor.pathUpdateHandler = { [monitor, operation, networkType] path in guard path.status == .satisfied else { operation.logger.log(.verbose, jobId: operation.name, message: "Unsatisfied network requirement") return } /// If network type is wifi, make sure the path is not using cellular, otherwise wait if networkType == .wifi, path.usesInterfaceType(.cellular) { operation.logger.log(.verbose, jobId: operation.name, message: "Unsatisfied network requirement") return } monitor.cancel() monitor.pathUpdateHandler = nil operation.run() } monitor.start(queue: operation.dispatchQueue) } } internal final class NetworkConstraint: SimpleConstraint, CodableConstraint { /// Require a certain connectivity type internal let networkType: NetworkType private let monitor: NetworkMonitor required init(networkType: NetworkType, monitor: NetworkMonitor) { assert(networkType != .any) self.networkType = networkType self.monitor = monitor } convenience init(networkType: NetworkType) { self.init(networkType: networkType, monitor: NWPathMonitorNetworkMonitor()) } convenience init?(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: NetworkConstraintKey.self) if container.contains(.requireNetwork) { try self.init(networkType: container.decode(NetworkType.self, forKey: .requireNetwork)) } else { return nil } } override func willSchedule(queue: SqOperationQueue, operation: SqOperation) throws { assert(operation.dispatchQueue != .main) } override func run(operation: SqOperation) -> Bool { if monitor.hasCorrectNetworkType(require: networkType) { return true } monitor.startMonitoring(networkType: networkType, operation: operation) return false } private enum NetworkConstraintKey: String, CodingKey { case requireNetwork } func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: NetworkConstraintKey.self) try container.encode(networkType, forKey: .requireNetwork) } }
mit
aa9213e68074c85c9e86efa6b4e677f2
34.428571
113
0.689068
4.733828
false
false
false
false
ibm-wearables-sdk-for-mobile/ios
RecordApp/RecordApp/RecordingViewController.swift
2
10430
/* * © Copyright 2015 IBM Corp. * * Licensed under the Mobile Edge iOS Framework License (the "License"); * you may not use this file except in compliance with the License. You may find * a copy of the license in the license.txt file in this package. * * 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 import IBMMobileEdge class RecordingViewController: UIViewController { @IBOutlet weak var imageView: UIImageView! @IBOutlet weak var iterationLabel: UILabel! @IBOutlet weak var statusLabel: UILabel! @IBOutlet weak var counter: UILabel! @IBOutlet weak var stopButton: UIButton! @IBOutlet weak var status: UILabel! @IBOutlet weak var spinner: UIActivityIndicatorView! @IBOutlet weak var continueButton: UIButton! @IBOutlet weak var pauseButton: UIButton! var timer:NSTimer! var counterValue = 3 let controller = AppDelegate.controller var id = "" var url = "" var uuid = "" var gesuteCouner = 1 var recordingDots = 0 var sensitivity:Double! var temp:NSString! let accelerometerListenerName = "accelerometerListener" let gyroscopeListenerName = "gyroscopeListener" var isDataSyncronizationDone = false var logFile = "" let minimunNumberOfIterations = 4 //minmum number of iteration before the user can save the gesture override func viewDidLoad() { super.viewDidLoad() self.title = AppDelegate.trainingGestureName statusLabel.hidden = true continueButton.hidden = false stopButton.hidden = true id = "" url = "" uuid = "" gesuteCouner = 1 sensitivity = nil logFile = LogUtils.createFileForNewGesture(AppDelegate.trainingGestureName) startCounter() } func startCounter(){ timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: "runCounterCode", userInfo: nil, repeats: true) spinner.stopAnimating() imageView.hidden = true continueButton.hidden = true stopButton.hidden = true disableButtons() //handle the counter counterValue = 3 counter.hidden = false counter.text = "\(counterValue)" setStatusText("Get Ready") setIterationNumber(gesuteCouner) } func runCounterCode(){ if (counterValue == 1){ counter.hidden = true startRecording() timer.invalidate() } else{ counter.text = "\(counterValue-1)" counterValue-- } } func startRecording(){ pauseButton.hidden = false enableButtons() //clear the previous data print("Clean") AppDelegate.accelerometerRecordData.removeAll() AppDelegate.gyroscopeRecordData.removeAll() //turn on the sensonrs again turnSensorsOn() spinner.startAnimating() status.hidden = false setStatusText("Recording") } override func viewDidAppear(animated: Bool){ super.viewDidAppear(animated) //clear the old data print("Clean") AppDelegate.accelerometerRecordData.removeAll() AppDelegate.gyroscopeRecordData.removeAll() controller.sensors.accelerometer.registerListener(accelerometerDataChanged, withName:accelerometerListenerName) controller.sensors.gyroscope.registerListener(gyroscopeDataChanged, withName: gyroscopeListenerName) } override func viewDidDisappear(animated: Bool){ super.viewDidDisappear(animated) turnSensorsOff() controller.sensors.accelerometer.unregisterListener(accelerometerListenerName) controller.sensors.gyroscope.unregisterListener(gyroscopeListenerName) } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == "moveToFinal" { if let resultViewController = segue.destinationViewController as? ResultViewController{ resultViewController.url = url resultViewController.uuid = uuid resultViewController.sensitivity = sensitivity } } } func setStatusText(text:String){ status.text = text } func setIterationNumber(iteration:Int){ iterationLabel.text = "Iteration \(iteration)" } func accelerometerDataChanged(data:AccelerometerData) { AppDelegate.accelerometerRecordData.append([data.x,data.y,data.z]) makeDataRateCorrection() } func gyroscopeDataChanged(data:GyroscopeData){ AppDelegate.gyroscopeRecordData.append([data.x,data.y,data.z]) makeDataRateCorrection() } //fix the data leght so that the data will synsconized func makeDataRateCorrection(){ let accelerometerLength = AppDelegate.accelerometerRecordData.count let gyroscopeLength = AppDelegate.gyroscopeRecordData.count //data syncronization done only after the first set of readings (check when one leght of the data is equal to 4) if (!isDataSyncronizationDone && gyroscopeLength > 3 && accelerometerLength > 3){ //need to dropt the first acceleroment data so that the data will be of the same legth (syncronized) if (accelerometerLength > gyroscopeLength){ AppDelegate.accelerometerRecordData.removeFirst(accelerometerLength - gyroscopeLength) print("Info: data syncronization fix. droped first \(accelerometerLength - gyroscopeLength) reads of accelerometer") } else if (gyroscopeLength > accelerometerLength){ AppDelegate.gyroscopeRecordData.removeFirst(gyroscopeLength - accelerometerLength) print("Info: data syncronization fix. droped first \(gyroscopeLength - accelerometerLength) reads of gyroscope") } isDataSyncronizationDone = true } } @IBAction func onStopButtonClicked(sender: AnyObject) { turnSensorsOff() self.performSegueWithIdentifier("moveToFinal", sender: self) } @IBAction func onPauseButtonClicked(sender: AnyObject) { disableButtons() continueButton.hidden = true status.hidden = false setStatusText("Validating") turnSensorsOff() //validate the the date usign the service RequestUtils.sendTrainRequest(AppDelegate.accelerometerRecordData, gyroscopeData: AppDelegate.gyroscopeRecordData, uuid: id, onSuccess: onTrainRequestSuccess, onFailure: onTrainRequestError) } func disableButtons(){ pauseButton.enabled = false pauseButton.alpha = 0.5 continueButton.enabled = false continueButton.alpha = 0.5 } func enableButtons() { pauseButton.enabled = true pauseButton.alpha = 1 continueButton.enabled = true continueButton.alpha = 1 } func turnSensorsOn(){ print("On") //this will enable data syncronization again isDataSyncronizationDone = false controller.sensors.accelerometer.on() controller.sensors.gyroscope.on() } func turnSensorsOff(){ print("Off") controller.sensors.accelerometer.off() controller.sensors.gyroscope.off() } @IBAction func onContinueButtonClicked(sender: AnyObject) { startCounter() } //this function is called after each succesul recorded iteration func onTrainRequestSuccess(result:NSDictionary!){ if let url = result["jsURI"] { self.url = url as! String } if let id = result["id"] { self.id = id as! String } if let uuid = result["UUID"] { self.uuid = "\(uuid)"//id as! String } if let sensitivity = result["sensitivity"] { self.sensitivity = Double(sensitivity as! String) } if let sensitivity = result["sensitivity"], let length = result["length"]{ dispatch_async(dispatch_get_main_queue()) { self.statusLabel.hidden = false self.statusLabel.text = "Currect sensitivity: \(sensitivity). Lenght: \(length)" } } //save the current iteration to a log file print("save the data to log") LogUtils.saveLog(logFile, iterationNumber: gesuteCouner, accelerometerDataArray: AppDelegate.accelerometerRecordData, gyroscopeDataArray: AppDelegate.gyroscopeRecordData) dispatch_async(dispatch_get_main_queue()) { self.spinner.stopAnimating() self.enableButtons() self.setStatusText("Iteration Accepted!") self.imageView.hidden = false self.imageView.image = UIImage(named: "success") self.continueButton.hidden = false self.gesuteCouner++ if (self.gesuteCouner > self.minimunNumberOfIterations){ self.stopButton.hidden = false } } } //this function is called in case the recorded iteration was rejected func onTrainRequestError(msg:String!){ dispatch_async(dispatch_get_main_queue()) { self.spinner.stopAnimating() self.enableButtons() self.continueButton.hidden = false self.setStatusText("Iteration Failed!") self.imageView.hidden = false self.imageView.image = UIImage(named: "failure") Utils.showMsgDialog(self, withMessage:msg) } } }
epl-1.0
ed6b475d68ebbcf7d28faed5dd5bc30a
31.489097
198
0.617413
5.301983
false
false
false
false
hughbe/semi-modal-controller
src/HBZoomSemiModalViewController.swift
1
2430
// // HBZoomSemiModalViewController.swift // Semi Modal // // Created by Hugh Bellamy on 29/06/2015. // Copyright (c) 2015 Hugh Bellamy. All rights reserved. // import UIKit enum HBZoomDirection { case ToRight case ToLeft } @IBDesignable class HBZoomSemiModalViewController: HBSlideSemiModalNavigationController, HBSlideModalSubclassing { @IBInspectable var zoomExtraWidthPercentage: CGFloat = 0.2 override func startedDragging() { } var previousInset: CGFloat? var zoomDirection = HBZoomDirection.ToRight override func handleDragged(heightPercentage: CGFloat) { let progress = 1 - (heightPercentage) let newInset = progress * superview.frame.width if let previousInset = previousInset where previousInset == newInset { return } previousInset = newInset if zoomDirection == .ToRight { setLeadingInset(newInset, updateConstraints: false) } else if zoomDirection == .ToLeft { setTrailingInset(newInset, updateConstraints: false) } } override func endedDragging(heightPercentage: CGFloat) { if !shouldDismiss { return } let progress = heightPercentage if progress > dismissHeightPercentageThreshold { if zoomDirection == .ToRight { setLeadingInset(nil, updateConstraints: false) } else if zoomDirection == .ToLeft { setTrailingInset(nil, updateConstraints: false) } setTopInset(nil, updateConstraints: false) superview.setNeedsUpdateConstraints() UIView.animateWithDuration(NSTimeInterval(showHideAnimationDuration), animations: { self.superview.layoutIfNeeded() }) } else { UIView.animateWithDuration(NSTimeInterval(showHideAnimationDuration), animations: { if self.zoomDirection == .ToRight { self.view.frame.origin = CGPointMake(self.superview.frame.width, self.superview.frame.height) } else if self.zoomDirection == .ToLeft { self.view.frame.origin = CGPointMake(-self.superview.frame.width, self.superview.frame.height) } }, completion: { (finished) in self.hide() }) } } }
mit
cbc46e60414fcbee92ca64a0cb012985
32.75
114
0.615638
5.181237
false
false
false
false
coderMONSTER/ioscelebrity
YStar/YStar/Scenes/Controller/BindBankCardVC.swift
1
5147
// // BindBankCardVC.swift // YStar // // Created by MONSTER on 2017/7/6. // Copyright © 2017年 com.yundian. All rights reserved. // import UIKit import SVProgressHUD class BindBankCardVC: BaseTableViewController { @IBOutlet weak var starNameTextField: UITextField! // 持卡人姓名 @IBOutlet weak var starCardNumTextField: UITextField! // 卡号 @IBOutlet weak var starPhoneNumTextField: UITextField! // 手机号 @IBOutlet weak var verificationCodeTextField: UITextField! // 验证码 @IBOutlet weak var sendCodeButton: UIButton! // 发送验证码按钮 @IBOutlet weak var bindBankButton: UIButton! // 绑定银行卡按钮 fileprivate var timer : Timer? // 定时器 fileprivate var codeTimer = 60 // 时间区间 var timeStamp = "" // 时间戳 var vToken = "" // token override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) self.navigationController?.setNavigationBarHidden(false, animated: true) } override func viewDidLoad() { super.viewDidLoad() setupUI() } func setupUI() { self.title = "绑定银行卡" self.tableView.tableFooterView = UIView.init() } } // MARK: - 按钮相关操作 extension BindBankCardVC { // 发送验证码Action @IBAction func sendCodeAction(_ sender: UIButton) { if !checkTextFieldEmpty([starNameTextField,starCardNumTextField,starPhoneNumTextField]) { return } if !isTelNumber(num: starPhoneNumTextField.text!) { SVProgressHUD.showError(withStatus: "请您输入正确的手机号") return } let codeModel = SendVerificationCodeRequestModel() codeModel.phone = self.starPhoneNumTextField.text! SVProgressHUD.showProgressMessage(ProgressMessage: "") AppAPIHelper.commen().sendVerificationCode(model: codeModel, complete: {[weak self] (response) -> ()? in SVProgressHUD.dismiss() self?.sendCodeButton.isEnabled = true if let object = response as? verifyCodeModel { if object.result == 1 { self?.timer = Timer.scheduledTimer(timeInterval: 1, target: self!, selector: #selector(self?.updateSendCodeButtonTitle), userInfo: nil, repeats: true) self?.timeStamp = object.timeStamp self?.vToken = object.vToken } } return nil }) { (error) -> ()? in self.didRequestError(error) self.sendCodeButton.isEnabled = true return nil } } // MARK: - 更新sendCodeButton秒数 func updateSendCodeButtonTitle() { if codeTimer == 0 { sendCodeButton.isEnabled = true sendCodeButton.setTitle("重新发送", for: .normal) codeTimer = 60 timer?.invalidate() sendCodeButton.setTitleColor(UIColor.init(hexString: "FFFFFF"), for: .normal) sendCodeButton.backgroundColor = UIColor(hexString: "FB9938") return } sendCodeButton.isEnabled = false codeTimer = codeTimer - 1 let title: String = "\(codeTimer)秒重新发送" sendCodeButton.setTitle(title, for: .normal) sendCodeButton.setTitleColor(UIColor.init(hexString: "000000"), for: .normal) sendCodeButton.backgroundColor = UIColor(hexString: "ECECEC") } // MARK: - 绑定银行卡Action @IBAction func bindBankAction(_ sender: UIButton) { if !checkTextFieldEmpty([starNameTextField,starCardNumTextField,starPhoneNumTextField,verificationCodeTextField]) { return } if !isTelNumber(num: starPhoneNumTextField.text!) { SVProgressHUD.showError(withStatus: "请您输入正确的手机号") return } let stringToken = AppConst.pwdKey + self.timeStamp + verificationCodeTextField.text! + starPhoneNumTextField.text! if stringToken.md5() != self.vToken { SVProgressHUD.showErrorMessage(ErrorMessage: "验证码错误", ForDuration: 1.0, completion: nil) return } let model = BindCardRequestModel() model.bankUsername = starNameTextField.text! model.account = starCardNumTextField.text! AppAPIHelper.commen().bindCard(model: model, complete: {[weak self] (response) -> ()? in if let objects = response as? BindBankModel { if objects.cardNO.length() != 0 { SVProgressHUD.showSuccessMessage(SuccessMessage: "绑定成功", ForDuration: 2.0, completion: { _ = self?.navigationController?.popViewController(animated: true) }) } else { SVProgressHUD.showErrorMessage(ErrorMessage: "绑定失败", ForDuration: 2.0, completion: nil) } } return nil }, error: errorBlockFunc()) } }
mit
deb15383824e75db0769696cffd0aba0
33.760563
170
0.605146
4.81561
false
false
false
false
wibosco/WhiteBoardCodingChallenges
WhiteBoardCodingChallenges/Challenges/HackerRank/CavityMap/CavityMap.swift
1
2048
// // CavityMap.swift // WhiteBoardCodingChallenges // // Created by William Boles on 10/05/2016. // Copyright © 2016 Boles. All rights reserved. // import UIKit //https://www.hackerrank.com/challenges/cavity-map class CavityMap: NSObject { class func generateCavityMap(map: [String]) -> [String] { let cavity = "X" var cavityMap = map if map.count > 2 { for rowIndex in 1..<(cavityMap.count - 1) { let row = cavityMap[rowIndex] var cavityRow = row for cellIndex in cavityRow.indices { if cellIndex != cavityRow.startIndex && cellIndex != cavityRow.index(cavityRow.endIndex, offsetBy: -1) { let cell = String(cavityRow[cellIndex]) let previousCellInRow = String(cavityRow[cavityRow.index(cellIndex, offsetBy: -1)]) let nextCellInRow = String(cavityRow[cavityRow.index(cellIndex, offsetBy: 1)]) let previousRow = cavityMap[(rowIndex - 1)] let nextRow = cavityMap[(rowIndex + 1)] let cellInPreviousRow = String(previousRow[cellIndex]) let cellInNextRow = String(nextRow[cellIndex]) if !(cell == cavity || previousCellInRow == cavity || nextCellInRow == cavity || cellInPreviousRow == cavity || cellInNextRow == cavity) { if Int(cell)! > Int(previousCellInRow)! && Int(cell)! > Int(nextCellInRow)! && Int(cell)! > Int(cellInPreviousRow)! && Int(cell)! > Int(cellInNextRow)! { let range = cellIndex..<cavityRow.index(cellIndex, offsetBy: 1) cavityRow.replaceSubrange(range, with: cavity) } } } } cavityMap[rowIndex] = cavityRow } } return cavityMap } }
mit
9a3dea9e70711bf10f965fb76f302149
36.907407
181
0.519785
4.430736
false
false
false
false
Shashi717/ImmiGuide
ImmiGuide/ImmiGuide/AppDelegate.swift
1
2816
// // AppDelegate.swift // ImmiGuide // // Created by Madushani Lekam Wasam Liyanage on 2/17/17. // Copyright © 2017 Madushani Lekam Wasam Liyanage. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { let userDefaults = UserDefaults.standard let appLanguage = userDefaults.object(forKey: TranslationLanguage.appLanguage.rawValue) if appLanguage == nil { userDefaults.setValue(TranslationLanguage.english.rawValue, forKey: TranslationLanguage.appLanguage.rawValue) } let didViewTour = userDefaults.bool(forKey: "didViewTour") if didViewTour == false{ self.window = UIWindow(frame: UIScreen.main.bounds) let rootVC = TourPageViewController() self.window?.rootViewController = rootVC self.window?.makeKeyAndVisible() } return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. 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 active 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
07af73efb53d82346b2d27284fea48d1
48.385965
285
0.724689
5.530452
false
false
false
false
mgadda/zig
Sources/MessagePackEncoder/MessagePackKey.swift
1
601
// // MessagePackKey.swift // MessagePackEncoder // // Created by Matt Gadda on 9/27/17. // import Foundation internal struct MessagePackKey : CodingKey { public var stringValue: String public var intValue: Int? public init?(stringValue: String) { self.stringValue = stringValue self.intValue = nil } public init?(intValue: Int) { self.stringValue = "\(intValue)" self.intValue = intValue } internal init(index: Int) { self.stringValue = "index=\(index)" self.intValue = index } internal static let superKey = MessagePackKey(stringValue: "super")! }
mit
2936f7cf1d82d7928b0b24a79c7916ab
19.033333
70
0.682196
4.006667
false
false
false
false
hanangellove/Tuan
Tuan/Deal/HMDealDetailViewController.swift
2
7650
// // HMDealDetailViewController.swift // Tuan // // Created by nero on 15/5/26. // Copyright (c) 2015年 nero. All rights reserved. // 团购详情页 import UIKit class HMDealDetailViewController: UIViewController { @IBOutlet weak var webView: UIWebView! var loadingView:UIActivityIndicatorView? @IBOutlet weak var collectButton: UIButton! @IBOutlet weak var refundableAnyTimeButton: UIButton! @IBOutlet weak var refundableExpiresButton: UIButton! @IBOutlet weak var leftTimeButton: UIButton! @IBOutlet weak var purchaseCountButton: UIButton! var deal:HMDeal? // // label @IBOutlet weak var titleLabel: UILabel! @IBOutlet weak var descLabel: UILabel! @IBOutlet weak var currentPriceLabel: UILabel! @IBOutlet weak var listPriceLabel: HMCenterLineLabel! // // 按钮 @IBAction func share() { let alert = UIAlertController(title: "💗", message: "我没有搞分享 主要友盟更新太频繁了 分享经常不能用", preferredStyle: UIAlertControllerStyle.Alert) alert.addAction(UIAlertAction(title: "寒哥, 我知道错了 ", style: UIAlertActionStyle.Default, handler: { (action) -> Void in })) presentViewController(alert, animated: true, completion: nil) } @IBAction func collec() { if (self.collectButton.selected) { HMDealLocalTool.sharedDealLocalTool().unsaveCollectDeal(deal!) MBProgressHUD.showSuccess("取消收藏成功!") self.collectButton.selected = false } else { HMDealLocalTool.sharedDealLocalTool().saveCollectDeal(deal!) MBProgressHUD.showSuccess("收藏成功!") self.collectButton.selected = true } } @IBAction func buy() { } @IBAction func back() { dismissViewControllerAnimated(true, completion: nil) } override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = UIColor.whiteColor() // 保存最近浏览记录 HMDealLocalTool.sharedDealLocalTool().saveHistoryDeal(deal) // 判断是否收藏 let collectDeals = HMDealLocalTool.sharedDealLocalTool().collectDeals collectButton.selected = collectDeals.containsObject(deal!) setupLeft() updateLeftContent() setupRight() } func setupLeft(){ // 更新左边内容 updateLeftContent() // 加载更详细的团购数据 let param = HMGetSingleDealParam() param.deal_id = deal?.deal_id HMDealTool.getSingleDeal(param, success: { (result) -> Void in if let deals = result.deals where result.deals.count >= 0 { self.deal = deals.first as? HMDeal // 更新左边的内容 self.updateLeftContent() }else{ MBProgressHUD.showError("没有找到指定的团购信息") } }) { (error) -> Void in MBProgressHUD.showError("加载团购数据失败") } } /** 加载右侧webview */ func setupRight(){ self.view.backgroundColor = UIColor(red: 230/255.0, green: 230/255.0, blue: 230/255.0, alpha: 230/255.0) self.webView.backgroundColor = UIColor(red: 230/255.0, green: 230/255.0, blue: 230/255.0, alpha: 230/255.0) // // 加载网页 webView.loadRequest(NSURLRequest(URL: NSURL(string: deal!.deal_h5_url)!)) webView.scrollView.hidden = true print(deal!.deal_h5_url, terminator: "") // // 圈圈 loadingView = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.WhiteLarge) webView.addSubview(loadingView!) loadingView?.startAnimating() loadingView?.autoCenterInSuperview() } /** 更新左侧详情 */ func updateLeftContent(){ // 简单信息 self.titleLabel.text = self.deal?.title; self.descLabel.text = self.deal?.desc; self.currentPriceLabel.text = "¥\(self.deal!.current_price)" self.listPriceLabel.text = "门店价¥\( self.deal!.list_price)" self.purchaseCountButton.title = "已售出\(self.deal!.purchase_count)" if self.deal?.restrictions == nil { self.refundableAnyTimeButton.selected = false self.refundableExpiresButton.selected = false }else{ self.refundableAnyTimeButton.selected = self.deal?.restrictions.is_refundable ?? false self.refundableExpiresButton.selected = self.deal?.restrictions.is_refundable ?? false } /* // 剩余时间处理 // 当前时间 2014-08-27 09:06 NSDate *now = [NSDate date]; // 过期时间 2014-08-28 00:00 NSDateFormatter *fmt = [[NSDateFormatter alloc] init]; fmt.dateFormat = @"yyyy-MM-dd"; NSDate *deadTime = [[fmt dateFromString:self.deal.purchase_deadline] dateByAddingTimeInterval:24 * 3600]; // 比较2个时间的差距 NSCalendar *calendar = [NSCalendar currentCalendar]; NSCalendarUnit unit = NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute; NSDateComponents *cmps = [calendar components:unit fromDate:now toDate:deadTime options:0]; if (cmps.day > 365) { self.leftTimeButton.title = @"一年内不过期"; } else { self.leftTimeButton.title = [NSString stringWithFormat:@"%d天%d小时%d分", cmps.day, cmps.hour, cmps.minute]; } */ } } extension HMDealDetailViewController:UIWebViewDelegate { func webViewDidFinishLoad(webView: UIWebView) { // // 拼接详情的URL路径 // NSString *ID = self.deal.deal_id; var id = deal!.deal_id as NSString id = id.substringFromIndex(id.rangeOfString("-").location+1) var urlStr = "http://lite.m.dianping.com/group/deal/moreinfo/\(id)" urlStr = "http://m.dianping.com/tuan/deal/\(id)" // let webViewURL = webView.request?.URL?.absoluteString if webViewURL == urlStr { var js = "" js = ("\(js) var bodyHTML = ';'") // 拼接link的内容 js = ("\(js) var link = document.body.getElementsByTagName('link')[0];") js = ("\(js) bodyHTML += link.outerHTML;") // / 拼接多个div的内容 js = ("\(js) var divs = document.getElementsByClassName('detail-info');") js = ("\(js) for (var i = 0; i<=divs.length; i++) {") js = ("\(js) var div = divs[i];") js = ("\(js) if (div) { bodyHTML += div.outerHTML; }") js = ("\(js) }") // // 设置body的内容 js = js.stringByAppendingString("document.body.innerHTML = bodyHTML;") // // 执行JS代码 webView.stringByEvaluatingJavaScriptFromString(js) // // 显示网页内容 webView.scrollView.hidden = false // // 移除圈圈 loadingView?.removeFromSuperview() }else{ // } else { // 加载初始网页完毕 let js = "window.location.href = '\(urlStr)';" // // 执行JS代码 webView.stringByEvaluatingJavaScriptFromString(js) } } // override func supportedInterfaceOrientations() -> UIInterfaceOrientationMask { // } override func supportedInterfaceOrientations() -> UIInterfaceOrientationMask { return UIInterfaceOrientationMask.All } }
mit
a6e35468069e8ea33fa9402f97dd1c64
35.075
134
0.599861
4.266706
false
false
false
false
apple/swift-tools-support-core
Sources/TSCUtility/Platform.swift
1
4342
/* 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 TSCBasic import Foundation /// Recognized Platform types. public enum Platform: Equatable { case android case darwin case linux(LinuxFlavor) case windows /// Recognized flavors of linux. public enum LinuxFlavor: Equatable { case debian case fedora } /// Lazily checked current platform. public static var currentPlatform = Platform.findCurrentPlatform(localFileSystem) /// Returns the cache directories used in Darwin. private static var darwinCacheDirectoriesLock = NSLock() private static var _darwinCacheDirectories: [AbsolutePath]? = .none /// Attempt to match `uname` with recognized platforms. internal static func findCurrentPlatform(_ fileSystem: FileSystem) -> Platform? { #if os(Windows) return .windows #else guard let uname = try? Process.checkNonZeroExit(args: "uname").spm_chomp().lowercased() else { return nil } switch uname { case "darwin": return .darwin case "linux": return Platform.findCurrentPlatformLinux(fileSystem) default: return nil } #endif } internal static func findCurrentPlatformLinux(_ fileSystem: FileSystem) -> Platform? { do { if try fileSystem.isFile(AbsolutePath(validating: "/etc/debian_version")) { return .linux(.debian) } if try fileSystem.isFile(AbsolutePath(validating: "/system/bin/toolbox")) || fileSystem.isFile(AbsolutePath(validating: "/system/bin/toybox")) { return .android } if try fileSystem.isFile(AbsolutePath(validating: "/etc/redhat-release")) || fileSystem.isFile(AbsolutePath(validating: "/etc/centos-release")) || fileSystem.isFile(AbsolutePath(validating: "/etc/fedora-release")) || Platform.isAmazonLinux2(fileSystem) { return .linux(.fedora) } } catch {} return nil } private static func isAmazonLinux2(_ fileSystem: FileSystem) -> Bool { do { let release = try fileSystem.readFileContents(AbsolutePath(validating: "/etc/system-release")).cString return release.hasPrefix("Amazon Linux release 2") } catch { return false } } /// Returns the cache directories used in Darwin. public static func darwinCacheDirectories() throws -> [AbsolutePath] { try Self.darwinCacheDirectoriesLock.withLock { if let darwinCacheDirectories = Self._darwinCacheDirectories { return darwinCacheDirectories } var directories = [AbsolutePath]() // Compute the directories. try directories.append(AbsolutePath(validating: "/private/var/tmp")) (try? TSCBasic.determineTempDirectory()).map{ directories.append($0) } #if canImport(Darwin) getConfstr(_CS_DARWIN_USER_TEMP_DIR).map({ directories.append($0) }) getConfstr(_CS_DARWIN_USER_CACHE_DIR).map({ directories.append($0) }) #endif Self._darwinCacheDirectories = directories return directories } } #if canImport(Darwin) /// Returns the value of given path variable using `getconf` utility. /// /// - Note: This method returns `nil` if the value is an invalid path. private static func getConfstr(_ name: Int32) -> AbsolutePath? { let len = confstr(name, nil, 0) let tmp = UnsafeMutableBufferPointer(start: UnsafeMutablePointer<Int8>.allocate(capacity: len), count:len) defer { tmp.deallocate() } guard confstr(name, tmp.baseAddress, len) == len else { return nil } let value = String(cString: tmp.baseAddress!) guard value.hasSuffix(AbsolutePath.root.pathString) else { return nil } return try? resolveSymlinks(AbsolutePath(validating: value)) } #endif }
apache-2.0
5699103acc8aa2aa137e0f29c38d212b
37.087719
115
0.637494
4.851397
false
false
false
false
andrebocchini/SwiftChatty
SwiftChatty/Requests/Threads/GetThreadRequest.swift
1
798
// // GetThreadRequest.swift // SwiftChatty // // Created by Andre Bocchini on 1/16/16. // Copyright © 2016 Andre Bocchini. All rights reserved.// /// -SeeAlso: http://winchatty.com/v2/readme#_Toc421451665 public struct GetThreadRequest: Request { public let endpoint: ApiEndpoint = .GetThread public var customParameters: [String : Any] = [:] public init(withThreadIds ids: [Int]) { if ids.count > 0 { var concatenatedIds: String = "" for i in 0...(ids.count - 1) { if i == 0 { concatenatedIds += String(ids[i]) } else { concatenatedIds += ("," + String(ids[i])) } } self.customParameters["id"] = concatenatedIds } } }
mit
1491528c322eb6459f148d922eb538d1
27.464286
61
0.537014
4.151042
false
false
false
false
andrebocchini/SwiftChatty
SwiftChatty/Requests/Posts/PostCommentRequest.swift
1
683
// // PostCommentRequest.swift // SwiftChatty // // Created by Andre Bocchini on 2/14/16. // Copyright © 2016 Andre Bocchini. All rights reserved.// import Alamofire /// -SeeAlso: http://winchatty.com/v2/readme#_Toc421451675 public struct PostCommentRequest: Request { public let endpoint: ApiEndpoint = .PostComment public var customParameters: [String : Any] = [:] public let httpMethod: HTTPMethod = .post public let account: Account public init(withAccount account: Account, parentId: Int, text: String) { self.account = account self.customParameters["parentId"] = parentId self.customParameters["text"] = text } }
mit
52ede56a12255a4b5464e638535d73cd
27.416667
76
0.686217
4.236025
false
false
false
false
chenjiang3/RDVTabBarControllerSwift
Example/RDVTabBarControllerSwift/AppDelegate.swift
1
4518
// // AppDelegate.swift // RDVTabBarControllerSwift // // Created by chenjiang on 01/23/2017. // Copyright (c) 2017 chenjiang. All rights reserved. // import UIKit import RDVTabBarControllerSwift @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? var viewController: UIViewController? func setupTabViewController() { let firstViewController = RDVFirstViewController(nibName: nil, bundle: nil) let firstNavigationController = UINavigationController(rootViewController: firstViewController) let secondViewController = RDVSecondViewController(nibName: nil, bundle: nil) let secondNavigationController = UINavigationController(rootViewController: secondViewController) let thirdViewController = RDVThirdViewController(nibName: nil, bundle: nil) let thirdNavigationController = UINavigationController(rootViewController: thirdViewController) let tabBarController = RDVTabBarController() tabBarController.viewControllers = [firstNavigationController, secondNavigationController, thirdNavigationController] self.viewController = tabBarController customizeTabBarForController(tabBarController) let tabBar = tabBarController.tabBar tabBar.translucent = true tabBar.backgroundView.backgroundColor = UIColor(red: 245/255.0, green: 245/255.0, blue: 245/255.0, alpha: 0.9) } func customizeTabBarForController(_ tabBarController: RDVTabBarController) { guard let items = tabBarController.tabBar.items else { return } let finishedImage = UIImage(named: "tabbar_selected_background") let unfinishedImage = UIImage(named: "tabbar_normal_background") let tabBarItemImages = ["first", "second", "third"] var index = 0 for item in items { item.setBackgroundSelectedImage(finishedImage, unselectedImage: unfinishedImage) let selectedimage = UIImage(named: "\(tabBarItemImages[index])_selected") let unselectedimage = UIImage(named: "\(tabBarItemImages[index])_normal") item.setFinishedSelectedImage(selectedimage, unselectedImage: unselectedimage) index += 1 } } func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { window = UIWindow(frame: UIScreen.main.bounds) window?.backgroundColor = UIColor.clear setupTabViewController() window?.rootViewController = self.viewController window?.makeKeyAndVisible() return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
mit
cabf75fa9284ac5dd5c53b5fe27644e8
42.442308
285
0.707393
5.814672
false
false
false
false
citysite102/kapi-kaffeine
kapi-kaffeine/kapi-kaffeine/KPFifthIntroView.swift
1
7375
// // KPFifthIntroView.swift // kapi-kaffeine // // Created by YU CHONKAO on 2017/5/23. // Copyright © 2017年 kapi-kaffeine. All rights reserved. // import UIKit import FacebookLogin import FacebookCore class KPFifthIntroView: KPSharedIntroView { var bottomImageView: UIImageView! var firstPopImageView: UIImageView! var secondPopImageView: UIImageView! var thirdPopImageView: UIImageView! var facebookLoginButton: UIButton! override init(frame: CGRect) { super.init(frame: frame); isUserInteractionEnabled = true bottomImageView = UIImageView(image: R.image.image_onbroading_5()) bottomImageView.contentMode = .scaleAspectFit addSubview(bottomImageView) bottomImageView.addConstraints(fromStringArray: ["V:[$self]", "H:[$self]"]) bottomImageView.addConstraintForCenterAligningToSuperview(in: .horizontal) bottomImageView.addConstraintForCenterAligningToSuperview(in: .vertical, constant: -80) firstPopImageView = UIImageView(image: R.image.image_onbroading_51()) addSubview(firstPopImageView) firstPopImageView.addConstraintForAligning(to: .top, of: bottomImageView, constant: 32) firstPopImageView.addConstraintForAligning(to: .left, of: bottomImageView, constant: 8) secondPopImageView = UIImageView(image: R.image.image_onbroading_52()) addSubview(secondPopImageView) secondPopImageView.addConstraintForAligning(to: .top, of: bottomImageView, constant: 16) secondPopImageView.addConstraintForAligning(to: .right, of: bottomImageView, constant: 0) thirdPopImageView = UIImageView(image: R.image.image_onbroading_53()) addSubview(thirdPopImageView) thirdPopImageView.addConstraintForAligning(to: .bottom, of: bottomImageView, constant: 16) thirdPopImageView.addConstraintForAligning(to: .left, of: bottomImageView, constant: 32) introTitleLabel.text = "最挺你的社群" introDescriptionLabel.textAlignment = .center introDescriptionLabel.setText(text: "全台網友協力貢獻店家資料,找咖啡不再是件麻煩事", lineSpacing: KPFactorConstant.KPSpacing.introSpacing) facebookLoginButton = UIButton() facebookLoginButton.setImage(R.image.facebook_login(), for: .normal) facebookLoginButton.isHidden = KPUserManager.sharedManager.currentUser != nil ? true : false addSubview(facebookLoginButton) facebookLoginButton.addConstraintForCenterAligningToSuperview(in: .horizontal) facebookLoginButton.addConstraints(fromStringArray: ["V:[$self(64)]-32-|", "H:[$self(276)]"]) facebookLoginButton.transform = CGAffineTransform(translationX: 0, y: 120) } func showPopContents() { UIView.animate(withDuration: 0.8, delay: 0.0, usingSpringWithDamping: 0.7, initialSpringVelocity: 1.0, options: .curveEaseOut, animations: { self.facebookLoginButton.transform = .identity }) { (_) in } UIView.animateKeyframes(withDuration: 3.0, delay: 0, options: [.repeat], animations: { UIView.addKeyframe(withRelativeStartTime: 0, relativeDuration: 0.25, animations: { self.firstPopImageView.alpha = 0.0 }) UIView.addKeyframe(withRelativeStartTime: 0.5, relativeDuration: 0.25, animations: { self.firstPopImageView.alpha = 1.0 }) }) { (_) in } UIView.animateKeyframes(withDuration: 3.0, delay: 1.0, options: [.repeat], animations: { UIView.addKeyframe(withRelativeStartTime: 0, relativeDuration: 0.25, animations: { self.secondPopImageView.alpha = 0.0 }) UIView.addKeyframe(withRelativeStartTime: 0.5, relativeDuration: 0.25, animations: { self.secondPopImageView.alpha = 1.0 }) }) { (_) in } UIView.animateKeyframes(withDuration: 3.0, delay: 2.0, options: [.repeat], animations: { UIView.addKeyframe(withRelativeStartTime: 0, relativeDuration: 0.25, animations: { self.thirdPopImageView.alpha = 0.0 }) UIView.addKeyframe(withRelativeStartTime: 0.5, relativeDuration: 0.25, animations: { self.thirdPopImageView.alpha = 1.0 }) }) { (_) in } } func updateLayoutWithProgress(_ progress: CGFloat) { firstPopImageView.transform = CGAffineTransform(translationX: progress == 0 ? 0 : 140-140*progress, y: 0) secondPopImageView.transform = CGAffineTransform(translationX: progress == 0 ? 0 : 200-200*progress, y: 0) thirdPopImageView.transform = CGAffineTransform(translationX: progress == 0 ? 0 : 260-260*progress, y: 0) // facebookLoginButton.transform = CGAffineTransform(translationX: 0, // y: progress == 0 ? 0 : 80-80*progress) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
mit
ee9019ee16e14debd7ff8e20edcb2269
45.585987
108
0.461034
6.343452
false
false
false
false
YQqiang/Nunchakus
Nunchakus/Nunchakus/Selfie/ViewController/WebViewController.swift
1
2131
// // WebViewController.swift // Nunchakus // // Created by sungrow on 2017/3/23. // Copyright © 2017年 sungrow. All rights reserved. // import UIKit import Toaster class WebViewController: BaseViewController, UIWebViewDelegate { var getRealUrl: ((_ url: String) -> ())? fileprivate lazy var webView: UIWebView = UIWebView() var v_id: String? { didSet { print("v_id = \(v_id)") if let v_id = v_id { webView.stringByEvaluatingJavaScript(from: "requestURL(window, '\(v_id)')") } else { Hud.showError(status: NSLocalizedString("视屏id错误", comment: "")) } } } override func viewDidLoad() { super.viewDidLoad() navigationItem.title = NSLocalizedString("视屏播放", comment: "") emptyDataView.isHidden = true webView.delegate = self webView.frame = CGRect.zero view.addSubview(webView) let baseURL = Bundle.main.bundlePath let requestJSPath = Bundle.main.path(forResource: "test", ofType: "html")! guard let requestJS = try? String.init(contentsOfFile: requestJSPath) else { print("failure!") return } webView.loadHTMLString(requestJS, baseURL: URL(fileURLWithPath: baseURL)) } deinit { print("\(#function)----deinit") } func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool { print("url = \(request.url?.absoluteString)") let urlStr = request.url?.absoluteString if let urlStr = urlStr, urlStr.hasPrefix("yuqiang://encodeidfailed") { Hud.showError(status: NSLocalizedString("播放出错", comment: "")) return false } if let urlStr = urlStr, urlStr.hasPrefix("http://pl.youku.com") { if let getRealUrl = getRealUrl { getRealUrl(urlStr) } return false } return true } func webViewDidFinishLoad(_ webView: UIWebView) { } }
mit
0218c98b068c2d809835f3bce1e9802c
30.878788
130
0.589829
4.675556
false
false
false
false
RajanFernandez/MotoParks
MotoParks/WatchConnection/WatchSessionManager.swift
1
2245
// // WatchSessionManager.swift // MotoParks // // Created by Rajan Fernandez on 31/03/17. // Copyright © 2017 Rajan Fernandez. All rights reserved. // import Foundation import MapKit import WatchConnectivity class WatchSessionManager: NSObject { static let shared = WatchSessionManager() func configureAndActivateSession() { guard WCSession.isSupported() else { return } let session = WCSession.default session.delegate = self; session.activate() } func updateApplicationContext(_ context: [String : Any]) throws { let session = WCSession.default // If a phone is not paired to a watch, or the watch app is not installed, we can consider the session invalid and not both sending any data to the watch. guard session.isPaired && session.isWatchAppInstalled else { return } try session.updateApplicationContext(context) } } extension WatchSessionManager: WCSessionDelegate { func session(_ session: WCSession, activationDidCompleteWith activationState: WCSessionActivationState, error: Error?) { // No action required } func sessionDidBecomeInactive(_ session: WCSession) { // No action required } func sessionDidDeactivate(_ session: WCSession) { // No action required } func session(_ session: WCSession, didReceiveMessage message: [String : Any], replyHandler: @escaping ([String : Any]) -> Void) { guard let applicationContext = ApplicationContext(applicationContext: message) else { // TODO: Send some error here. replyHandler(message) return } // Ensure the data source has loaded the park data. do { try ParkLocationDataSource.shared.loadParkLocationsIfRequiredWithDataSetNamed("parks") } catch { replyHandler(message) return } if let parks = ParkLocationDataSource.shared.parks(closestToUserLocation: applicationContext.userLocation, numberOfParks: 10, maximumDistance: 700) { applicationContext.parks = parks } replyHandler(applicationContext.messagePayload) } }
mit
6ac85ba82babb294b64c60b2513377a9
30.605634
162
0.659982
5.146789
false
false
false
false
jovito-royeca/Decktracker
ios/old/Decktracker/View/Settings/SignupViewController.swift
1
1180
// // SignupViewController.swift // Decktracker // // Created by Jovit Royeca on 4/8/15. // Copyright (c) 2015 Jovito Royeca. All rights reserved. // import UIKit class SignupViewController: PFSignUpViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. self.view.backgroundColor = JJJUtil.colorFromRGB(0x691F01) let image = UIImage(named: "\(NSBundle.mainBundle().bundlePath)/images/AppIcon57x57.png") let imageView = UIImageView(frame: CGRectMake(0, 0, 57, 57)) imageView.image = image self.signUpView!.logo = imageView self.navigationItem.title = "Signup" #if !DEBUG // send the screen to Google Analytics if let tracker = GAI.sharedInstance().defaultTracker { tracker.set(kGAIScreenName, value: "Signup") tracker.send(GAIDictionaryBuilder.createScreenView().build() as [NSObject : AnyObject]) } #endif } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
apache-2.0
6c1dab9c545ba05ea3c84ff50263c683
29.25641
99
0.654237
4.627451
false
false
false
false
msedd/ControlSlider
ControlSlider/ControlVSlider.swift
1
5230
// // DimSlider.swift // ControlSlider.h // // Created by Marko Seifert on 21.12.15. // // Copyright © 2015 Marko Seifert. // Licensed under the Apache License, Version 2.0 (the "License") import UIKit @IBDesignable open class ControlVSlider: UIControl { @IBInspectable open var activeFillColor: UIColor = UIColor(red: 0.232, green: 0.653, blue: 0.999, alpha: 1.000) @IBInspectable open var textForeground: UIColor = UIColor(red: 1.000, green: 1.000, blue: 1.000, alpha: 1.000) @IBInspectable open var buttonColor: UIColor = UIColor(red: 1.000, green: 1.000, blue: 1.000, alpha: 0.640) @IBInspectable open var buttonStrokeColor: UIColor = UIColor(red: 1.000, green: 1.000, blue: 1.000, alpha: 1.000) @IBInspectable open var bgBarColor: UIColor = UIColor(red: 0.1647, green: 0.1647, blue: 0.1647, alpha: 1.0) @IBInspectable open var bgColor: UIColor = UIColor(red: 0.1255, green: 0.1255, blue: 0.1255, alpha: 1.0) @IBInspectable open var maxValue:CGFloat = 255 open var defaultValue:Float = 0 open var showLable:Bool = true fileprivate var _value: Float = 0 dynamic open var value: Float { get { return _value } } var size:CGRect { get { let bounds = self.bounds let offset: CGFloat = 50.0 return CGRect(x: bounds.origin.x+offset/2, y: bounds.origin.y, width: bounds.size.width-offset,height: bounds.size.height) } } var viewSize:CGRect { get { let bounds = self.bounds return CGRect(x: bounds.origin.x, y: bounds.origin.y, width: bounds.size.width,height: bounds.size.height) } } var length:CGFloat{ get { return CGFloat(value) * (size.width)/maxValue } } override public init(frame: CGRect) { super.init(frame: frame) registerGesture() } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) registerGesture() } fileprivate func registerGesture() { let doubleTap : UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(resetToDefault)) doubleTap.numberOfTapsRequired = 2 addGestureRecognizer(doubleTap) } @objc func resetToDefault(){ setValueInternal(value: defaultValue) self.setNeedsDisplay() } open func setValue(value: Float) { _value = value } fileprivate func setValueInternal(value: Float) { _value = value sendActions(for: .valueChanged) } override open func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { } override open func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) { if let touch = touches.first { let loc = touch.location(in: self) let v = (loc.x) / size.width * maxValue if(v < 0) { setValueInternal(value: 0) } else if (v>maxValue) { setValueInternal(value: Float(maxValue)) } else { setValueInternal(value: Float(v)) } self.setNeedsDisplay() } } override open func draw(_ rect: CGRect) { let ctx = UIGraphicsGetCurrentContext() ctx!.clear(rect) drawBackground() drawActiveBar() drawButton() } func drawButton(){ let buttonPath = UIBezierPath(roundedRect: CGRect(x: size.origin.x+length-20, y: size.origin.y, width: 40, height: size.height), cornerRadius: 6) buttonColor.setFill() buttonPath.fill() buttonStrokeColor.setStroke() buttonPath.lineWidth = 1 buttonPath.stroke() if showLable { let labelRect = CGRect(x: size.origin.x+length-20, y: size.height-30 , width: 40, height: 30) let labelStyle = NSParagraphStyle.default.mutableCopy() as! NSMutableParagraphStyle labelStyle.alignment = .center let labelFontAttributes = [//NSAttributedString.Key.font: UIFont(name: "Helvetica", size: 18), NSAttributedString.Key.foregroundColor: textForeground, NSAttributedString.Key.paragraphStyle: labelStyle] let intValue:Int = Int(value) NSString(string: "\(intValue)").draw(in: labelRect, withAttributes:labelFontAttributes) } } func drawActiveBar(){ let bgBarPath = UIBezierPath(roundedRect: CGRect(x: size.origin.x, y: size.origin.y+4, width: length, height: size.height-8), cornerRadius: 4) activeFillColor.setFill() bgBarPath.fill() } func drawBackground(){ let bgPath = UIBezierPath(rect: viewSize) bgColor.setFill() bgPath.fill(); let bgBarPath = UIBezierPath(roundedRect: CGRect(x: size.origin.x, y: size.origin.y+4, width: size.width, height: size.height-8), cornerRadius: 4) bgBarColor.setFill() bgBarPath.fill() } }
apache-2.0
3afd52a7b4af2c8e11417b1bac71303f
32.519231
153
0.593039
4.3108
false
false
false
false
vapor/vapor
Sources/Vapor/Response/ResponseCodable.swift
1
3429
/// Can convert `self` to a `Response`. /// /// Types that conform to this protocol can be returned in route closures. public protocol ResponseEncodable { /// Encodes an instance of `Self` to a `Response`. /// /// - parameters: /// - for: The `Request` associated with this `Response`. /// - returns: A `Response`. func encodeResponse(for request: Request) -> EventLoopFuture<Response> } /// Can convert `Request` to a `Self`. /// /// Types that conform to this protocol can decode requests to their type. public protocol RequestDecodable { /// Decodes an instance of `Request` to a `Self`. /// /// - parameters: /// - request: The `Request` to be decoded. /// - returns: An asynchronous `Self`. static func decodeRequest(_ request: Request) -> EventLoopFuture<Self> } extension Request: RequestDecodable { public static func decodeRequest(_ request: Request) -> EventLoopFuture<Request> { return request.eventLoop.makeSucceededFuture(request) } } // MARK: Convenience extension ResponseEncodable { /// Asynchronously encodes `Self` into a `Response`, setting the supplied status and headers. /// /// router.post("users") { req -> EventLoopFuture<Response> in /// return try req.content /// .decode(User.self) /// .save(on: req) /// .encode(status: .created, for: req) /// } /// /// - parameters: /// - status: `HTTPStatus` to set on the `Response`. /// - headers: `HTTPHeaders` to merge into the `Response`'s headers. /// - returns: Newly encoded `Response`. public func encodeResponse(status: HTTPStatus, headers: HTTPHeaders = [:], for request: Request) -> EventLoopFuture<Response> { return self.encodeResponse(for: request).map { response in for (name, value) in headers { response.headers.replaceOrAdd(name: name, value: value) } response.status = status return response } } } // MARK: Default Conformances extension Response: ResponseEncodable { // See `ResponseEncodable`. public func encodeResponse(for request: Request) -> EventLoopFuture<Response> { return request.eventLoop.makeSucceededFuture(self) } } extension StaticString: ResponseEncodable { // See `ResponseEncodable`. public func encodeResponse(for request: Request) -> EventLoopFuture<Response> { let res = Response(headers: staticStringHeaders, body: .init(staticString: self, byteBufferAllocator: request.byteBufferAllocator)) return request.eventLoop.makeSucceededFuture(res) } } extension String: ResponseEncodable { // See `ResponseEncodable`. public func encodeResponse(for request: Request) -> EventLoopFuture<Response> { let res = Response(headers: staticStringHeaders, body: .init(string: self, byteBufferAllocator: request.byteBufferAllocator)) return request.eventLoop.makeSucceededFuture(res) } } extension EventLoopFuture: ResponseEncodable where Value: ResponseEncodable { // See `ResponseEncodable`. public func encodeResponse(for request: Request) -> EventLoopFuture<Response> { return self.flatMap { t in return t.encodeResponse(for: request) } } } internal let staticStringHeaders: HTTPHeaders = ["content-type": "text/plain; charset=utf-8"]
mit
01d8abaf0c8d18028039b44565441858
36.271739
139
0.660834
4.553785
false
false
false
false
digipost/ios
Digipost/UIImage+Barcode.swift
1
1102
// // Copyright (C) Posten Norge AS // // 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. // extension UIImage { convenience init?(barcode: String, barcodeType: String) { let type = barcodeType == "code-128" ? "CICode128BarcodeGenerator" : barcodeType let data = barcode.data(using: .ascii) guard let filter = CIFilter(name:type) else { return nil } filter.setValue(data, forKey: "inputMessage") guard let ciImage = filter.outputImage else { return nil } self.init(ciImage: ciImage) } }
apache-2.0
df2669d8060171e82a20e3fe01824aae
33.4375
88
0.666969
4.304688
false
false
false
false
GraphQLSwift/GraphQL
Sources/GraphQL/SwiftUtilities/SuggestionList.swift
1
2131
/** * Given an invalid input string and a list of valid options, returns a filtered * list of valid options sorted based on their similarity with the input. */ func suggestionList( input: String, options: [String] ) -> [String] { var optionsByDistance: [String: Int] = [:] let oLength = options.count let inputThreshold = input.utf8.count / 2 for i in 0 ..< oLength { let distance = lexicalDistance(input, options[i]) let threshold = max(inputThreshold, options[i].utf8.count / 2, 1) if distance <= threshold { optionsByDistance[options[i]] = distance } } return optionsByDistance.keys.sorted { // Values are guaranteed non-nil since the keys come from the object itself optionsByDistance[$0]! - optionsByDistance[$1]! != 0 } } /** * Computes the lexical distance between strings A and B. * * The "distance" between two strings is given by counting the minimum number * of edits needed to transform string A into string B. An edit can be an * insertion, deletion, or substitution of a single character, or a swap of two * adjacent characters. * * This distance can be useful for detecting typos in input or sorting * */ func lexicalDistance(_ a: String, _ b: String) -> Int { let aLength = a.utf8.count let bLength = b.utf8.count var d = [[Int]](repeating: [Int](repeating: 0, count: bLength + 1), count: aLength + 1) for i in 0 ... aLength { d[i][0] = i } for j in 1 ... bLength { d[0][j] = j } for i in 1 ... aLength { for j in 1 ... bLength { let cost = a.charCode(at: i - 1) == b.charCode(at: j - 1) ? 0 : 1 let stupidCompiler = min(d[i][j - 1] + 1, d[i - 1][j - 1] + cost) d[i][j] = min(d[i - 1][j] + 1, stupidCompiler) if i > 1, j > 1, a.charCode(at: i - 1) == b.charCode(at: j - 2), a.charCode(at: i - 2) == b.charCode(at: j - 1) { d[i][j] = min(d[i][j], d[i - 2][j - 2] + cost) } } } return d[aLength][bLength] }
mit
3689502bb1c720fd42659e3df0c0fd6c
30.338235
91
0.571093
3.442649
false
false
false
false
Alexiuce/Tip-for-day
iFeiBo/iFeiBo/HTTPManager.swift
1
1043
// // HTTPManager.swift // iFeiBo // // Created by alexiuce  on 2017/9/18. // Copyright © 2017年 Alexcai. All rights reserved. // import Cocoa import Alamofire class HTTPManager { class func getWBStatus(_ begingID :Int64 = 0 ,endID : Int64 = 0 , finished : @escaping ([String : Any]?)->()) { // 1. url let statusURL = URL(string: WBStatusURL)! // 2. setup parameter let para = ["access_token": UAToolManager.defaultManager.userAccount!.access_token, "since_id":begingID, "max_id": endID] as [String : Any] // 3. send https request Alamofire.request(statusURL, method: HTTPMethod.get, parameters:para ).responseJSON { (response) in if let error = response.error{ XCPring(error.localizedDescription) } guard let dict = response.value as? [String : Any] else {return} // 3. callback closure finished(dict) } } }
mit
3acfbfe83919ded3dad8d2d799e7f19a
27.861111
115
0.556304
4.106719
false
false
false
false
IntrepidPursuits/swift-wisdom
SwiftWisdom/Core/Async/After/After.swift
1
1365
// // After.swift // // Created by Logan Wright on 10/24/15. // Copyright © 2015 lowriDevs. All rights reserved. // // swiftlint:disable identifier_name import Foundation // MARK: Now public func Main(_ function: @escaping Block) { DispatchQueue.main.async(execute: function) } public func Background(_ function: @escaping Block) { DispatchQueue.global(qos: .background).async(execute: function) } // MARK: Later public func After(_ after: TimeInterval, on queue: DispatchQueue = .main, op: @escaping Block) { let seconds = Int64(after * Double(NSEC_PER_SEC)) let dispatchTime = DispatchTime.now() + Double(seconds) / Double(NSEC_PER_SEC) queue.asyncAfter(deadline: dispatchTime, execute: op) } public func RepeatAtInterval(_ interval: TimeInterval, numberOfTimes: Int, op: @escaping () -> (), on queue: DispatchQueue = .main, completion: @escaping () -> Void = {}) { let numberOfTimesLeft = numberOfTimes - 1 let wrappedCompletion: () -> Void if numberOfTimesLeft > 0 { wrappedCompletion = { RepeatAtInterval(interval, numberOfTimes: numberOfTimesLeft, op: op, completion: completion) } } else { wrappedCompletion = completion } let wrappedOperation: () -> Void = { op() wrappedCompletion() } After(interval, on: queue, op: wrappedOperation) }
mit
cf658e1803da54757af30edfb38326f6
26.836735
172
0.671554
4.035503
false
false
false
false
zoulinzhya/GLTools
GLTools/Classes/ActionSheetTableCell.swift
1
2506
// // ActionSheetTableCell.swift // GLTDemo // // Created by zoulin on 2017/10/27. // Copyright © 2017年 zoulin. All rights reserved. // import UIKit import SnapKit enum ActionSheetBtnType : Int { case actionSheetBtn_unknown = -1 //未知按钮类型 case actionSheetBtn_title = 0 //标题按钮 case actionSheetBtn_content = 1 //内容按钮 case actionSheetBtn_cancel = 2 //取消按钮 } struct ActionSheetButton { var btnType:ActionSheetBtnType var title : String? var titleFont: UIFont? var titleColor: UIColor? var index:Int = -1 var isHaveBtnSelectStyle:Bool = true init(with title:String, buttonType:ActionSheetBtnType = .actionSheetBtn_content, titleFont:UIFont = UIFont.boldSystemFont(ofSize: 17), titleColor:UIColor = UIColor.darkGray) { self.btnType = buttonType self.title = title self.titleFont = titleFont self.titleColor = titleColor } } class ActionSheetTableCell: UITableViewCell { static let identifier = "ActionSheetTableCeller" internal var contentlabel = UILabel() override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) self.configContentLabel() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } fileprivate func configContentLabel() { self.contentView.backgroundColor = UIColor.white self.contentView.addSubview(contentlabel) contentlabel.translatesAutoresizingMaskIntoConstraints = false self.contentView.backgroundColor = UIColor.clear contentlabel.snp.makeConstraints { (make) in make.center.equalToSuperview() } } func updateActionSheetButton(button:ActionSheetButton) { contentlabel.font = button.titleFont contentlabel.textColor = button.titleColor contentlabel.text = button.title self.selectionStyle = button.btnType == .actionSheetBtn_cancel || button.isHaveBtnSelectStyle == false ? .none : .default } 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 } }
mit
d8401e4737b9773b9621ba01b051f702
28.369048
129
0.663559
4.744231
false
false
false
false
levantAJ/ResearchKit
TestVoiceActions/PurchaseProducts.swift
1
985
// // PurchaseProducts.swift // TestVoiceActions // // Created by Le Tai on 8/25/16. // Copyright © 2016 Snowball. All rights reserved. // import UIKit struct PurchaseProducts { static let Prefix = "com.levantAJ.Testing." static let ChangeLogo = Prefix + "change_logo" static let Export10Videos = Prefix + "export_ten_videos" static let ExportVideoWithTransitions = "export_video_with_transitions" static let AddEmoticons = Prefix + "AddEmoticons" static let AddAudioForExportingVideos = Prefix + "AddAudioForExportingVideos" static let AddFiltersForYourVideos = Prefix + "AddFiltersForYourVideos" static let BuyMeIfYouCan = Prefix + "BuyMeIfYouCan" static let productIdentifiers: Set<ProductIdentifier> = [ExportVideoWithTransitions, Export10Videos, ChangeLogo, AddEmoticons, AddAudioForExportingVideos, AddFiltersForYourVideos, BuyMeIfYouCan] static let store = PurchaseStore(productIds: PurchaseProducts.productIdentifiers) }
mit
c2b4e7c196522c0f768dbbb22a4113e3
40.041667
198
0.764228
4.066116
false
true
false
false
KevinYangGit/DYTV
DYZB/DYZB/Classes/Main/View/PageTitleView.swift
1
6449
// // PageTitleView.swift // DYZB // // Created by 杨琦 on 2016/10/13. // Copyright © 2016年 杨琦. All rights reserved. // import UIKit //定义协议 protocol PageTitleViewDelegate : class { func pageTitleView(titleView : PageTitleView, selectedIndex index : Int) } //定义常量 private let KScrollLineH : CGFloat = 2 private let KNormalColor : (CGFloat, CGFloat, CGFloat) = (85, 85, 85) private let KSelectColor : (CGFloat, CGFloat, CGFloat) = (255, 128, 0) private let KTitleMargin : CGFloat = 0 //定义PageTitleView类 class PageTitleView: UIView { //定义属性 fileprivate var currentIndex : Int = 0 fileprivate var titles : [String] fileprivate var isScrollEnable : Bool weak var delegate : PageTitleViewDelegate? //懒加载属性 fileprivate lazy var titleLabels : [UILabel] = [UILabel]() fileprivate lazy var scrollView : UIScrollView = { let scrollView = UIScrollView() scrollView.showsVerticalScrollIndicator = false scrollView.scrollsToTop = false scrollView.bounces = false return scrollView }() fileprivate lazy var scrollLine : UIView = { let scrollLine = UIView() scrollLine.backgroundColor = UIColor.orange return scrollLine }() //自定义构造函数 init(frame: CGRect, isScrollEnable : Bool, titles : [String]) { self.isScrollEnable = isScrollEnable self.titles = titles super.init(frame: frame) setupUI() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } // 设置UI界面 extension PageTitleView { fileprivate func setupUI() { //添加UIScrollView addSubview(scrollView) scrollView.frame = bounds //添加title对应的Labels setupTitleLabels() //设置底线和滚动滑块 setupBottomLineAndScrollLine() } fileprivate func setupTitleLabels() { //确定label的一些frame值 let labelH : CGFloat = frame.height - KScrollLineH let labelY : CGFloat = 0 for (index, title) in titles.enumerated() { //创建UILabel let label = UILabel() //设置Label的属性 label.text = title label.tag = index label.font = UIFont.systemFont(ofSize: 16.0) label.textColor = UIColor(r: KNormalColor.0, g: KNormalColor.1, b: KNormalColor.0) label.textAlignment = .center //设置Label的frame var labelW : CGFloat = 0 var labelX : CGFloat = 0 if !isScrollEnable { labelW = frame.width / CGFloat(titles.count) labelX = labelW * CGFloat(index) } else { let size = (title as NSString).boundingRect(with: CGSize(width: CGFloat(MAXFLOAT), height: 0), options: .usesLineFragmentOrigin, attributes: [NSFontAttributeName: label.font], context: nil) labelW = size.width if index != 0 { labelX = titleLabels[index - 1].frame.maxX + KTitleMargin // _Swift_3.0_ } } label.frame = CGRect(x: labelX, y: labelY, width: labelW, height: labelH) //将Label添加到scrollView中 scrollView.addSubview(label) titleLabels.append(label) //给Label添加手势 label.isUserInteractionEnabled = true let tapGes = UITapGestureRecognizer(target: self, action:#selector(titleLabelClick(tapGes:))) label.addGestureRecognizer(tapGes) } } //添加底线 fileprivate func setupBottomLineAndScrollLine() { let bottomLine = UIView() bottomLine.backgroundColor = UIColor.lightGray let lineH : CGFloat = 0.5 bottomLine.frame = CGRect(x: 0, y: frame.height - lineH, width: frame.width, height: lineH) addSubview(bottomLine) guard let firstLabel = titleLabels.first else { return } firstLabel.textColor = UIColor(r: KSelectColor.0, g: KSelectColor.1, b: KSelectColor.2) scrollView.addSubview(scrollLine) scrollLine.frame = CGRect(x: firstLabel.frame.origin.x, y: frame.height - KScrollLineH, width: firstLabel.frame.width, height: KScrollLineH) } } // 监听Label的点击 extension PageTitleView { @objc fileprivate func titleLabelClick(tapGes : UITapGestureRecognizer) { guard let currentLabel = tapGes.view as? UILabel else { return } if currentLabel.tag == currentIndex { return } let oldLabel = titleLabels[currentIndex] currentLabel.textColor = UIColor(r: KSelectColor.0, g: KSelectColor.1, b:KSelectColor.2) oldLabel.textColor = UIColor(r: KNormalColor.0, g: KNormalColor.1, b: KNormalColor.2) currentIndex = currentLabel.tag let scrollLineX = CGFloat(currentIndex) * scrollLine.frame.width UIView.animate(withDuration: 0.15) { self.scrollLine.frame.origin.x = scrollLineX } //通知代理 delegate?.pageTitleView(titleView: self, selectedIndex: currentIndex) } } //对外暴露的方法 extension PageTitleView { func setTitleWithProgress(progress : CGFloat, sourceIndex : Int, targetIndex : Int) { let sourceLabel = titleLabels[sourceIndex] let targetLabel = titleLabels[targetIndex] let moveTotalX = targetLabel.frame.origin.x - sourceLabel.frame.origin.x let moveX = moveTotalX * progress scrollLine.frame.origin.x = sourceLabel.frame.origin.x + moveX //颜色渐变,取出变化的范围 let colorDelta = (KSelectColor.0 - KNormalColor.0, KSelectColor.1 - KNormalColor.1, KSelectColor.2 - KNormalColor.2) sourceLabel.textColor = UIColor(r: KSelectColor.0 - colorDelta.0 * progress, g: KSelectColor.1 - colorDelta.1 * progress, b: KSelectColor.2 - colorDelta.2 * progress) targetLabel.textColor = UIColor(r: KNormalColor.0 + colorDelta.0 * progress, g: KNormalColor.1 + colorDelta.1 * progress, b: KNormalColor.2 + colorDelta.2 * progress) currentIndex = targetIndex } }
mit
1713e6032585975df12bac1f00d44769
32.483871
205
0.617855
4.820433
false
false
false
false