repo_name
stringlengths
6
91
path
stringlengths
6
999
copies
stringclasses
283 values
size
stringlengths
1
7
content
stringlengths
3
1.05M
license
stringclasses
15 values
mathewsheets/SwiftLearningExercises
Exercise_5.playground/Pages/Exercises.xcplaygroundpage/Contents.swift
1
541
/*: [Next](@next) * callout(Exercise): Create a playground with pages with each playground page consisting of the previous four exercises. Refactor each exercise leveraging collection types and functions. **Constraints:** Create a swift file containing your functions for each exercise in the **Sources** directory. Make sure each function has the keyword `public` in front of the keyword `func`. - [Exercise 1](Exercise%201) - [Exercise 2](Exercise%202) - [Exercise 3](Exercise%203) - [Exercise 4](Exercise%204) [Next](@next) */
mit
someoneAnyone/Nightscouter
NightscouterToday/SiteNSNowTableViewCell.swift
1
3091
// // SiteTableViewswift // Nightscouter // // Created by Peter Ina on 6/16/15. // Copyright © 2015 Peter Ina. All rights reserved. // import UIKit import NightscouterKit class SiteNSNowTableViewCell: UITableViewCell { @IBOutlet weak var siteLastReadingHeader: UILabel! @IBOutlet weak var siteLastReadingLabel: UILabel! @IBOutlet weak var siteBatteryHeader: UILabel! @IBOutlet weak var siteBatteryLabel: UILabel! @IBOutlet weak var siteRawHeader: UILabel! @IBOutlet weak var siteRawLabel: UILabel! @IBOutlet weak var siteNameLabel: UILabel! @IBOutlet weak var siteColorBlockView: UIView! @IBOutlet weak var siteSgvLabel: UILabel! @IBOutlet weak var siteDirectionLabel: UILabel! override func awakeFromNib() { super.awakeFromNib() // Initialization code self.backgroundColor = UIColor.clear } func configure(withDataSource dataSource: TableViewRowWithCompassDataSource, delegate: TableViewRowWithCompassDelegate?) { siteLastReadingHeader.text = LocalizedString.lastReadingLabel.localized siteLastReadingLabel.text = dataSource.lastReadingDate.timeAgoSinceNow siteLastReadingLabel.textColor = delegate?.lastReadingColor siteBatteryHeader.text = LocalizedString.batteryLabel.localized siteBatteryHeader.isHidden = dataSource.batteryHidden siteBatteryLabel.isHidden = dataSource.batteryHidden siteBatteryLabel.text = dataSource.batteryLabel siteBatteryLabel.textColor = delegate?.batteryColor siteRawHeader.text = LocalizedString.rawLabel.localized siteRawLabel?.isHidden = dataSource.rawHidden siteRawHeader?.isHidden = dataSource.rawHidden siteRawLabel.text = dataSource.rawFormatedLabel siteRawLabel.textColor = delegate?.rawColor siteNameLabel.text = dataSource.nameLabel siteColorBlockView.backgroundColor = delegate?.sgvColor siteSgvLabel.text = dataSource.sgvLabel + " " + dataSource.direction.emojiForDirection siteSgvLabel.textColor = delegate?.sgvColor siteDirectionLabel.text = dataSource.deltaLabel siteDirectionLabel.textColor = delegate?.deltaColor } override func prepareForReuse() { super.prepareForReuse() siteNameLabel.text = nil siteBatteryLabel.text = nil siteRawLabel.text = nil siteLastReadingLabel.text = nil siteColorBlockView.backgroundColor = DesiredColorState.neutral.colorValue siteSgvLabel.text = nil siteSgvLabel.textColor = Theme.AppColor.labelTextColor siteDirectionLabel.text = nil siteDirectionLabel.textColor = Theme.AppColor.labelTextColor siteLastReadingLabel.text = LocalizedString.tableViewCellLoading.localized siteLastReadingLabel.textColor = Theme.AppColor.labelTextColor siteRawHeader.isHidden = false siteRawLabel.isHidden = false siteRawLabel.textColor = Theme.AppColor.labelTextColor } }
mit
levibostian/SoundCloudHLSStreamer
SoundCloudHLSStreamer/AppDelegate.swift
1
2159
// // AppDelegate.swift // SoundCloudHLSStreamer // // Created by Levi Bostian on 11/19/15. // Copyright © 2015 Levi Bostian. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. 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
silence0201/Swift-Study
AdvancedSwift/错误处理/Errors and Optionals.playgroundpage/Contents.swift
1
2966
/*: ## Errors and Optionals Errors and optionals are both very common ways for functions to signal that something went wrong. Earlier in this chapter, we gave you some advice on how to decide which pattern you should use for your own functions. You'll end up working a lot with both errors and optionals, and passing results to other APIs will often make it necessary to convert back and forth between throwing functions and optional values. The `try?` keyword allows us to ignore the error of a `throws` function and convert the return value into an optional that tells us if the function succeeded or not: */ //#-hidden-code enum ParseError: Error { case wrongEncoding case warning(line: Int, message: String) } //#-end-hidden-code //#-hidden-code func parse(text: String) throws -> [String] { switch text { case "encoding": throw ParseError.wrongEncoding case "warning": throw ParseError.warning(line: 1, message: "Expected file header") default: return [ "This is a dummy return value. Pass \"encoding\" or \"warning\"" + "as the argument to have this function throw an error."] } } //#-end-hidden-code //#-hidden-code let input = "{ \"message\": \"We come in peace\" }" //#-end-hidden-code //#-editable-code if let result = try? parse(text: input) { print(result) } //#-end-editable-code /*: Using the `try?` keyword means we receive less information than before: we only know if the function returned a successful value or if it returned some error — any specific information about that error gets thrown away. To go the other way, from an optional to a function that throws, we have to provide the error value that gets used in case the optional is `nil`. Here's an extension on `Optional` that, given an error, does this: */ //#-editable-code extension Optional { /// Unwraps `self` if it is non-`nil`. /// Throws the given error if `self` is `nil`. func or(error: Error) throws -> Wrapped { switch self { case let x?: return x case nil: throw error } } } //#-end-editable-code //#-hidden-code enum ReadIntError: Error { case couldNotRead } //#-end-hidden-code //#-editable-code do { let int = try Int("42").or(error: ReadIntError.couldNotRead) } catch { print(error) } //#-end-editable-code /*: This can be useful in conjunction with multiple `try` statements, or when you're working inside a function that's already marked as `throws`. The existence of the `try?` keyword may appear contradictory to Swift's philosophy that ignoring errors shouldn't be allowed. However, you still have to explicitly write `try?` so that the compiler forces you to acknowledge your actions. In cases where you're not interested in the error message, this can be very helpful. It's also possible to write equivalent functions for converting between `Result` and `throws`, or between `throws` and `Result`, or between optionals and `Result`. */
mit
eurofurence/ef-app_ios
Eurofurence/SwiftUI/Modules/Dealers/DealerCategoriesView.swift
1
1056
import EurofurenceKit import SwiftUI struct DealerCategoriesView: View { @FetchRequest(fetchRequest: DealerCategory.alphabeticallySortedFetchRequest()) private var categories: FetchedResults<DealerCategory> @Binding var selectedCategory: DealerCategory? var body: some View { ForEach(categories) { category in NavigationLink(tag: category, selection: $selectedCategory) { DealersCollectionView(category: category) } label: { CanonicalDealerCategoryLabel( category: category.canonicalCategory, unknownCategoryText: Text(verbatim: category.name) ) } } } } struct DealerCategoriesView_Previews: PreviewProvider { static var previews: some View { EurofurenceModel.preview { _ in NavigationView { List { DealerCategoriesView(selectedCategory: .constant(nil)) } } } } }
mit
austinzheng/swift-compiler-crashes
crashes-duplicates/17298-no-stacktrace.swift
11
221
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing if true { ( [ { class A { protocol a { class case ,
mit
austinzheng/swift-compiler-crashes
crashes-duplicates/10921-swift-sourcemanager-getmessage.swift
11
240
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing { case let { func b( ) { for in a { class A { let a { ( { class case ,
mit
austinzheng/swift-compiler-crashes
crashes-duplicates/26145-swift-lexer-getlocforendoftoken.swift
7
218
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing if{struct B<T where h:a{class A{let h={}func a{a
mit
eurofurence/ef-app_ios
Packages/EurofurenceKit/Sources/EurofurenceKit/SwiftUI/Modifiers/Transient Overlay/EnvironmentValues+TransientOverlayNamespace.swift
1
484
import SwiftUI extension EnvironmentValues { var transientOverlayNamespace: Namespace.ID? { get { self[ModalImageNamespaceEnvironmentKey.self] } set { self[ModalImageNamespaceEnvironmentKey.self] = newValue } } private struct ModalImageNamespaceEnvironmentKey: EnvironmentKey { typealias Value = Namespace.ID? static var defaultValue: Namespace.ID? } }
mit
austinzheng/swift-compiler-crashes
crashes-duplicates/27745-swift-modulefile-getdecl.swift
4
210
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing {struct A{struct B<T where H:T{let:T.g={
mit
austinzheng/swift-compiler-crashes
crashes-duplicates/21001-no-stacktrace.swift
11
273
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing func c { case let start = [ { { extension g { enum S { protocol A { struct Q { { } let a { class case ,
mit
austinzheng/swift-compiler-crashes
crashes-duplicates/16022-swift-sourcemanager-getmessage.swift
11
231
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing [ ( ) { func b { protocol a { enum b { class B { class case ,
mit
liujinlongxa/AnimationTransition
testTransitioning/CustomSegue.swift
1
821
// // CustomSegue.swift // AnimationTransition // // Created by Liujinlong on 8/12/15. // Copyright © 2015 Jaylon. All rights reserved. // import UIKit class CustomSegue: UIStoryboardSegue { override func perform() { let fromVCView = self.source.view as UIView let toVCView = self.destination.view as UIView var frame = fromVCView.bounds frame.origin.x += frame.width toVCView.frame = frame UIApplication.shared.keyWindow?.addSubview(toVCView) frame.origin.x = 0 UIView.animate(withDuration: 1.0, animations: { () -> Void in toVCView.frame = frame }, completion: { (_) -> Void in self.source.present(self.destination, animated: false, completion: nil) }) } }
mit
austinzheng/swift-compiler-crashes
crashes-duplicates/16731-swift-sourcemanager-getmessage.swift
11
223
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing e( { enum A { let a { c = [ { struct d { class case ,
mit
alvaromb/CS-Trivia
Swift Playground/MyPlayground.playground/section-1.swift
1
1265
// Álvaro Medina Ballester, 2014 import Cocoa /** * Given a inputString, find the longest palindrome inside it. * Simple version, we just have to loop through all the possible * centers and try to find the biggest palindrome with that center. */ let inputString = "abcbabcbabcba" //"abababa" let inputNSString = inputString as NSString let seqLen = countElements(inputString) let centers = (seqLen * 2) + 1 var palindromeLengths: [Int] = [] var longestPalindromeLength = 0 var longestPalindrome = "" for index in 0..<centers { var leftIndex = index/2 - 1 var rightIndex = index - index/2 // Integer division alternate: Int(ceil(Double(index)/Double(2))) var palindromeLength = index%2 while leftIndex >= 0 && rightIndex < seqLen && Array(inputString)[leftIndex] == Array(inputString)[rightIndex] { leftIndex-- rightIndex++ palindromeLength += 2 } if palindromeLength > longestPalindromeLength { longestPalindrome = inputNSString.substringWithRange(NSMakeRange(leftIndex+1, rightIndex+1)) longestPalindromeLength = palindromeLength } palindromeLengths.append(palindromeLength) } println("Palindrome Lengths \(palindromeLengths)") println("Longest palindrome '\(longestPalindrome)'")
gpl-3.0
sviatoslav/EndpointProcedure
Examples/Using DefaultConfigurationProvider and HTTPRequestDataBuidlerProvider.playground/Sources/SilentCondition.swift
2
618
// // ProcedureKit // // Copyright © 2016 ProcedureKit. All rights reserved. // /** A simple condition which suppresses its contained condition to not enqueue any dependencies. This is useful for verifying access to a resource without prompting for permission, for example. */ public final class SilentCondition<C: Condition>: ComposedCondition<C> { /// Public override of initializer. public override init(_ condition: C) { condition.producedDependencies.forEach { condition.remove(dependency: $0) } super.init(condition) name = condition.name.map { "Silent<\($0)>" } } }
mit
daggmano/photo-management-studio
src/Client/OSX/PMS-2/Photo Management Studio/Photo Management Studio/ImportViewItem.swift
1
2930
// // ImportViewItem.swift // Photo Management Studio // // Created by Darren Oster on 29/04/2016. // Copyright © 2016 Criterion Software. All rights reserved. // import Cocoa class ImportViewItem: NSCollectionViewItem { @IBOutlet weak var titleLabel: NSTextField! @IBOutlet weak var subTitleLabel: NSTextField! private func updateView() { super.viewWillAppear() self.imageView?.image = NSImage(named: "placeholder") titleLabel.stringValue = "" subTitleLabel.stringValue = "" view.toolTip = "" if let item = self.importableItem { titleLabel.stringValue = item.title if let subTitle = item.subTitle { subTitleLabel.stringValue = subTitle self.view.toolTip = "\(item.title)\n\n\(subTitle)" } else { subTitleLabel.stringValue = "" self.view.toolTip = item.title } if !item.imageUrl.containsString("http:") { imageView?.image = NSImage(named: item.imageUrl) } else { var url: String; if (item.imageUrl.containsString("?")) { url = "\(item.imageUrl)&size=500" } else { url = "\(item.imageUrl)?size=500" } print(url) let thumbName = "\(item.identifier!)_500x500.jpg" ImageCache.getImage(url, thumbName: thumbName, useCache: true, callback: { (image) in self.imageView?.image = image self.imageView?.needsDisplay = true }) } } } // MARK: properties var importableItem: PhotoItem? { return representedObject as? PhotoItem } override var representedObject: AnyObject? { didSet { super.representedObject = representedObject if let _ = representedObject as? PhotoItem { self.updateView() } } } override var selected: Bool { didSet { (self.view as! ImportViewItemView).selected = selected } } override var highlightState: NSCollectionViewItemHighlightState { didSet { (self.view as! ImportViewItemView).highlightState = highlightState } } // MARK: NSResponder override func mouseDown(theEvent: NSEvent) { if theEvent.clickCount == 2 { // if let thumbUrl = importableItem?.thumbUrl { // print("Double click \(importableItem!.fullPath)") // Event.emit("display-preview", obj: thumbUrl) // } } else { super.mouseDown(theEvent) } } }
mit
cuappdev/tempo
Tempo/Views/HamburgerIconView.swift
1
4203
// // HamburgerIconView.swift // Tempo // // Created by Dennis Fedorko on 5/10/16. // Copyright © 2016 Dennis Fedorko. All rights reserved. // import UIKit import SWRevealViewController let RevealControllerToggledNotification = "RevealControllerToggled" class HamburgerIconView: UIButton { var topBar: UIView! var middleBar: UIView! var bottomBar: UIView! var isHamburgerMode = true let spacingRatio: CGFloat = 0.2 //MARK: - //MARK: Init init(frame: CGRect, color: UIColor, lineWidth: CGFloat, iconWidthRatio: CGFloat) { super.init(frame: frame) func applyStyle(_ bar: UIView, heightMultiplier: CGFloat) { bar.isUserInteractionEnabled = false bar.center = CGPoint(x: bar.center.x, y: frame.height * heightMultiplier) bar.layer.cornerRadius = lineWidth * 0.5 bar.backgroundColor = color bar.layer.allowsEdgeAntialiasing = true addSubview(bar) } topBar = UIView(frame: CGRect(x: 0, y: 0, width: frame.width * iconWidthRatio, height: lineWidth)) middleBar = UIView(frame: CGRect(x: 0, y: 0, width: frame.width * iconWidthRatio, height: lineWidth)) bottomBar = UIView(frame: CGRect(x: 0, y: 0, width: frame.width * iconWidthRatio, height: lineWidth)) applyStyle(topBar, heightMultiplier: 0.5 - spacingRatio) applyStyle(middleBar, heightMultiplier: 0.5) applyStyle(bottomBar, heightMultiplier: 0.5 + spacingRatio) //be notified when hamburger menu opens/closes NotificationCenter.default.addObserver(self, selector: #selector(hamburgerMenuToggled), name: NSNotification.Name(rawValue: RevealControllerToggledNotification), object: nil) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } //MARK: - //MARK: User Interaction func hamburgerMenuToggled(_ notification: Notification) { if let revealVC = notification.object as? SWRevealViewController { if revealVC.frontViewController.view.isUserInteractionEnabled { //turn on hamburger menu animateToHamburger() } else { animateToClose() } } } func animateIcon() { isUserInteractionEnabled = true if isHamburgerMode { animateToClose() isHamburgerMode = false } else { animateToHamburger() isHamburgerMode = true } } func animateToClose() { if !isHamburgerMode { return } UIView.animate(withDuration: 0.7, delay: 0, usingSpringWithDamping: 0.9, initialSpringVelocity: 30, options: [], animations: { self.middleBar.alpha = 0 }, completion: nil) UIView.animate(withDuration: 0.7, delay: 0, usingSpringWithDamping: 0.5, initialSpringVelocity: 30, options: [], animations: { let rotationClockWise = CGAffineTransform(rotationAngle: CGFloat(M_PI_4)) let rotationCounterClockWise = CGAffineTransform(rotationAngle: CGFloat(-M_PI_4)) let moveDownToCenter = CGAffineTransform(translationX: 0, y: self.frame.height * self.spacingRatio) let moveUpToCenter = CGAffineTransform(translationX: 0, y: -self.frame.height * self.spacingRatio) self.topBar.transform = rotationClockWise.concatenating(moveDownToCenter) self.bottomBar.transform = rotationCounterClockWise.concatenating(moveUpToCenter) }, completion: { _ in self.isUserInteractionEnabled = true }) isHamburgerMode = false } func animateToHamburger() { if isHamburgerMode { return } UIView.animate(withDuration: 0.7, delay: 0, usingSpringWithDamping: 0.9, initialSpringVelocity: 30, options: [], animations: { self.middleBar.alpha = 1 }, completion: nil) UIView.animate(withDuration: 0.7, delay: 0, usingSpringWithDamping: 0.5, initialSpringVelocity: 30, options: [], animations: { self.topBar.transform = CGAffineTransform.identity self.topBar.center = CGPoint(x: self.topBar.center.x, y: self.frame.height * (0.5 - self.spacingRatio)) self.bottomBar.transform = CGAffineTransform.identity self.bottomBar.center = CGPoint(x: self.bottomBar.center.x, y: self.frame.height * (0.5 + self.spacingRatio)) }, completion: { _ in self.isUserInteractionEnabled = true }) isHamburgerMode = true } }
mit
gcirone/Mama-non-mama
Mama non mama/FlowerRainbow.swift
1
10037
// // FlowerRainbow.swift // TestSpriteFlowers // // Created by Cirone, Gianluca on 10/02/15. // Copyright (c) 2015 freshdev. All rights reserved. // import SpriteKit class FlowerRainbow: SKNode { let atlas = SKTextureAtlas(named: "flower-rainbow") deinit { //println("FlowerRainbow.deinit") } override init(){ super.init() name = "flower" let pistillo = SKSpriteNode(texture: atlas.textureNamed("5_pistillo")) pistillo.name = "pistillo" pistillo.position = CGPointMake(0.0, 0.0) //pistillo.size = CGSizeMake(78.0, 80.0) pistillo.zRotation = 0.0 pistillo.zPosition = 10.0 addChild(pistillo) let gambo = SKSpriteNode(texture: atlas.textureNamed("5_gambo")) gambo.name = "gambo" gambo.position = CGPointMake(0.0, 0.0) gambo.anchorPoint = CGPointMake(0.5, 1) //gambo = CGSizeMake(22.0, 367.0) gambo.zRotation = 0.0 gambo.zPosition = -1.0 addChild(gambo) let petalo_0 = SKSpriteNode(texture: atlas.textureNamed("5_petalo_0")) petalo_0.name = "petalo" petalo_0.position = CGPointMake(-73.3526458740234, -30.1807556152344) //petalo_0.size = CGSizeMake(98.0, 30.0) petalo_0.zRotation = 0.483552724123001 petalo_0.zPosition = 3.0 addChild(petalo_0) let petalo_1 = SKSpriteNode(texture: atlas.textureNamed("5_petalo_1")) petalo_1.name = "petalo" petalo_1.position = CGPointMake(-75.8443374633789, 6.2181396484375) //petalo_1.size = CGSizeMake(99.0, 31.0) petalo_1.zRotation = 0.0 petalo_1.zPosition = 3.0 addChild(petalo_1) let petalo_2 = SKSpriteNode(texture: atlas.textureNamed("5_petalo_2")) petalo_2.name = "petalo" petalo_2.position = CGPointMake(-69.0649261474609, 30.3306579589844) //petalo_2.size = CGSizeMake(97.0, 29.0) petalo_2.zRotation = -0.35145291686058 petalo_2.zPosition = 2.0 addChild(petalo_2) let petalo_3 = SKSpriteNode(texture: atlas.textureNamed("5_petalo_3")) petalo_3.name = "petalo" petalo_3.position = CGPointMake(-47.7362060546875, 56.2152099609375) //petalo_3.size = CGSizeMake(29.0, 95.0) petalo_3.zRotation = 0.648896634578705 petalo_3.zPosition = 3.0 addChild(petalo_3) let petalo_4 = SKSpriteNode(texture: atlas.textureNamed("5_petalo_4")) petalo_4.name = "petalo" petalo_4.position = CGPointMake(-1.37254333496094, 76.3231811523438) //petalo_4.size = CGSizeMake(30.0, 96.0) petalo_4.zRotation = 0.0604744032025337 petalo_4.zPosition = 3.0 addChild(petalo_4) let petalo_5 = SKSpriteNode(texture: atlas.textureNamed("5_petalo_5")) petalo_5.name = "petalo" petalo_5.position = CGPointMake(-25.5420379638672, 71.4871826171875) //petalo_5.size = CGSizeMake(29.0, 92.0) petalo_5.zRotation = 0.249543845653534 petalo_5.zPosition = 2.0 addChild(petalo_5) let petalo_6 = SKSpriteNode(texture: atlas.textureNamed("5_petalo_6")) petalo_6.name = "petalo" petalo_6.position = CGPointMake(-58.0411834716797, 45.7310791015625) //petalo_6.size = CGSizeMake(90.0, 34.0) petalo_6.zRotation = -0.65658438205719 petalo_6.zPosition = 1.0 addChild(petalo_6) let petalo_7 = SKSpriteNode(texture: atlas.textureNamed("5_petalo_7")) petalo_7.name = "petalo" petalo_7.position = CGPointMake(-49.8720245361328, -57.9573364257812) //petalo_7.size = CGSizeMake(28.0, 96.0) petalo_7.zRotation = -0.621631443500519 petalo_7.zPosition = 5.0 addChild(petalo_7) let petalo_8 = SKSpriteNode(texture: atlas.textureNamed("5_petalo_8")) petalo_8.name = "petalo" petalo_8.position = CGPointMake(-73.8744659423828, -11.1670227050781) //petalo_8.size = CGSizeMake(96.0, 26.0) petalo_8.zRotation = 0.110586866736412 petalo_8.zPosition = 2.0 addChild(petalo_8) let petalo_9 = SKSpriteNode(texture: atlas.textureNamed("5_petalo_9")) petalo_9.name = "petalo" petalo_9.position = CGPointMake(-60.8856887817383, -48.7349700927734) //petalo_9.size = CGSizeMake(28.0, 97.0) petalo_9.zRotation = -0.731421649456024 petalo_9.zPosition = 2.0 addChild(petalo_9) let petalo_10 = SKSpriteNode(texture: atlas.textureNamed("5_petalo_10")) petalo_10.name = "petalo" petalo_10.position = CGPointMake(-30.1141662597656, -73.4540405273438) //petalo_10.size = CGSizeMake(29.0, 94.0) petalo_10.zRotation = -0.329761922359467 petalo_10.zPosition = 4.0 addChild(petalo_10) let petalo_11 = SKSpriteNode(texture: atlas.textureNamed("5_petalo_11")) petalo_11.name = "petalo" petalo_11.position = CGPointMake(-2.47735595703125, -78.5593566894531) //petalo_11.size = CGSizeMake(31.0, 96.0) petalo_11.zRotation = 0.0570810660719872 petalo_11.zPosition = 3.0 addChild(petalo_11) let petalo_12 = SKSpriteNode(texture: atlas.textureNamed("5_petalo_12")) petalo_12.name = "petalo" petalo_12.position = CGPointMake(24.7819366455078, -76.9860382080078) //petalo_12.size = CGSizeMake(32.0, 97.0) petalo_12.zRotation = 0.2876937687397 petalo_12.zPosition = 2.0 addChild(petalo_12) let petalo_13 = SKSpriteNode(texture: atlas.textureNamed("5_petalo_13")) petalo_13.name = "petalo" petalo_13.position = CGPointMake(45.9588317871094, -68.5952453613281) //petalo_13.size = CGSizeMake(29.0, 99.0) petalo_13.zRotation = 0.628583908081055 petalo_13.zPosition = 1.0 addChild(petalo_13) let petalo_14 = SKSpriteNode(texture: atlas.textureNamed("5_petalo_14")) petalo_14.name = "petalo" petalo_14.position = CGPointMake(76.0393676757812, -30.5138092041016) //petalo_14.size = CGSizeMake(94.0, 31.0) petalo_14.zRotation = -0.365856379270554 petalo_14.zPosition = 2.0 addChild(petalo_14) let petalo_15 = SKSpriteNode(texture: atlas.textureNamed("5_petalo_15")) petalo_15.name = "petalo" petalo_15.position = CGPointMake(61.9654235839844, -51.4241638183594) //petalo_15.size = CGSizeMake(98.0, 31.0) petalo_15.zRotation = -0.669111967086792 petalo_15.zPosition = 0.0 addChild(petalo_15) let petalo_16 = SKSpriteNode(texture: atlas.textureNamed("5_petalo_16")) petalo_16.name = "petalo" petalo_16.position = CGPointMake(76.3208312988281, 17.4443969726562) //petalo_16.size = CGSizeMake(95.0, 27.0) petalo_16.zRotation = 0.23156164586544 petalo_16.zPosition = 3.0 addChild(petalo_16) let petalo_17 = SKSpriteNode(texture: atlas.textureNamed("5_petalo_17")) petalo_17.name = "petalo" petalo_17.position = CGPointMake(74.02685546875, -3.48822021484375) //petalo_17.size = CGSizeMake(92.0, 27.0) petalo_17.zRotation = 0.0 petalo_17.zPosition = 1.0 addChild(petalo_17) let petalo_18 = SKSpriteNode(texture: atlas.textureNamed("5_petalo_18")) petalo_18.name = "petalo" petalo_18.position = CGPointMake(62.664306640625, 51.2071228027344) //petalo_18.size = CGSizeMake(31.0, 99.0) petalo_18.zRotation = -0.747934758663177 petalo_18.zPosition = 3.0 addChild(petalo_18) let petalo_19 = SKSpriteNode(texture: atlas.textureNamed("5_petalo_19")) petalo_19.name = "petalo" petalo_19.position = CGPointMake(73.4706115722656, 36.2119445800781) //petalo_19.size = CGSizeMake(28.0, 95.0) petalo_19.zRotation = -0.943031191825867 petalo_19.zPosition = 2.0 addChild(petalo_19) let petalo_20 = SKSpriteNode(texture: atlas.textureNamed("5_petalo_20")) petalo_20.name = "petalo" petalo_20.position = CGPointMake(32.3933258056641, 69.6167602539062) //petalo_20.size = CGSizeMake(31.0, 91.0) petalo_20.zRotation = -0.359138071537018 petalo_20.zPosition = 3.0 addChild(petalo_20) let petalo_21 = SKSpriteNode(texture: atlas.textureNamed("5_petalo_21")) petalo_21.name = "petalo" petalo_21.position = CGPointMake(17.885498046875, 75.0881042480469) //petalo_21.size = CGSizeMake(27.0, 85.0) petalo_21.zRotation = -0.219870626926422 petalo_21.zPosition = 1.0 addChild(petalo_21) let petalo_22 = SKSpriteNode(texture: atlas.textureNamed("5_petalo_22")) petalo_22.name = "petalo" petalo_22.position = CGPointMake(49.2562408447266, 60.7242431640625) //petalo_22.size = CGSizeMake(28.0, 96.0) petalo_22.zRotation = -0.64398181438446 petalo_22.zPosition = 1.0 addChild(petalo_22) // petalo speciale let petalo_23 = SKSpriteNode(texture: atlas.textureNamed("5_petalo_17")) petalo_23.name = "petalo_mama" petalo_23.position = CGPointMake(73.9085083007812, -23.3897399902344) //petalo_23.size = CGSizeMake(92.0, 27.0) petalo_23.zRotation = -0.199623420834541 petalo_23.zPosition = 0.0 addChild(petalo_23) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
mit
depl0y/pixelbits
pixelbits/Converters/UIEdgeInsetsConverter.swift
1
1647
// // UIEdgeInsetsConverter.swift // pixelbits // // Created by Wim Haanstra on 17/01/16. // Copyright © 2016 Wim Haanstra. All rights reserved. // import UIKit internal class UIEdgeInsetsConverter { /** Converts a value `insets(4, 4, 4, 4)` to a UIEdgeInsets struct - returns: A UIEdgeInsets object or nil if invalid */ static func fromString(valueString: String) -> NSValue? { let expression = "insets\\(([0-9. ,a-zA-Z\\$\\-_]+?)\\)" let matches = valueString.variableValue().matches(expression) if matches.count == 0 { return nil } let insets = matches[0] let insetParts = insets.characters.split { $0 == "," }.map(String.init) var insetValues: [CGFloat] = [] /** * Check if all the inset values are convertible to NSNumber objects. */ for index in 0..<insetParts.count { if let insetValue = insetParts[index].variableValue().toNumber() { insetValues.append(CGFloat(insetValue)) } } switch (insetValues.count) { case 1: return NSValue(UIEdgeInsets: UIEdgeInsetsMake(insetValues[0], insetValues[0], insetValues[0], insetValues[0])) case 2: return NSValue(UIEdgeInsets: UIEdgeInsetsMake(insetValues[0], insetValues[1], insetValues[0], insetValues[1])) case 4: return NSValue(UIEdgeInsets: UIEdgeInsetsMake(insetValues[0], insetValues[1], insetValues[2], insetValues[3])) default: return nil } } }
mit
ben-ng/swift
validation-test/compiler_crashers_fixed/25384-swift-constraints-constraintsystem-opengeneric.swift
1
455
// This source file is part of the Swift.org open source project // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // RUN: not %target-swift-frontend %s -typecheck struct B<T where B:P{{} struct d{{{ }} class B<b let a=B
apache-2.0
danthorpe/Examples
Operations/Last Opened/Last Opened/AppDelegate.swift
1
492
// // AppDelegate.swift // Last Opened // // Created by Daniel Thorpe on 11/01/2016. // Copyright © 2016 Daniel Thorpe. All rights reserved. // import UIKit import Operations @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { Operations.LogManager.severity = .Verbose return true } }
mit
Esri/arcgis-runtime-samples-ios
arcgis-ios-sdk-samplesTests/Sample Tests/SetMinMaxScaleViewControllerTests.swift
1
1454
// // Copyright © 2018 Esri. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // import XCTest import ArcGIS @testable import ArcGIS_Runtime_SDK_Samples class SetMinMaxScaleViewControllerTests: XCTestCase { func makeViewController() -> SetMinMaxScaleViewController { return UIStoryboard(name: "SetMinMaxScale", bundle: nil).instantiateInitialViewController() as! SetMinMaxScaleViewController } func testLoadingView() { let viewController = makeViewController() viewController.loadViewIfNeeded() XCTAssertNotNil(viewController.mapView) if let mapView = viewController.mapView { XCTAssertNotNil(mapView.map) if let map = mapView.map { XCTAssertEqual(map.basemap.name, AGSBasemap.streets().name) XCTAssertEqual(map.minScale, 8_000) XCTAssertEqual(map.maxScale, 2_000) } } } }
apache-2.0
cnoon/swift-compiler-crashes
fixed/25145-void.swift
7
238
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing protocol P{protocol c:a}struct A{struct B{class a{protocol a{class A
mit
cnoon/swift-compiler-crashes
crashes-duplicates/12222-swift-sourcemanager-getmessage.swift
11
233
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing class a { func d { ( > let { protocol P { enum e { class case ,
mit
cnoon/swift-compiler-crashes
crashes-duplicates/17264-no-stacktrace.swift
11
236
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing for in a { { } class A { { } let a = [ { protocol b { class case ,
mit
cnoon/swift-compiler-crashes
crashes-fuzzing/08893-std-function-func-swift-archetypebuilder-maptypeintocontext.swift
11
192
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing enum S<T where S:a>:T.j
mit
cnoon/swift-compiler-crashes
crashes-duplicates/14937-swift-sourcemanager-getmessage.swift
11
235
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing [ { func compose( ) { return ( ) { if true { let a { class case ,
mit
tardieu/swift
validation-test/compiler_crashers_fixed/26467-swift-parser-parsedecl.swift
65
419
// This source file is part of the Swift.org open source project // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // RUN: not %target-swift-frontend %s -typecheck for(n){m class case,
apache-2.0
dsoisson/SwiftLearningExercises
MyPlayground.playground/Contents.swift
1
848
//: Playground - noun: a place where people can play import Foundation func operation(num: Int) -> ((Int) -> Int)? { func single(num: Int) -> Int { return num * 1 } func double(num: Int) -> Int { return num * 2 } func triple(num: Int) -> Int { return num * 3 } func quadruple(num: Int) -> Int { return num * 4 } switch num { case 1: return single case 2: return double case 3: return triple case 4: return quadruple default: return nil } } operation(4) //let c = operation(3)!(4) - operation(1)!(3) //enum Bill : Int { // // case One = 1 // // case Five // // case Ten = 10 // // case Twenty // // case Fifty // // case Hundred // //} // //print(Bill(rawValue: 20)!)
mit
Echx/GridOptic
GridOptic/GridOptic/GameTestViewController.swift
1
4920
// // GameTestViewController.swift // GridOptic // // Created by Lei Mingyu on 01/04/15. // Copyright (c) 2015 Echx. All rights reserved. // import UIKit import SpriteKit class GameTestViewController: UIViewController { @IBOutlet var directionSlider: UISlider? var grid: GOGrid? var object: GOOpticRep? var shapeLayer = CAShapeLayer() override func viewDidLoad() { super.viewDidLoad() self.view.layer.addSublayer(shapeLayer) shapeLayer.strokeEnd = 1.0 shapeLayer.strokeColor = UIColor.whiteColor().CGColor shapeLayer.fillColor = UIColor.clearColor().CGColor shapeLayer.lineWidth = 2.0 // Do any additional setup after loading the view, typically from a nib. self.view.backgroundColor = UIColor.grayColor() self.grid = GOGrid(width: 64, height: 48, andUnitLength: 16) if self.object == nil { self.directionSlider?.userInteractionEnabled = false self.directionSlider?.alpha = 0 } let swipeGesture = UISwipeGestureRecognizer(target: self, action: Selector("didSwipe:")) swipeGesture.direction = UISwipeGestureRecognizerDirection.Down self.view.addGestureRecognizer(swipeGesture) self.directionSlider?.addTarget(self, action: "updateObjectDirection:", forControlEvents: UIControlEvents.ValueChanged) } func updateObjectDirection(sender: UISlider) { self.object?.setDirection(CGVector.vectorFromXPlusRadius(CGFloat(sender.value))) drawInitContent() } override func viewDidAppear(animated: Bool) { drawInitContent() } func drawInitContent() { if let opticRep = self.object { shapeLayer.path = opticRep.bezierPath.CGPath } else { self.setUpGrid() self.drawGrid() self.drawRay() } } private func setUpGrid() { let mirror = GOFlatMirrorRep(center: GOCoordinate(x: 60, y: 35), thickness: 2, length: 6, direction: CGVectorMake(-0.3, 1), id: "MIRROR_1") self.grid?.addInstrument(mirror) let flatLens = GOFlatLensRep(center: GOCoordinate(x: 27, y: 29), thickness: 8, length: 8, direction: CGVectorMake(1, 1), refractionIndex: 1.33, id: "FLAT_LENS_1") self.grid?.addInstrument(flatLens) let concaveLens = GOConcaveLensRep(center: GOCoordinate(x: 44, y: 33), direction: CGVectorMake(0, 1), thicknessCenter: 1, thicknessEdge: 4, curvatureRadius: 5, id: "CONCAVE_LENS_1", refractionIndex: 1.50) self.grid?.addInstrument(concaveLens) let convexLens = GOConvexLensRep(center: GOCoordinate(x: 35, y: 26), direction: CGVectorMake(0, -1), thickness: 3, curvatureRadius: 20, id: "CONVEX_LENS_1", refractionIndex: 1.50) self.grid?.addInstrument(convexLens) let convexLens1 = GOConvexLensRep(center: GOCoordinate(x: 15, y: 25), direction: CGVectorMake(1, -1), thickness: 3, curvatureRadius: 8, id: "CONVEX_LENS_2", refractionIndex: 1.50) self.grid?.addInstrument(convexLens1) } private func drawGrid() { for (id, instrument) in self.grid!.instruments { let layer = self.getPreviewShapeLayer() layer.path = self.grid!.getInstrumentDisplayPathForID(id)?.CGPath self.view.layer.addSublayer(layer) } } private func drawRay() { let ray = GORay(startPoint: CGPoint(x:0.1, y: 24), direction: CGVector(dx: 1, dy: 0)) let layer = self.getPreviewShapeLayer() println("before path calculation") let path = self.grid!.getRayPath(ray) println("after path calculation") println(path.CGPath) layer.path = path.CGPath self.view.layer.addSublayer(layer) let pathAnimation = CABasicAnimation(keyPath: "strokeEnd") pathAnimation.fromValue = 0.0; pathAnimation.toValue = 1.0; pathAnimation.duration = 3.0; pathAnimation.repeatCount = 1.0 pathAnimation.fillMode = kCAFillModeForwards pathAnimation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear) layer.addAnimation(pathAnimation, forKey: "strokeEnd") } private func getPreviewShapeLayer() -> CAShapeLayer { let layer = CAShapeLayer() layer.strokeEnd = 1.0 layer.strokeColor = UIColor.whiteColor().CGColor layer.fillColor = UIColor.clearColor().CGColor layer.lineWidth = 2.0 return layer } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func didSwipe(sender: UISwipeGestureRecognizer) { self.dismissViewControllerAnimated(true, completion: nil) } func setUp(object: GOOpticRep?) { self.object = object } }
mit
nerd010/fabric-sdk-swift
Sources/Proto/Peer/chaincode.pb.swift
1
127
// // chaincode.pb.swift // fabric-sdk-swiftPackageDescription // // Created by Richard on 2017/9/21. // import Foundation
apache-2.0
box/box-ios-sdk
Sources/Modules/WebLinksModule.swift
1
11809
// // WebLinksModule.swift // BoxSDK-iOS // // Created by Cary Cheng on 8/3/19. // Copyright © 2019 box. All rights reserved. // import Foundation /// Provides [Web Link](../Structs/WebLink.html) management. public class WebLinksModule { /// Required for communicating with Box APIs. weak var boxClient: BoxClient! // swiftlint:disable:previous implicitly_unwrapped_optional /// Initializer /// /// - Parameter boxClient: Required for communicating with Box APIs. init(boxClient: BoxClient) { self.boxClient = boxClient } /// Get information about a specified web link. /// /// - Parameters: /// - webLinkId: The ID of the web link on which to retrieve information. /// - fields: Comma-separated list of [fields](https://developer.box.com/reference#fields) to /// include in the response. /// - completion: Returns a full web link object or an error. public func get( webLinkId: String, fields: [String]? = nil, completion: @escaping Callback<WebLink> ) { boxClient.get( url: URL.boxAPIEndpoint("/2.0/web_links/\(webLinkId)", configuration: boxClient.configuration), queryParameters: ["fields": FieldsQueryParam(fields)], completion: ResponseHandler.default(wrapping: completion) ) } // swiftlint:disable unused_param /// Creates a new web link with the specified url on the specified item. /// /// - Parameters: /// - url: The specified url to create the web link for. /// - parentId: The id of the folder item that the web link lives in. /// - name: Optional name value for the created web link. If no name value is specified, defaults to url. /// - description: Optional description value for the created web link. /// - sharedLink: Shared links provide direct, read-only access to files or folder on Box using a URL. /// - fields: Comma-separated list of [fields](https://developer.box.com/reference#fields) to /// include in the response. /// - completion: Returns a full web link object or an error. @available(*, deprecated, message: "Please use create(url:parentId:name:description:fields:completion:)'instead.") public func create( url: String, parentId: String, name: String? = nil, description: String? = nil, sharedLink _: NullableParameter<SharedLinkData>? = nil, fields: [String]? = nil, completion: @escaping Callback<WebLink> ) { create( url: url, parentId: parentId, name: name, description: description, fields: fields, completion: completion ) } // swiftlint:enable unused_param /// Creates a new web link with the specified url on the specified item. /// /// - Parameters: /// - url: The specified url to create the web link for. /// - parentId: The id of the folder item that the web link lives in. /// - name: Optional name value for the created web link. If no name value is specified, defaults to url. /// - description: Optional description value for the created web link. /// - fields: Comma-separated list of [fields](https://developer.box.com/reference#fields) to /// include in the response. /// - completion: Returns a full web link object or an error. public func create( url: String, parentId: String, name: String? = nil, description: String? = nil, fields: [String]? = nil, completion: @escaping Callback<WebLink> ) { var body: [String: Any] = [:] body["parent"] = ["id": parentId] body["url"] = url body["name"] = name body["description"] = description boxClient.post( url: URL.boxAPIEndpoint("/2.0/web_links", configuration: boxClient.configuration), queryParameters: ["fields": FieldsQueryParam(fields)], json: body, completion: ResponseHandler.default(wrapping: completion) ) } /// Update the specified web link info. /// /// - Parameters: /// - webLinkId: The id of the web link to update info for. /// - url: The new url for the web link to update to. /// - parentId: The id of the new parent folder to move the web link. /// - name: The new name for the web link to update to. /// - description: The new description for the web link to update to. /// - sharedLink: Shared links provide direct, read-only access to web link on Box using a URL. /// The canDownload which is inner property in sharedLink is not supported in web links. /// - fields: Comma-separated list of [fields](https://developer.box.com/reference#fields) to /// include in the response. /// - completion: Returns the updated web link object or an error. public func update( webLinkId: String, url: String? = nil, parentId: String? = nil, name: String? = nil, description: String? = nil, sharedLink: NullableParameter<SharedLinkData>? = nil, fields: [String]? = nil, completion: @escaping Callback<WebLink> ) { var body: [String: Any] = [:] body["url"] = url body["name"] = name body["description"] = description if let parentId = parentId { body["parent"] = ["id": parentId] } if let unwrappedSharedLink = sharedLink { switch unwrappedSharedLink { case .null: body["shared_link"] = NSNull() case let .value(sharedLinkValue): var bodyDict = sharedLinkValue.bodyDict // The permissions property is not supported in web link. // So we need to remove this property in case when user set it. bodyDict.removeValue(forKey: "permissions") body["shared_link"] = bodyDict } } boxClient.put( url: URL.boxAPIEndpoint("/2.0/web_links/\(webLinkId)", configuration: boxClient.configuration), queryParameters: ["fields": FieldsQueryParam(fields)], json: body, completion: ResponseHandler.default(wrapping: completion) ) } /// Delete a specified web link. /// /// - Parameters: /// - webLink: The ID of the web link to delete. /// - completion: An empty response will be returned upon successful deletion. public func delete( webLinkId: String, completion: @escaping Callback<Void> ) { boxClient.delete( url: URL.boxAPIEndpoint("/2.0/web_links/\(webLinkId)", configuration: boxClient.configuration), completion: ResponseHandler.default(wrapping: completion) ) } /// Gets web link with updated shared link /// /// - Parameters: /// - webLinkId: The ID of the web link /// - completion: Returns a standard shared link object or an error public func getSharedLink( forWebLink webLinkId: String, completion: @escaping Callback<SharedLink> ) { get(webLinkId: webLinkId, fields: ["shared_link"]) { result in completion(WebLinksModule.unwrapSharedLinkObject(from: result)) } } // swiftlint:disable unused_param /// Creates or updates shared link for a web link /// /// - Parameters: /// - webLink: The ID of the web link /// - access: The level of access. If you omit this field then the access level will be set to the default access level specified by the enterprise admin /// - unsharedAt: The date-time that this link will become disabled. This field can only be set by users with paid accounts /// - vanityName: The custom name of a shared link, as used in the vanityUrl field. /// It should be between 12 and 30 characters. This field can contains only letters, numbers, and hyphens. /// - password: The password required to access the shared link. Set to .null to remove the password /// - canDownload: Whether the shared link allows downloads. Applies to any items in the folder /// - completion: Returns a standard SharedLink object or an error @available(*, deprecated, message: "Please use setSharedLink(forWebLink:access:unsharedAt:vanityName:password:completion:)'instead.") public func setSharedLink( forWebLink webLinkId: String, access: SharedLinkAccess? = nil, unsharedAt: NullableParameter<Date>? = nil, vanityName: NullableParameter<String>? = nil, password: NullableParameter<String>? = nil, canDownload _: Bool? = nil, completion: @escaping Callback<SharedLink> ) { setSharedLink( forWebLink: webLinkId, access: access, unsharedAt: unsharedAt, vanityName: vanityName, password: password, completion: completion ) } // swiftlint:enable unused_param /// Creates or updates shared link for a web link /// /// - Parameters: /// - webLink: The ID of the web link /// - access: The level of access. If you omit this field then the access level will be set to the default access level specified by the enterprise admin /// - unsharedAt: The date-time that this link will become disabled. This field can only be set by users with paid accounts /// - vanityName: The custom name of a shared link, as used in the vanity_url field. /// It should be between 12 and 30 characters. This field can contains only letters, numbers, and hyphens. /// - password: The password required to access the shared link. Set to .null to remove the password /// - completion: Returns a standard SharedLink object or an error public func setSharedLink( forWebLink webLinkId: String, access: SharedLinkAccess? = nil, unsharedAt: NullableParameter<Date>? = nil, vanityName: NullableParameter<String>? = nil, password: NullableParameter<String>? = nil, completion: @escaping Callback<SharedLink> ) { update( webLinkId: webLinkId, sharedLink: .value(SharedLinkData( access: access, password: password, unsharedAt: unsharedAt, vanityName: vanityName )), fields: ["shared_link"] ) { result in completion(WebLinksModule.unwrapSharedLinkObject(from: result)) } } /// Removes shared link for a web link /// /// - Parameters: /// - webLinkId: The ID of the web link /// - completion: Returns an empty response or an error public func deleteSharedLink( forWebLink webLinkId: String, completion: @escaping Callback<Void> ) { update(webLinkId: webLinkId, sharedLink: .null) { result in completion(result.map { _ in }) } } /// Unwrap a SharedLink object from web link /// /// - Parameter result: A standard collection of objects with the web link object or an error /// - Returns: Returns a standard SharedLink object or an error static func unwrapSharedLinkObject(from result: Result<WebLink, BoxSDKError>) -> Result<SharedLink, BoxSDKError> { switch result { case let .success(webLink): guard let sharedLink = webLink.sharedLink else { return .failure(BoxSDKError(message: .notFound("Shared link for web link"))) } return .success(sharedLink) case let .failure(error): return .failure(error) } } }
apache-2.0
fernandomarins/food-drivr-pt
hackathon-for-hunger/Modules/Driver/Dashboards/Views/CurrentDonationsDashboard.swift
1
7193
// // CurrentDonationsDashboard.swift // hackathon-for-hunger // // Created by Ian Gristock on 4/22/16. // Copyright © 2016 Hacksmiths. All rights reserved. // import UIKit import RealmSwift class CurrentDonationsDashboard: UIViewController { // action for unwind segue @IBAction func unwindForAccept(unwindSegue: UIStoryboardSegue, towardsViewController subsequentVC: UIViewController) { } @IBOutlet weak var noDonationsView: UIView! @IBOutlet weak var imageView: UIImageView! @IBOutlet weak var tableView: UITableView! private var refreshControl: UIRefreshControl! var activityIndicator : ActivityIndicatorView! private let dashboardPresenter = DashboardPresenter(donationService: DonationService()) var pendingDonations: Results<Donation>? override func viewDidLoad() { self.noDonationsView.hidden = true super.viewDidLoad() dashboardPresenter.attachView(self) activityIndicator = ActivityIndicatorView(inview: self.view, messsage: "Syncing") refreshControl = UIRefreshControl() refreshControl.addTarget(self, action: #selector(PendingDonationsDashboard.refresh(_:)), forControlEvents: UIControlEvents.ValueChanged) tableView.addSubview(refreshControl) } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) dashboardPresenter.fetch([DonationStatus.Accepted.rawValue, DonationStatus.PickedUp.rawValue]) } func refresh(sender: AnyObject) { self.startLoading() dashboardPresenter.fetchRemotely([DonationStatus.Accepted.rawValue, DonationStatus.PickedUp.rawValue]) refreshControl?.endRefreshing() } @IBAction func toggleMenu(sender: AnyObject) { self.slideMenuController()?.openLeft() } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if (segue.identifier == "toDriverMapDetailCurrentFromDashboard") { if let donation = sender as? Donation { let donationVC = segue.destinationViewController as! DriverMapDetailPendingVC donationVC.donation = donation } } if (segue.identifier == "acceptedDonation") { if let donation = sender as? Donation { let donationVC = segue.destinationViewController as! DriverMapPickupVC donationVC.donation = donation } } } } extension CurrentDonationsDashboard: UITableViewDelegate, UITableViewDataSource { func tableView(tableView: UITableView, editActionsForRowAtIndexPath indexPath: NSIndexPath) -> [UITableViewRowAction]? { let cancel = UITableViewRowAction(style: UITableViewRowActionStyle.Default, title: "Remove" , handler: { (action:UITableViewRowAction!, indexPath:NSIndexPath!) -> Void in let donation = self.pendingDonations![indexPath.row] self.startLoading() self.dashboardPresenter.updateDonationStatus(donation, status: .Pending) }) cancel.backgroundColor = UIColor.redColor() return [cancel] } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return pendingDonations?.count ?? 0 } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let identifier = "pendingDonation" let cell = tableView.dequeueReusableCellWithIdentifier(identifier, forIndexPath: indexPath) as! PendingDonationsDashboardTableViewCell cell.indexPath = indexPath cell.information = pendingDonations![indexPath.row] return cell } func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) { cell.layer.transform = CATransform3DMakeScale(0.1,0.1,1) UIView.animateWithDuration(0.25, animations: { cell.layer.transform = CATransform3DMakeScale(1,1,1) }) } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { self.performSegueWithIdentifier("toDriverMapDetailCurrentFromDashboard", sender: self) } //empty implementation func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { } } extension CurrentDonationsDashboard: DashboardView { func startLoading() { self.activityIndicator.startAnimating() } func finishLoading() { self.activityIndicator.stopAnimating() self.activityIndicator.title = "Syncing" } func donations(sender: DashboardPresenter, didSucceed donations: Results<Donation>) { self.finishLoading() self.pendingDonations = donations self.tableView.reloadData() } func donations(sender: DashboardPresenter, didFail error: NSError) { self.finishLoading() if error.code == 401 { let refreshAlert = UIAlertController(title: "Unable To Sync.", message: "Your session has expired. Please log back in", preferredStyle: UIAlertControllerStyle.Alert) refreshAlert.addAction(UIAlertAction(title: "Ok", style: .Default, handler: { (action: UIAlertAction!) in self.logout() })) presentViewController(refreshAlert, animated: true, completion: nil) } } func donationStatusUpdate(sender: DashboardPresenter, didSucceed donation: Donation) { self.finishLoading() self.dashboardPresenter.fetch([DonationStatus.Accepted.rawValue, DonationStatus.PickedUp.rawValue]) } func donationStatusUpdate(sender: DashboardPresenter, didFail error: NSError) { self.finishLoading() if error.code == 401 { let refreshAlert = UIAlertController(title: "Unable To Sync.", message: "Your session has expired. Please log back in", preferredStyle: UIAlertControllerStyle.Alert) refreshAlert.addAction(UIAlertAction(title: "Ok", style: .Default, handler: { (action: UIAlertAction!) in self.logout() })) presentViewController(refreshAlert, animated: true, completion: nil) } else { let refreshAlert = UIAlertController(title: "Unable To Accept.", message: "Donation might have already been cancelled. Resync your donations?.", preferredStyle: UIAlertControllerStyle.Alert) refreshAlert.addAction(UIAlertAction(title: "Ok", style: .Default, handler: { (action: UIAlertAction!) in self.startLoading() self.dashboardPresenter.fetchRemotely([DonationStatus.Accepted.rawValue, DonationStatus.PickedUp.rawValue]) })) refreshAlert.addAction(UIAlertAction(title: "Cancel", style: .Default, handler: { (action: UIAlertAction!) in })) presentViewController(refreshAlert, animated: true, completion: nil) } } }
mit
HongliYu/firefox-ios
Client/Frontend/Settings/SettingsLoadingView.swift
1
1265
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import UIKit import SnapKit class SettingsLoadingView: UIView { var searchBarHeight: CGFloat = 0 { didSet { setNeedsUpdateConstraints() } } lazy var indicator: UIActivityIndicatorView = { let isDarkTheme = ThemeManager.instance.currentName == .dark let indicator = UIActivityIndicatorView(activityIndicatorStyle: isDarkTheme ? .white : .gray) indicator.hidesWhenStopped = false return indicator }() required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override init(frame: CGRect) { super.init(frame: frame) addSubview(indicator) backgroundColor = UIColor.theme.tableView.headerBackground indicator.startAnimating() } internal override func updateConstraints() { super.updateConstraints() indicator.snp.remakeConstraints { make in make.centerX.equalTo(self) make.centerY.equalTo(self).offset(-(searchBarHeight / 2)) } } }
mpl-2.0
pseudomuto/CircuitBreaker
Pod/Classes/Invoker.swift
1
1319
// // Invoker.swift // Pods // // Created by David Muto on 2016-02-05. // // class Invoker { private let queue: dispatch_queue_t! init(_ queue: dispatch_queue_t) { self.queue = queue } func invoke<T>(state: State, timeout: NSTimeInterval, block: () throws -> T) throws -> T { var endResult: T? = nil var error: ErrorType? = nil exec(timeout.dispatchTime(), block: block) { (result, exc) in error = exc endResult = result } if error != nil { state.onError() throw error! } state.onSuccess() return endResult! } private func exec<T>(timeout: dispatch_time_t, block: () throws -> T, handler: (T?, ErrorType?) -> Void) { let semaphore = dispatch_semaphore_create(0) var result: T? = nil var handled = false let handleError = { (error: ErrorType) in if handled { return } handled = true handler(nil, error) } dispatch_async(queue) { defer { dispatch_semaphore_signal(semaphore) } do { result = try block() } catch let err { handleError(err) } } if dispatch_semaphore_wait(semaphore, timeout) != 0 { handleError(Error.InvocationTimeout) } if !handled { handler(result, nil) } } }
mit
stephentyrone/swift
test/Driver/PrivateDependencies/Inputs/private/d.swift
96
77
# Dependencies after compilation: provides-nominal: [d] depends-nominal: [c]
apache-2.0
zyhndesign/SDX_DG
sdxdg/sdxdg/ConstantsUtil.swift
1
3810
// // ConstantsUtil.swift // sdxdg // // Created by lotusprize on 17/3/16. // Copyright © 2017年 geekTeam. All rights reserved. // import Foundation import UIKit class ConstantsUtil : NSObject { //static var WEB_API_BASE_URL:String = "http://cyzsk.fzcloud.design-engine.org/sdx_cloud" static var WEB_API_BASE_URL:String = "http://192.168.3.166:8080/sdx" static let APP_USER_LOGIN_URL:String = WEB_API_BASE_URL + "/dggl/appUser/authorityCheck" static let APP_USER_UPDATE_URL:String = WEB_API_BASE_URL + "/dggl/appUser/updateUser" static let APP_USER_GET_VIP_URL:String = WEB_API_BASE_URL + "/dggl/appVipUser/getVipuserByShoppingGuideId" static let APP_USER_UPDATE_DATA_URL:String = WEB_API_BASE_URL + "/dggl/appUser/appUpdateUser" static let APP_USER_BACK_HELP_DATA_URL:String = WEB_API_BASE_URL + "/dggl/appHelper/createInfo" static let ALL_USER_UPDATE_PWD:String = WEB_API_BASE_URL + "/dggl/appUser/updatePwd" //创建搭配 static let APP_MATCH_CREATE_URL:String = WEB_API_BASE_URL + "/dggl/match/createMatch" //获取已经分享数据 static let APP_MATCH_LIST_BY_SHARESTATUS_URL:String = WEB_API_BASE_URL + "/dggl/match/getAppMatchByShareStatus" //获取草稿箱数据 static let APP_MATCH_LIST_BY_DRAFT_URL:String = WEB_API_BASE_URL + "/dggl/match/getAppMatchByDraftStatus" //获取反馈数据 static let APP_MATCH_LIST_BY_BACK_URL:String = WEB_API_BASE_URL + "/dggl/match/getAppMatchByBackStatus" //创建反馈 static let APP_MATCH_LIST_FEEDBACK_URL:String = WEB_API_BASE_URL + "/dggl/feedback/createFeedback" //取消反馈 static let APP_MATCH_LIST_CANCEL_FEEDBACK_URL:String = WEB_API_BASE_URL + "/dggl/feedback/deleteFeedback" //获取热门反馈 static let APP_MATCH_LIST_HOT_FEEDBACK_URL:String = WEB_API_BASE_URL + "/dggl/feedback/getDataByUserId" //获取前3个热门反馈 static let APP_MATCH_THREE_HOT_FEEDBACK_URL:String = WEB_API_BASE_URL + "/dggl/feedback/getTopThreeDataByUserId" //获取用户已经分享的数据 static let APP_GET_SHARE_DATA_URL:String = WEB_API_BASE_URL + "/dggl/share/getShareData" //创建分享 static let APP_CREATE_SHARE_DATA_URL:String = WEB_API_BASE_URL + "/dggl/share/createShare" static let APP_GET_STATISTICS_YEAR_DATA:String = WEB_API_BASE_URL + "/dggl/match/getStatisticsDataByYear" static let APP_GET_STATISTICS_MONTH_DATA:String = WEB_API_BASE_URL + "/dggl/match/getStatisticsDataByMonth" static let APP_GET_STATISTICS_WEEK_DATA:String = WEB_API_BASE_URL + "/dggl/match/getStatisticsDataByWeek" static let APP_UPDATE_SHARE_SUCESS_DATE_URL:String = WEB_API_BASE_URL + "/dggl/match/updateShareStatus"; static let APP_MATCH_LIST_BY_CATEGORY = WEB_API_BASE_URL + "/app/hpManage/getHpDataByCategoryId" static let APP_FEEDBACK_VIP_NAMES = WEB_API_BASE_URL + "/dggl/feedback/getFeedbackVipName" static let APP_HPGL_CATEGORY = WEB_API_BASE_URL + "/hpgl/category/getData" static let APP_HPGL_INDEX = WEB_API_BASE_URL + "/hpgl/hpIndexManage/getAppData" static let APP_SHARE_HISTORY_URL = WEB_API_BASE_URL + "/dggl/match/getPushHistoryByVipNameAndUserId" static let APP_HPGL_HP_DETAIL = WEB_API_BASE_URL + "/hpgl/hpManage/productDetail/" static let APP_DGGL_MATCH_DETAIL = WEB_API_BASE_URL + "/dggl/match/matchDetail/" static let APP_DGGL_SHARE_DETAIL = WEB_API_BASE_URL + "/dggl/match/shareDetail/" static let APP_DGGL_SHARE_RESULT_DETAIL = WEB_API_BASE_URL + "/dggl/share/shareDetail/" static let APP_QINIU_TOKEN = WEB_API_BASE_URL + "/hpgl/hpManage/getUploadKey" static let APP_QINIU_UPLOAD_URL = "http://upload.qiniu.com/" static let APP_QINIU_IMAGE_URL_PREFIX = "http://oaycvzlnh.bkt.clouddn.com/" }
apache-2.0
svedm/SweetyViperDemo
SweetyViperDemo/SweetyViperDemo/Classes/PresentationLayer/UserStories/MainUserStory/Module/Main/Interactor/MainInteractorInput.swift
1
215
// // MainMainInteractorInput.swift // SweetyViperDemo // // Created by Svetoslav Karasev on 14/02/2017. // Copyright © 2017 Svedm. All rights reserved. // import Foundation protocol MainInteractorInput { }
mit
k-thorat/Vanilla
examples/iOS/Flavours/AppDelegate.swift
1
1499
// // AppDelegate.swift // Flavours // // Created by Kiran on 30/4/20. // import UIKit import Vanilla @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. print("Vanilla!") print("Sample CheckMe: \(Sample().checkMe())") print("Platform Name: \(Platform().name)") return true } // MARK: UISceneSession Lifecycle func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration { // Called when a new scene session is being created. // Use this method to select a configuration to create the new scene with. return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role) } func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) { // Called when the user discards a scene session. // If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions. // Use this method to release any resources that were specific to the discarded scenes, as they will not return. } }
mit
alblue/swift
test/SILGen/mangling_retroactive_overlay.swift
1
547
// RUN: %empty-directory(%t) // RUN: %build-silgen-test-overlays // RUN: %target-swift-emit-silgen(mock-sdk: -sdk %S/Inputs -I %t) %s -enable-sil-ownership | %FileCheck %s // REQUIRES: objc_interop import ObjectiveC struct RequiresEq<T: Equatable> { } // Note: the NSObject: Equatable conformance from the overlay is not considered // to be a "retroactive" conformance, so ensure that it isn't mangled as such. // CHECK: sil hidden @$s28mangling_retroactive_overlay4testyyAA10RequiresEqVySo8NSObjectCGF func test(_: RequiresEq<NSObject>) { }
apache-2.0
LeeShiYoung/DouYu
DouYuAPP/DouYuAPP/Classes/Main/View/Yo_BaseSectionHeaderView.swift
1
1683
// // Yo_BaseSectionHeaderView.swift // DouYuAPP // // Created by shying li on 2017/3/31. // Copyright © 2017年 李世洋. All rights reserved. // import UIKit class Yo_BaseSectionHeaderView: GenericReusableView, Yo_BaseCollectionViewProtocol { override func configureView() { super.configureView() setupUI() } public lazy var headerIcon: UIImageView = {[weak self] in let headerIcon = UIImageView() self?.addSubview(headerIcon) return headerIcon }() public lazy var sectionName: UILabel = {[weak self] in let sectionName = UILabel() sectionName.font = UIFont.systemFont(ofSize: 16) sectionName.textColor = UIColor.colorWithHex("#020202") self?.addSubview(sectionName) return sectionName }() fileprivate lazy var garyLayer: CALayer = { let garyLayer = CALayer() garyLayer.frame = CGRect(x: 0, y: 0, width: kScreenW, height: 10) garyLayer.backgroundColor = UIColor.colorWithHex("#e5e5e5")?.cgColor return garyLayer }() } extension Yo_BaseSectionHeaderView { fileprivate func setupUI() { layer.addSublayer(garyLayer) headerIcon.snp.makeConstraints { (maker) in maker.left.equalTo(self.snp.left).offset(10) maker.centerY.equalTo(self.snp.centerY).offset(5) } sectionName.snp.makeConstraints { (maker) in maker.centerY.equalTo(headerIcon.snp.centerY) maker.left.equalTo(headerIcon.snp.right).offset(5) } } func configure(Item: Any, indexPath: IndexPath) { } }
apache-2.0
tinrobots/Mechanica
Tests/UIKitTests/UIViewUtilsTests.swift
1
2533
#if os(iOS) || os(tvOS) || os(watchOS) import XCTest @testable import Mechanica final class UIWiewUtilsTests: XCTestCase { func testCornerRadius() { let view = UIView() view.cornerRadius = 5.0 XCTAssertEqual(view.layer.cornerRadius, view.cornerRadius) } func testBorderWidth() { let view = UIView() view.borderWidth = 5.0 XCTAssertEqual(view.layer.borderWidth, view.borderWidth) } func testBorderColor() { let view = UIView() view.borderColor = .red XCTAssertNotNil(view.borderColor) let layerColor = view.layer.borderColor XCTAssertEqual(layerColor, UIColor.red.cgColor) view.borderColor = nil XCTAssertNil(view.borderColor) XCTAssertNil(view.layer.borderColor) } func testShadowRadius() { let view = UIView() view.shadowRadius = 15.0 XCTAssertEqual(view.layer.shadowRadius, view.shadowRadius) } func testShadowOpacity() { let view = UIView() view.shadowOpacity = 0.7 XCTAssertEqual(view.layer.shadowOpacity, view.shadowOpacity) } func testShadowOffset() { let view = UIView() view.shadowOffset = CGSize(width: 12.3, height: 45.6) XCTAssertEqual(view.layer.shadowOffset, view.shadowOffset) } func testShadowColor() { let view = UIView() view.shadowColor = .red XCTAssertNotNil(view.shadowColor) let layerShadowColor = view.layer.shadowColor XCTAssertEqual(layerShadowColor, UIColor.red.cgColor) view.shadowColor = nil XCTAssertNil(view.shadowColor) XCTAssertNil(view.layer.shadowColor) } #if os(iOS) || os(tvOS) func testUseAutolayout() { let view = UIView() let view2 = UIView() view.usesAutoLayout = true XCTAssertFalse(view.translatesAutoresizingMaskIntoConstraints) view.usesAutoLayout = false XCTAssertTrue(view.translatesAutoresizingMaskIntoConstraints) view2.translatesAutoresizingMaskIntoConstraints = false XCTAssertTrue(view2.usesAutoLayout) } func testScreenshot() { let view1 = UIView(frame: CGRect(origin: .zero, size: CGSize(width: 100, height: 50))) view1.backgroundColor = .red let view2 = UIView(frame: CGRect(origin: .zero, size: CGSize(width: 50, height: 25))) view2.backgroundColor = .green view1.addSubview(view2) let screenshot = view1.screenshot() XCTAssertTrue(screenshot.size.width == 100) XCTAssertTrue(screenshot.size.height == 50) XCTAssertFalse(screenshot.size.width == 50) XCTAssertFalse(screenshot.size.height == 100) } #endif } #endif
mit
benlangmuir/swift
stdlib/public/BackDeployConcurrency/AsyncThrowingFlatMapSequence.swift
5
6431
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2021 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// import Swift @available(SwiftStdlib 5.1, *) extension AsyncSequence { /// Creates an asynchronous sequence that concatenates the results of calling /// the given error-throwing transformation with each element of this /// sequence. /// /// Use this method to receive a single-level asynchronous sequence when your /// transformation produces an asynchronous sequence for each element. /// /// In this example, an asynchronous sequence called `Counter` produces `Int` /// values from `1` to `5`. The transforming closure takes the received `Int` /// and returns a new `Counter` that counts that high. For example, when the /// transform receives `3` from the base sequence, it creates a new `Counter` /// that produces the values `1`, `2`, and `3`. The `flatMap(_:)` method /// "flattens" the resulting sequence-of-sequences into a single /// `AsyncSequence`. However, when the closure receives `4`, it throws an /// error, terminating the sequence. /// /// do { /// let stream = Counter(howHigh: 5) /// .flatMap { (value) -> Counter in /// if value == 4 { /// throw MyError() /// } /// return Counter(howHigh: value) /// } /// for try await number in stream { /// print ("\(number)", terminator: " ") /// } /// } catch { /// print(error) /// } /// // Prints: 1 1 2 1 2 3 MyError() /// /// - Parameter transform: An error-throwing mapping closure. `transform` /// accepts an element of this sequence as its parameter and returns an /// `AsyncSequence`. If `transform` throws an error, the sequence ends. /// - Returns: A single, flattened asynchronous sequence that contains all /// elements in all the asychronous sequences produced by `transform`. The /// sequence ends either when the the last sequence created from the last /// element from base sequence ends, or when `transform` throws an error. @inlinable public __consuming func flatMap<SegmentOfResult: AsyncSequence>( _ transform: @escaping (Element) async throws -> SegmentOfResult ) -> AsyncThrowingFlatMapSequence<Self, SegmentOfResult> { return AsyncThrowingFlatMapSequence(self, transform: transform) } } /// An asynchronous sequence that concatenates the results of calling a given /// error-throwing transformation with each element of this sequence. @available(SwiftStdlib 5.1, *) public struct AsyncThrowingFlatMapSequence<Base: AsyncSequence, SegmentOfResult: AsyncSequence> { @usableFromInline let base: Base @usableFromInline let transform: (Base.Element) async throws -> SegmentOfResult @usableFromInline init( _ base: Base, transform: @escaping (Base.Element) async throws -> SegmentOfResult ) { self.base = base self.transform = transform } } @available(SwiftStdlib 5.1, *) extension AsyncThrowingFlatMapSequence: AsyncSequence { /// The type of element produced by this asynchronous sequence. /// /// The flat map sequence produces the type of element in the asynchronous /// sequence produced by the `transform` closure. public typealias Element = SegmentOfResult.Element /// The type of iterator that produces elements of the sequence. public typealias AsyncIterator = Iterator /// The iterator that produces elements of the flat map sequence. public struct Iterator: AsyncIteratorProtocol { @usableFromInline var baseIterator: Base.AsyncIterator @usableFromInline let transform: (Base.Element) async throws -> SegmentOfResult @usableFromInline var currentIterator: SegmentOfResult.AsyncIterator? @usableFromInline var finished = false @usableFromInline init( _ baseIterator: Base.AsyncIterator, transform: @escaping (Base.Element) async throws -> SegmentOfResult ) { self.baseIterator = baseIterator self.transform = transform } /// Produces the next element in the flat map sequence. /// /// This iterator calls `next()` on its base iterator; if this call returns /// `nil`, `next()` returns `nil`. Otherwise, `next()` calls the /// transforming closure on the received element, takes the resulting /// asynchronous sequence, and creates an asynchronous iterator from it. /// `next()` then consumes values from this iterator until it terminates. /// At this point, `next()` is ready to receive the next value from the base /// sequence. If `transform` throws an error, the sequence terminates. @inlinable public mutating func next() async throws -> SegmentOfResult.Element? { while !finished { if var iterator = currentIterator { do { guard let element = try await iterator.next() else { currentIterator = nil continue } // restore the iterator since we just mutated it with next currentIterator = iterator return element } catch { finished = true throw error } } else { guard let item = try await baseIterator.next() else { return nil } let segment: SegmentOfResult do { segment = try await transform(item) var iterator = segment.makeAsyncIterator() guard let element = try await iterator.next() else { currentIterator = nil continue } currentIterator = iterator return element } catch { finished = true currentIterator = nil throw error } } } return nil } } @inlinable public __consuming func makeAsyncIterator() -> Iterator { return Iterator(base.makeAsyncIterator(), transform: transform) } }
apache-2.0
benlangmuir/swift
test/SymbolGraph/Symbols/Mixins/Availability/Duplicated/DeprecatedReplaced.swift
20
1424
// RUN: %empty-directory(%t) // RUN: %target-build-swift %s -module-name DeprecatedReplaced -emit-module -emit-module-path %t/ // RUN: %target-swift-symbolgraph-extract -module-name DeprecatedReplaced -I %t -pretty-print -output-dir %t // RUN: %FileCheck %s --input-file %t/DeprecatedReplaced.symbols.json --check-prefix=DEPRECATED // RUN: %FileCheck %s --input-file %t/DeprecatedReplaced.symbols.json --check-prefix=NOTDEPRECATED // REQUIRES: OS=macosx @available(macOS, deprecated: 7.0) @available(macOS, deprecated: 11.0) public func foo() {} // Last `deprecated` wins. // DEPRECATED-LABEL: "precise": "s:18DeprecatedReplaced3fooyyF", // DEPRECATED: "availability": [ // DEPRECATED-NEXT: { // DEPRECATED-NEXT: "domain": "macOS", // DEPRECATED-NEXT: "deprecated": { // DEPRECATED-NEXT: "major": 11, // DEPRECATED-NEXT: "minor": 0 // DEPRECATED-NEXT: } // DEPRECATED-NEXT: } // DEPRECATED-NEXT: ] @available(macOS, deprecated: 10.0) @available(macOS, introduced: 10.0) public func noLongerDeprecated() {} // NOTDEPRECATED: "precise": "s:18DeprecatedReplaced08noLongerA0yyF", // NOTDEPRECATED: "availability": [ // NOTDEPRECATED-NEXT: { // NOTDEPRECATED-NEXT: "domain": "macOS", // NOTDEPRECATED-NEXT: "introduced": { // NOTDEPRECATED-NEXT: "major": 10, // NOTDEPRECATED-NEXT: "minor": 0 // NOTDEPRECATED-NEXT: } // NOTDEPRECATED-NEXT: } // NOTDEPRECATED-NEXT: ]
apache-2.0
sharath-cliqz/browser-ios
SyncTests/MockSyncServer.swift
2
17493
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation import Shared import GCDWebServers @testable import Sync import XCTest private let log = Logger.syncLogger private func optTimestamp(x: AnyObject?) -> Timestamp? { guard let str = x as? String else { return nil } return decimalSecondsStringToTimestamp(str) } private func optStringArray(x: AnyObject?) -> [String]? { guard let str = x as? String else { return nil } return str.componentsSeparatedByString(",").map { $0.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet()) } } private struct SyncRequestSpec { let collection: String let id: String? let ids: [String]? let limit: Int? let offset: String? let sort: SortOption? let newer: Timestamp? let full: Bool static func fromRequest(request: GCDWebServerRequest) -> SyncRequestSpec? { // Input is "/1.5/user/storage/collection", possibly with "/id" at the end. // That means we get five or six path components here, the first being empty. let parts = request.path!.componentsSeparatedByString("/").filter { !$0.isEmpty } let id: String? let ids = optStringArray(request.query["ids"]) let newer = optTimestamp(request.query["newer"]) let full: Bool = request.query["full"] != nil let limit: Int? if let lim = request.query["limit"] as? String { limit = Int(lim) } else { limit = nil } let offset = request.query["offset"] as? String let sort: SortOption? switch request.query["sort"] as? String ?? "" { case "oldest": sort = SortOption.OldestFirst case "newest": sort = SortOption.NewestFirst case "index": sort = SortOption.Index default: sort = nil } if parts.count < 4 { return nil } if parts[2] != "storage" { return nil } // Use dropFirst, you say! It's buggy. switch parts.count { case 4: id = nil case 5: id = parts[4] default: // Uh oh. return nil } return SyncRequestSpec(collection: parts[3], id: id, ids: ids, limit: limit, offset: offset, sort: sort, newer: newer, full: full) } } struct SyncDeleteRequestSpec { let collection: String? let id: GUID? let ids: [GUID]? let wholeCollection: Bool static func fromRequest(request: GCDWebServerRequest) -> SyncDeleteRequestSpec? { // Input is "/1.5/user{/storage{/collection{/id}}}". // That means we get four, five, or six path components here, the first being empty. return SyncDeleteRequestSpec.fromPath(request.path!, withQuery: request.query) } static func fromPath(path: String, withQuery query: [NSObject: AnyObject]) -> SyncDeleteRequestSpec? { let parts = path.componentsSeparatedByString("/").filter { !$0.isEmpty } let queryIDs: [GUID]? = (query["ids"] as? String)?.componentsSeparatedByString(",") guard [2, 4, 5].contains(parts.count) else { return nil } if parts.count == 2 { return SyncDeleteRequestSpec(collection: nil, id: nil, ids: queryIDs, wholeCollection: true) } if parts[2] != "storage" { return nil } if parts.count == 4 { let hasIDs = queryIDs != nil return SyncDeleteRequestSpec(collection: parts[3], id: nil, ids: queryIDs, wholeCollection: !hasIDs) } return SyncDeleteRequestSpec(collection: parts[3], id: parts[4], ids: queryIDs, wholeCollection: false) } } private struct SyncPutRequestSpec { let collection: String let id: String static func fromRequest(request: GCDWebServerRequest) -> SyncPutRequestSpec? { // Input is "/1.5/user/storage/collection/id}}}". // That means we get six path components here, the first being empty. let parts = request.path!.componentsSeparatedByString("/").filter { !$0.isEmpty } guard parts.count == 5 else { return nil } if parts[2] != "storage" { return nil } return SyncPutRequestSpec(collection: parts[3], id: parts[4]) } } class MockSyncServer { let server = GCDWebServer() let username: String var offsets: Int = 0 var continuations: [String: [EnvelopeJSON]] = [:] var collections: [String: (modified: Timestamp, records: [String: EnvelopeJSON])] = [:] var baseURL: String! init(username: String) { self.username = username } class func makeValidEnvelope(guid: GUID, modified: Timestamp) -> EnvelopeJSON { let clientBody: [String: AnyObject] = [ "id": guid, "name": "Foobar", "commands": [], "type": "mobile", ] let clientBodyString = JSON(clientBody).toString(false) let clientRecord: [String : AnyObject] = [ "id": guid, "collection": "clients", "payload": clientBodyString, "modified": Double(modified) / 1000, ] return EnvelopeJSON(JSON(clientRecord).toString(false)) } class func withHeaders(response: GCDWebServerResponse, lastModified: Timestamp? = nil, records: Int? = nil, timestamp: Timestamp? = nil) -> GCDWebServerResponse { let timestamp = timestamp ?? NSDate.now() let xWeaveTimestamp = millisecondsToDecimalSeconds(timestamp) response.setValue("\(xWeaveTimestamp)", forAdditionalHeader: "X-Weave-Timestamp") if let lastModified = lastModified { let xLastModified = millisecondsToDecimalSeconds(lastModified) response.setValue("\(xLastModified)", forAdditionalHeader: "X-Last-Modified") } if let records = records { response.setValue("\(records)", forAdditionalHeader: "X-Weave-Records") } return response; } func storeRecords(records: [EnvelopeJSON], inCollection collection: String, now: Timestamp? = nil) { let now = now ?? NSDate.now() let coll = self.collections[collection] var out = coll?.records ?? [:] records.forEach { out[$0.id] = $0.withModified(now) } let newModified = max(now, coll?.modified ?? 0) self.collections[collection] = (modified: newModified, records: out) } private func splitArray<T>(items: [T], at: Int) -> ([T], [T]) { return (Array(items.dropLast(items.count - at)), Array(items.dropFirst(at))) } private func recordsMatchingSpec(spec: SyncRequestSpec) -> (records: [EnvelopeJSON], offsetID: String?)? { // If we have a provided offset, handle that directly. if let offset = spec.offset { log.debug("Got provided offset \(offset).") guard let remainder = self.continuations[offset] else { log.error("Unknown offset.") return nil } // Remove the old one. self.continuations.removeValueForKey(offset) // Handle the smaller-than-limit or no-provided-limit cases. guard let limit = spec.limit where limit < remainder.count else { log.debug("Returning all remaining items.") return (remainder, nil) } // Record the next continuation and return the first slice of records. let next = "\(self.offsets)" self.offsets += 1 let (returned, remaining) = splitArray(remainder, at: limit) self.continuations[next] = remaining log.debug("Returning \(limit) items; next continuation is \(next).") return (returned, next) } guard let records = self.collections[spec.collection]?.records.values else { // No matching records. return ([], nil) } var items = Array(records) log.debug("Got \(items.count) candidate records.") if spec.newer ?? 0 > 0 { items = items.filter { $0.modified > spec.newer } } if let ids = spec.ids { let ids = Set(ids) items = items.filter { ids.contains($0.id) } } if let sort = spec.sort { switch sort { case SortOption.NewestFirst: items = items.sort { $0.modified > $1.modified } log.debug("Sorted items newest first: \(items.map { $0.modified })") case SortOption.OldestFirst: items = items.sort { $0.modified < $1.modified } log.debug("Sorted items oldest first: \(items.map { $0.modified })") case SortOption.Index: log.warning("Index sorting not yet supported.") } } if let limit = spec.limit where items.count > limit { let next = "\(self.offsets)" self.offsets += 1 let (returned, remaining) = splitArray(items, at: limit) self.continuations[next] = remaining return (returned, next) } return (items, nil) } private func recordResponse(record: EnvelopeJSON) -> GCDWebServerResponse { let body = JSON(record.asJSON()).toString() let bodyData = body.utf8EncodedData let response = GCDWebServerDataResponse(data: bodyData, contentType: "application/json") return MockSyncServer.withHeaders(response, lastModified: record.modified) } private func modifiedResponse(timestamp: Timestamp) -> GCDWebServerResponse { let body = JSON(["modified": NSNumber(value: timestamp)]).toString() let bodyData = body.utf8EncodedData let response = GCDWebServerDataResponse(data: bodyData, contentType: "application/json") return MockSyncServer.withHeaders(response) } func modifiedTimeForCollection(collection: String) -> Timestamp? { return self.collections[collection]?.modified } func removeAllItemsFromCollection(collection: String, atTime: Timestamp) { if self.collections[collection] != nil { self.collections[collection] = (atTime, [:]) } } func start() { let basePath = "/1.5/\(self.username)" let storagePath = "\(basePath)/storage/" let infoCollectionsPath = "\(basePath)/info/collections" server.addHandlerForMethod("GET", path: infoCollectionsPath, requestClass: GCDWebServerRequest.self) { (request) -> GCDWebServerResponse! in var ic = [String: NSNumber]() var lastModified: Timestamp = 0 for collection in self.collections.keys { if let timestamp = self.modifiedTimeForCollection(collection) { ic[collection] = NSNumber(double: Double(timestamp) / 1000) lastModified = max(lastModified, timestamp) } } let body = JSON(ic).toString() let bodyData = body.utf8EncodedData let response = GCDWebServerDataResponse(data: bodyData, contentType: "application/json") return MockSyncServer.withHeaders(response, lastModified: lastModified, records: ic.count) } let matchPut: GCDWebServerMatchBlock = { method, url, headers, path, query -> GCDWebServerRequest! in guard method == "PUT" && path.startsWith(basePath) else { return nil } return GCDWebServerDataRequest(method: method, url: url, headers: headers, path: path, query: query) } server.addHandlerWithMatchBlock(matchPut) { (request) -> GCDWebServerResponse! in guard let request = request as? GCDWebServerDataRequest else { return MockSyncServer.withHeaders(GCDWebServerDataResponse(statusCode: 400)) } guard let spec = SyncPutRequestSpec.fromRequest(request) else { return MockSyncServer.withHeaders(GCDWebServerDataResponse(statusCode: 400)) } var body = JSON(request.jsonObject).asDictionary! body["modified"] = JSON(millisecondsToDecimalSeconds(NSDate.now())) let record = EnvelopeJSON(JSON(body)) self.storeRecords([record], inCollection: spec.collection) let timestamp = self.modifiedTimeForCollection(spec.collection)! let response = GCDWebServerDataResponse(data: millisecondsToDecimalSeconds(timestamp).utf8EncodedData, contentType: "application/json") return MockSyncServer.withHeaders(response) } let matchDelete: GCDWebServerMatchBlock = { method, url, headers, path, query -> GCDWebServerRequest! in guard method == "DELETE" && path.startsWith(basePath) else { return nil } return GCDWebServerRequest(method: method, url: url, headers: headers, path: path, query: query) } server.addHandlerWithMatchBlock(matchDelete) { (request) -> GCDWebServerResponse! in guard let spec = SyncDeleteRequestSpec.fromRequest(request) else { return GCDWebServerDataResponse(statusCode: 400) } if let collection = spec.collection, id = spec.id { guard var items = self.collections[collection]?.records else { // Unable to find the requested collection. return MockSyncServer.withHeaders(GCDWebServerDataResponse(statusCode: 404)) } guard let item = items[id] else { // Unable to find the requested id. return MockSyncServer.withHeaders(GCDWebServerDataResponse(statusCode: 404)) } items.removeValueForKey(id) return self.modifiedResponse(item.modified) } if let collection = spec.collection { if spec.wholeCollection { self.collections.removeValueForKey(collection) } else { if let ids = spec.ids, var map = self.collections[collection]?.records { for id in ids { map.removeValueForKey(id) } self.collections[collection] = (modified: NSDate.now(), records: map) } } return self.modifiedResponse(NSDate.now()) } self.collections = [:] return MockSyncServer.withHeaders(GCDWebServerDataResponse(data: "{}".utf8EncodedData, contentType: "application/json")) } let match: GCDWebServerMatchBlock = { method, url, headers, path, query -> GCDWebServerRequest! in guard method == "GET" && path.startsWith(storagePath) else { return nil } return GCDWebServerRequest(method: method, url: url, headers: headers, path: path, query: query) } server.addHandlerWithMatchBlock(match) { (request) -> GCDWebServerResponse! in // 1. Decide what the URL is asking for. It might be a collection fetch or // an individual record, and it might have query parameters. guard let spec = SyncRequestSpec.fromRequest(request) else { return MockSyncServer.withHeaders(GCDWebServerDataResponse(statusCode: 400)) } // 2. Grab the matching set of records. Prune based on TTL, exclude with X-I-U-S, etc. if let id = spec.id { guard let collection = self.collections[spec.collection], record = collection.records[id] else { // Unable to find the requested collection/id. return MockSyncServer.withHeaders(GCDWebServerDataResponse(statusCode: 404)) } return self.recordResponse(record) } guard let (items, offset) = self.recordsMatchingSpec(spec) else { // Unable to find the provided offset. return MockSyncServer.withHeaders(GCDWebServerDataResponse(statusCode: 400)) } // TODO: TTL // TODO: X-I-U-S let body = JSON(items.map { $0.asJSON() }).toString() let bodyData = body.utf8EncodedData let response = GCDWebServerDataResponse(data: bodyData, contentType: "application/json") // 3. Compute the correct set of headers: timestamps, X-Weave-Records, etc. if let offset = offset { response.setValue(offset, forAdditionalHeader: "X-Weave-Next-Offset") } let timestamp = self.modifiedTimeForCollection(spec.collection)! log.debug("Returning GET response with X-Last-Modified for \(items.count) records: \(timestamp).") return MockSyncServer.withHeaders(response, lastModified: timestamp, records: items.count) } if server.startWithPort(0, bonjourName: nil) == false { XCTFail("Can't start the GCDWebServer.") } baseURL = "http://localhost:\(server.port)\(basePath)" } }
mpl-2.0
tungvoduc/DTButtonMenuController
Example/Tests/Tests.swift
1
1172
// https://github.com/Quick/Quick import Quick import Nimble import DTButtonMenuController class TableOfContentsSpec: QuickSpec { override func spec() { describe("these will fail") { it("can do maths") { expect(1) == 2 } it("can read") { expect("number") == "string" } it("will eventually fail") { expect("time").toEventually( equal("done") ) } context("these will pass") { it("can do maths") { expect(23) == 23 } it("can read") { expect("🐮") == "🐮" } it("will eventually pass") { var time = "passing" DispatchQueue.main.async { time = "done" } waitUntil { done in Thread.sleep(forTimeInterval: 0.5) expect(time) == "done" done() } } } } } }
mit
aapierce0/MatrixClient
MatrixClient/AppDelegate.swift
1
5755
/* Copyright 2017 Avery Pierce 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 Cocoa import SwiftMatrixSDK protocol MatrixSessionManagerDelegate { func matrixDidStart(_ session: MXSession) func matrixDidLogout() } class MatrixSessionManager { static let shared = MatrixSessionManager() static let credentialsDictionaryKey = "MatrixCredentials" enum State { case needsCredentials, notStarted, starting, started } private(set) var state: State var credentials: MXCredentials? { didSet { // Make sure to synchronize the user defaults after we're done here defer { UserDefaults.standard.synchronize() } guard let homeServer = credentials?.homeServer, let userId = credentials?.userId, let token = credentials?.accessToken else { UserDefaults.standard.removeObject(forKey: "MatrixCredentials"); return } let storedCredentials: [String: String] = [ "homeServer": homeServer, "userId": userId, "token": token ] UserDefaults.standard.set(storedCredentials, forKey: "MatrixCredentials") } } var session: MXSession? var delegate: MatrixSessionManagerDelegate? init() { // Make sure that someone is logged in. if let savedCredentials = UserDefaults.standard.dictionary(forKey: MatrixSessionManager.credentialsDictionaryKey), let homeServer = savedCredentials["homeServer"] as? String, let userId = savedCredentials["userId"] as? String, let token = savedCredentials["token"] as? String { credentials = MXCredentials(homeServer: homeServer, userId: userId, accessToken: token) state = .notStarted } else { state = .needsCredentials credentials = nil } } func start() { guard let credentials = credentials else { return } let restClient = MXRestClient(credentials: credentials, unrecognizedCertificateHandler: nil) session = MXSession(matrixRestClient: restClient) state = .starting let fileStore = MXFileStore() session?.setStore(fileStore) { response in if case .failure(let error) = response { print("An error occurred setting the store: \(error)") return } self.state = .starting self.session?.start { response in guard response.isSuccess else { return } DispatchQueue.main.async { self.state = .started self.delegate?.matrixDidStart(self.session!); } } } } func logout() { UserDefaults.standard.removeObject(forKey: MatrixSessionManager.credentialsDictionaryKey) UserDefaults.standard.synchronize() self.credentials = nil self.state = .needsCredentials session?.logout { _ in self.delegate?.matrixDidLogout() } } } @NSApplicationMain class AppDelegate: NSObject, NSApplicationDelegate, MatrixSessionManagerDelegate { func applicationDidFinishLaunching(_ aNotification: Notification) { // Insert code here to initialize your application MatrixSessionManager.shared.delegate = self } func applicationWillTerminate(_ aNotification: Notification) { // Insert code here to tear down your application } func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication) -> Bool { return false } func matrixDidStart(_ session: MXSession) { let allViewControllers = NSApplication.shared().windows.flatMap({ return $0.descendentViewControllers }) allViewControllers.flatMap({ return $0 as? MatrixSessionManagerDelegate }).forEach { (delegate) in delegate.matrixDidStart(session) } } func matrixDidLogout() { let allViewControllers = NSApplication.shared().windows.flatMap({ return $0.descendentViewControllers }) allViewControllers.flatMap({ return $0 as? MatrixSessionManagerDelegate }).forEach { (delegate) in delegate.matrixDidLogout() } } } fileprivate extension NSWindow { var descendentViewControllers: [NSViewController] { var descendents = [NSViewController]() if let rootViewController = windowController?.contentViewController { descendents.append(rootViewController) descendents.append(contentsOf: rootViewController.descendentViewControllers) } return descendents } } fileprivate extension NSViewController { var descendentViewControllers: [NSViewController] { // Capture this view controller's children, and add their descendents var descendents = childViewControllers descendents.append(contentsOf: childViewControllers.flatMap({ return $0.descendentViewControllers })) return descendents } }
apache-2.0
ryanfowler/RFTimer
RFTimer.swift
1
7357
// // RFTimer.swift // // Copyright (c) 2014 Ryan Fowler // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation import UIKit public class RFTimer { //declare RFTimer properties var startTime: NSDate? var tagName: String var timer = NSTimer() var intervals = 0 var inTimer = false var delegate: RFTimerDelegate? let notifCenter = NSNotificationCenter.defaultCenter() /** Start the timer */ public func start() { if !inTimer { startTime = NSDate() delegate?.timerStatusUpdated(self, isOn: true) timer = NSTimer.scheduledTimerWithTimeInterval(0.1, target: self, selector: "timerFireMethod", userInfo: nil, repeats: true) if let err = SD.executeChange("INSERT INTO RFTimerTemp (StartingTime, Tag, Singleton) VALUES (?, ?, 0)", withArgs: [startTime!, tagName]) { println("Error inserting item to RFTimerTemp") } intervals = 0 inTimer = true println("Timer started") } } /** Stop the timer and save it in the database */ public func stopAndSave() { if inTimer { timer.invalidate() delegate?.timerStatusUpdated(self, isOn: false) //insert the new timer event if let err = SD.executeChange("INSERT INTO RFTimer (StartingTime, EndingTime, Duration, Tag) VALUES (\(SD.escapeValue(startTime!)), \(SD.escapeValue(NSDate())), \(SD.escapeValue(Int(NSDate().timeIntervalSinceDate(startTime!)))), \(SD.escapeValue(tagName)))") { println("Error inserting row into RFTimer") } //delete the temp timer if let err = SD.executeChange("DELETE FROM RFTimerTemp") { println("Error deleting row from RFTimerTemp") } inTimer = false println("Timer stopped") } } init(tag: String) { //create RFTimerTemp table in the database if it does not already exist if let err = SD.executeChange("CREATE TABLE IF NOT EXISTS RFTimerTemp (ID INTEGER PRIMARY KEY AUTOINCREMENT, StartingTime DATE, Tag TEXT, Singleton INTEGER UNIQUE)") { println("Error attempting to create RFTimerTemp table in the RFTimer database") } //create RFTimer table in the database if it does not already exist if let err = SD.executeChange("CREATE TABLE IF NOT EXISTS RFTimer (ID INTEGER PRIMARY KEY AUTOINCREMENT, StartingTime DATE, EndingTime DATE, Duration INTEGER, Tag TEXT)") { println("Error attempting to create the RTTimer table in the database") } //create index on Tag column if it does not already exist if let err = SD.executeChange("CREATE INDEX IF NOT EXISTS TagIndex ON RFTimer (Tag)") { println("Error attempting to create TagIndex on the RFTimer table") } //add the tag tagName = tag //add self as an observer notifCenter.addObserver(self, selector: "wakeTimer", name: UIApplicationDidBecomeActiveNotification, object: nil) notifCenter.addObserver(self, selector: "sleepTimer", name: UIApplicationDidEnterBackgroundNotification, object: nil) } deinit { notifCenter.removeObserver(self) } @objc private func timerFireMethod() { ++intervals if intervals % 20 == 0 { intervals = Int(NSDate().timeIntervalSinceDate(startTime!)) * 10 } delegate?.timerFired(self, seconds: intervals/10 % 60, minutes: intervals/600 % 60, hours: intervals/36000) } @objc private func wakeTimer() { let (result, err) = SD.executeQuery("SELECT * FROM RFTimerTemp") if err != nil { println("Query of RFTimerTemp failed") } else { if result.count > 0 { println("Timer awoken from sleep") if let start = result[0]["StartingTime"]?.asDate() { if let tag = result[0]["Tag"]?.asString() { intervals = Int(NSDate().timeIntervalSinceDate(start)) * 10 inTimer = true startTime = start tagName = tag delegate?.timerFired(self, seconds: intervals/10 % 60, minutes: intervals/600 % 60, hours: intervals/36000) delegate?.timerStatusUpdated(self, isOn: true) timer = NSTimer.scheduledTimerWithTimeInterval(0.1, target: self, selector: "timerFireMethod", userInfo: nil, repeats: true) } } } } } @objc private func sleepTimer() { if inTimer { println("Timer sent to sleep") delegate?.timerStatusUpdated(self, isOn: true) timer.invalidate() } } } public protocol RFTimerDelegate { /** The timer has fired Anything that needs to be done when there is a change of time, such as update the UI, should be done in this function. This functions gets called roughly 10 times a second. */ func timerFired(timer: RFTimer, seconds: Int, minutes: Int, hours: Int) /** The timer status has been updated This function gets called when the timer has been turned on, woken from sleep, turned off, or sent to sleep. */ func timerStatusUpdated(timer: RFTimer, isOn: Bool) } extension SwiftData { /** Get all existing tags :returns: An array of strings with all existing tags, or nil if there was an error */ public static func getAllTags() -> [String]? { var (results, err) = SD.executeQuery("SELECT DISTINCT Tag FROM RFTimer") if err != nil { println("Error finding tables") } else { var tables = [String]() for result in results { if let tag = result["Tag"]?.asString() { tables.append(tag) } } return tables } return nil } }
mit
isgustavo/AnimatedMoviesMakeMeCry
iOS/Animated Movies Make Me Cry/Pods/Firebase/Samples/storage/StorageExampleSwift/AppDelegate.swift
9
1027
// // Copyright (c) 2016 Google Inc. // // 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 Firebase @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // [START firebase_configure] // Use Firebase library to configure APIs FIRApp.configure() // [END firebase_configure] return true } }
apache-2.0
chicio/RangeUISlider
Source/UI/Progress.swift
1
2307
// // ProgressView.swift // RangeUISlider // // Created by Fabrizio Duroni on 29/09/2017. // 2017 Fabrizio Duroni. // import Foundation import UIKit /** The `Progress` UI view RangeUIslider. It is a customized `UIView`. It is a subclass of `Gradient` view. */ public class Progress: Gradient { func setup( leftAnchorView: UIView, rightAnchorView: UIView, properties: ProgressProperties ) -> [NSLayoutConstraint] { accessibilityIdentifier = "Progress" translatesAutoresizingMaskIntoConstraints = false backgroundColor = properties.color let views = ConstraintViews(target: self, related: superview) return [ DimensionConstraintFactory.equalHeight(views: views), PositionConstraintFactory.centerY(views: views), MarginConstraintFactory.leadingTo( attribute: properties.leftAnchorConstraintAttribute, views: ConstraintViews(target: self, related: leftAnchorView), value: 0.0 ), MarginConstraintFactory.trailingTo( attribute: properties.rightAnchorConstraintAttribute, views: ConstraintViews(target: self, related: rightAnchorView), value: 0.0 ) ] } func addBackground(image: UIImage, edgeInset: UIEdgeInsets, corners: CGFloat) { let backgroundImageView = createBackgroundUsing(image: image, edgeInset: edgeInset, corners: corners) let views = ConstraintViews(target: backgroundImageView, related: self) addSubview(backgroundImageView) NSLayoutConstraint.activate(MatchingMarginConstraintFactory.make(views: views)) } private func createBackgroundUsing(image: UIImage, edgeInset: UIEdgeInsets, corners: CGFloat) -> UIView { let backgroundResizableImage = image.resizableImage(withCapInsets: edgeInset) let backgroundImageView = UIImageView(image: backgroundResizableImage) backgroundImageView.translatesAutoresizingMaskIntoConstraints = false backgroundImageView.layer.masksToBounds = corners > 0 backgroundImageView.layer.cornerRadius = corners backgroundImageView.accessibilityIdentifier = "ProgressBackground" return backgroundImageView } }
mit
wangela/wittier
wittier/Views/TweetCell.swift
1
8890
// // TweetCell.swift // wittier // // Created by Angela Yu on 9/26/17. // Copyright © 2017 Angela Yu. All rights reserved. // import UIKit import AFNetworking @objc protocol TweetCellDelegate { @objc optional func replyButtonTapped(tweetCell: TweetCell) @objc optional func profileButtonTapped(tweetCell: TweetCell) } extension Date { var yearsFromNow: Int { return Calendar.current.dateComponents([.year], from: self, to: Date()).year ?? 0 } var monthsFromNow: Int { return Calendar.current.dateComponents([.month], from: self, to: Date()).month ?? 0 } var weeksFromNow: Int { return Calendar.current.dateComponents([.weekOfYear], from: self, to: Date()).weekOfYear ?? 0 } var daysFromNow: Int { return Calendar.current.dateComponents([.day], from: self, to: Date()).day ?? 0 } var hoursFromNow: Int { return Calendar.current.dateComponents([.hour], from: self, to: Date()).hour ?? 0 } var minutesFromNow: Int { return Calendar.current.dateComponents([.minute], from: self, to: Date()).minute ?? 0 } var secondsFromNow: Int { return Calendar.current.dateComponents([.second], from: self, to: Date()).second ?? 0 } var relativeTime: String { if yearsFromNow > 0 { return "\(yearsFromNow) year" + (yearsFromNow > 1 ? "s" : "") + " ago" } if monthsFromNow > 0 { return "\(monthsFromNow) month" + (monthsFromNow > 1 ? "s" : "") + " ago" } if weeksFromNow > 0 { return "\(weeksFromNow) week" + (weeksFromNow > 1 ? "s" : "") + " ago" } if daysFromNow > 0 { return daysFromNow == 1 ? "Yesterday" : "\(daysFromNow) days ago" } if hoursFromNow > 0 { return "\(hoursFromNow) hour" + (hoursFromNow > 1 ? "s" : "") + " ago" } if minutesFromNow > 0 { return "\(minutesFromNow) minute" + (minutesFromNow > 1 ? "s" : "") + " ago" } if secondsFromNow > 0 { return secondsFromNow < 15 ? "Just now" : "\(secondsFromNow) second" + (secondsFromNow > 1 ? "s" : "") + " ago" } return "" } } class TweetCell: UITableViewCell { @IBOutlet weak var profileButton: UIButton! @IBOutlet weak var displayNameLabel: UILabel! @IBOutlet weak var screennameLabel: UILabel! @IBOutlet weak var tweetLabel: UILabel! @IBOutlet weak var timestampLabel: UILabel! @IBOutlet weak var retweetButton: UIButton! @IBOutlet weak var rtCountLabel: UILabel! @IBOutlet weak var favoriteButton: UIButton! @IBOutlet weak var favCountLabel: UILabel! @IBOutlet weak var superContentView: UIView! @IBOutlet weak var retweetView: UIView! @IBOutlet weak var retweeterLabel: UILabel! var delegate: TweetCellDelegate? var retweeter: User? var tweet: Tweet! { didSet { guard let user = tweet.user else { print("nil user") return } displayNameLabel.text = user.name screennameLabel.text = user.screenname tweetLabel.text = tweet.text tweetLabel.sizeToFit() if let profileURL = user.profileURL { profileButton.setBackgroundImageFor(.normal, with: profileURL) } else { profileButton.setImage(nil, for: .normal) } // Build relative timestamp if let timestamp = tweet.timestamp { let formatter = DateFormatter() formatter.dateFormat = "EEE MMM d HH:mm:ss Z y" if let timestampDate = formatter.date(from: timestamp) { let relativeTimestamp = timestampDate.relativeTime timestampLabel.text = relativeTimestamp } } showStats() showRetweet() } } override func awakeFromNib() { super.awakeFromNib() profileButton.layer.cornerRadius = profileButton.frame.size.width * 0.5 profileButton.clipsToBounds = true } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } func showStats() { // Show retweet stats if tweet.retweeted { retweetButton.setImage(#imageLiteral(resourceName: "retweet"), for: .normal) } else { retweetButton.setImage(#imageLiteral(resourceName: "retweet-aaa"), for: .normal) } rtCountLabel.text = "\(tweet.retweetCount)" // Show favorite stats if tweet.favorited { favoriteButton.setImage(#imageLiteral(resourceName: "favorite-blk"), for: .normal) } else { favoriteButton.setImage(#imageLiteral(resourceName: "favorite-aaa"), for: .normal) } favCountLabel.text = "\(tweet.favoritesCount)" } func showRetweet() { // Show retweet info if this is a retweet if let retweetUser = retweeter { if let retweeterName = retweetUser.name { retweeterLabel.text = "\(retweeterName) Retweeted" } else { retweeterLabel.text = "Somebody Retweeted" } retweetView.isHidden = false } else { retweetView.isHidden = true } } @IBAction func onProfileButton(_ sender: Any) { if let _ = delegate { delegate?.profileButtonTapped?(tweetCell: self) } } @IBAction func onReplyButton(_ sender: Any) { if let _ = delegate { delegate?.replyButtonTapped?(tweetCell: self) } } @IBAction func onRetweetButton(_ sender: Any) { guard let tweetID = tweet.idNum else { print("bad tweet ID") return } let rtState = tweet.retweeted let rtCount = tweet.retweetCount if rtState { TwitterClient.sharedInstance.retweet(retweetMe: false, id: tweetID, success: { (newTweet: Tweet) -> Void in self.tweet.retweeted = !rtState self.tweet.retweetCount = rtCount - 1 self.retweetButton.setImage(#imageLiteral(resourceName: "retweet-aaa"), for: .normal) self.rtCountLabel.text = "\(self.tweet.retweetCount)" }, failure: { (error: Error) -> Void in print("\(error.localizedDescription)") }) } else { TwitterClient.sharedInstance.retweet(retweetMe: true, id: tweetID, success: { (newTweet: Tweet) -> Void in self.tweet.retweeted = !rtState self.tweet.retweetCount = rtCount + 1 self.retweetButton.setImage(#imageLiteral(resourceName: "retweet"), for: .normal) self.rtCountLabel.text = "\(self.tweet.retweetCount)" }, failure: { (error: Error) -> Void in print("\(error.localizedDescription)") }) } } @IBAction func onFavoriteButton(_ sender: Any) { guard let tweetID = tweet.idNum else { print("bad tweet ID") return } let faveState = tweet.favorited let faveCount = tweet.favoritesCount if faveState { TwitterClient.sharedInstance.fave(faveMe: false, id: tweetID, success: { (newTweet: Tweet) -> Void in self.tweet.favorited = !faveState self.tweet.favoritesCount = faveCount - 1 self.favoriteButton.setImage(#imageLiteral(resourceName: "favorite-aaa"), for: .normal) self.favCountLabel.text = "\(self.tweet.favoritesCount)" }, failure: { (error: Error) -> Void in print("\(error.localizedDescription)") }) } else { TwitterClient.sharedInstance.fave(faveMe: true, id: tweetID, success: { (newTweet: Tweet) -> Void in self.tweet.favorited = !faveState self.tweet.favoritesCount = faveCount + 1 self.favoriteButton.setImage(#imageLiteral(resourceName: "favorite-blk"), for: .normal) self.favCountLabel.text = "\(self.tweet.favoritesCount)" }, failure: { (error: Error) -> Void in print("\(error.localizedDescription)") }) } } }
mit
kingsic/SGSegmentedControl
Sources/PagingTitle/SGPagingTitleView.swift
2
64853
// // SGPagingTitleView.swift // SGPagingView // // Created by kingsic on 2020/12/23. // Copyright © 2020 kingsic. All rights reserved. // import UIKit @objc public protocol SGPagingTitleViewDelegate: NSObjectProtocol { /// 获取当前选中标题下标值 @objc optional func pagingTitleView(titleView: SGPagingTitleView, index: Int) } public class SGPagingTitleView: UIView { @objc public init(frame: CGRect, titles:[String], configure: SGPagingTitleViewConfigure) { super.init(frame: frame) backgroundColor = UIColor.white.withAlphaComponent(0.77) assert(!titles.isEmpty, "SGPagingTitleView 初始化方法中的配置信息必须设置") self.titles = titles self.configure = configure initialization() addSubviews() } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } /// SGPagingTitleView 的代理 @objc public weak var delegate: SGPagingTitleViewDelegate? /// 选中标题的下标,默认为 0 @objc public var index: Int = 0 /// 重置选中标题的下标 @objc public func reset(index: Int) { btn_action(button: tempBtns[index]) } // MARK: 私有属性 private var titles = [String]() private var configure: SGPagingTitleViewConfigure! private var allBtnTextWidth: CGFloat = 0.0 private var allBtnWidth: CGFloat = 0.0 private var tempBtns = [SGPagingTitleButton]() private var tempBtn: UIButton? private var separators = [UIView]() private var previousIndexValue: Int? private var signBtnIndex: Int = 0 private var signBtnClick: Bool = false /// 开始颜色, 取值范围 0~1 private var startR: CGFloat = 0.0 private var startG: CGFloat = 0.0 private var startB: CGFloat = 0.0 /// 完成颜色, 取值范围 0~1 private var endR: CGFloat = 0.0 private var endG: CGFloat = 0.0 private var endB: CGFloat = 0.0 private lazy var scrollView: UIScrollView = { let tempScrollView = UIScrollView() tempScrollView.showsVerticalScrollIndicator = false tempScrollView.showsHorizontalScrollIndicator = false tempScrollView.alwaysBounceHorizontal = true tempScrollView.frame = bounds return tempScrollView }() private lazy var bottomSeparator: UIView = { let tempBottomSeparator = UIView() tempBottomSeparator.backgroundColor = configure.bottomSeparatorColor let w: CGFloat = frame.size.width let h: CGFloat = 0.5 let y: CGFloat = frame.size.height - h tempBottomSeparator.frame = CGRect(x: 0, y: y, width: w, height: h) return tempBottomSeparator }() private lazy var indicator: UIView = { let tempIndicator = UIView() tempIndicator.backgroundColor = configure.indicatorColor P_layoutIndicator(tempIndicator: tempIndicator) return tempIndicator }() public override func layoutSubviews() { super.layoutSubviews() btn_action(button: tempBtns[index]) } } // MARK: 外部方法 public extension SGPagingTitleView { /// 根据 SGPagingContentView 子视图的滚动而去修改标题选中样式 @objc func setPagingTitleView(progress: CGFloat, currentIndex: Int, targetIndex: Int) { p_setPagingTitleView(progress: progress, currentIndex: currentIndex, targetIndex: targetIndex) } /// 根据标题下标值重置标题文字 @objc func resetTitle(text: String, index: Int) { p_resetTitle(text: text, index: index) } /// 根据标题下标值设置标题的 attributed 属性 @objc func setTitle(attributed: NSAttributedString, selectedAttributed: NSAttributedString, index: Int) { p_setTitle(attributed: attributed, selectedAttributed: selectedAttributed, index: index) } /// 重置指示器颜色 @objc func resetIndicator(color: UIColor) { p_resetIndicator(color: color) } /// 重置标题颜色(color:普通状态下标题颜色、selectedColor:选中状态下标题颜色) @objc func resetTitle(color: UIColor, selectedColor: UIColor) { p_resetTitle(color: color, selectedColor: selectedColor) } /// 根据标题下标值添加对应的 badge @objc func addBadge(index: Int) { p_addBadge(index: index) } /// 根据标题下标值添加对应的 badge 及其文字 @objc func addBadge(text: String, index: Int) { p_addBadge(text: text, index: index) } /// 根据标题下标值移除对应的 badge @objc func removeBadge(index: Int) { p_removeBadge(index: index) } /// 设置标题图片及相对文字的位置(支持本地和网络图片) @objc func setImage(names: Array<String>, location: ImageLocation, spacing: CGFloat) { p_setImage(names: names, location: location, spacing: spacing) } /// 根据标题下标值设置标题图片及相对文字的位置(支持本地和网络图片) @objc func setImage(name: String, location: ImageLocation, spacing: CGFloat, index: Int) { p_setImage(name: name, location: location, spacing: spacing, index: index) } /// 根据标题下标值设置标题背景图片(支持本地和网络图片) @objc func setBackgroundImage(name: String, selectedName: String?, index: Int) { P_setBackgroundImage(name: name, selectedName: selectedName, index: index) } } // MARK: 修改指示器颜色、标题颜色、标题文字相关方法 private extension SGPagingTitleView { /// 根据标题下标值重置标题文字 func p_resetTitle(text: String, index: Int) { let btn: UIButton = tempBtns[index] btn.setTitle(text, for: .normal) if configure.showIndicator && signBtnIndex == index { if configure.indicatorType == .Default || configure.indicatorType == .Cover { var indicatorWidth = P_calculateWidth(string: text, font: configure.font) + configure.indicatorAdditionalWidth if indicatorWidth > btn.frame.size.width { indicatorWidth = btn.frame.size.width } indicator.frame.size.width = indicatorWidth indicator.center.x = btn.center.x } } } /// 根据标题下标值设置标题的 attributed 属性 func p_setTitle(attributed: NSAttributedString, selectedAttributed: NSAttributedString, index: Int) { let btn: UIButton = tempBtns[index] btn.titleLabel?.lineBreakMode = .byCharWrapping btn.titleLabel?.textAlignment = .center btn.setAttributedTitle(attributed, for: .normal) btn.setAttributedTitle(selectedAttributed, for: .selected) } /// 重置指示器颜色 func p_resetIndicator(color: UIColor) { indicator.backgroundColor = color } /// 重置标题颜色(color:普通状态下标题颜色、selectedColor:选中状态下标题颜色) func p_resetTitle(color: UIColor, selectedColor: UIColor) { for (_, btn) in tempBtns.enumerated() { btn.setTitleColor(color, for: .normal) btn.setTitleColor(selectedColor, for: .selected) } if configure.gradientEffect { configure.color = color configure.selectedColor = selectedColor P_startColor(color: configure.color) P_endColor(color: configure.selectedColor) } } } // MARK: 设置标题图片相关方法 private extension SGPagingTitleView { /// Set title image /// /// Support local and network images /// /// - parameter names: Title images name /// - parameter location: Position of image relative to text /// - parameter spacing: Space between image and text func p_setImage(names: Array<String>, location: ImageLocation, spacing: CGFloat) { if tempBtns.count == 0 { return } if names.count < tempBtns.count { for (index, btn) in tempBtns.enumerated() { if index >= names.count { return } setImage(btn: btn, imageName: names[index], location: location, spacing: spacing) } } else { for (index, btn) in tempBtns.enumerated() { setImage(btn: btn, imageName: names[index], location: location, spacing: spacing) } } } /// Set the title image according to the subscript /// /// Support local and network images /// /// - parameter names: Title image name /// - parameter location: Position of image relative to text /// - parameter spacing: Space between image and text /// - parameter index: Title subscript func p_setImage(name: String, location: ImageLocation, spacing: CGFloat, index: Int) { if tempBtns.count == 0 { return } let btn = tempBtns[index] setImage(btn: btn, imageName: name, location: location, spacing: spacing) } /// 设置标题背景图片 func P_setBackgroundImage(name: String, selectedName: String?, index: Int) { let btn: UIButton = tempBtns[index] btn.setTitleColor(.clear, for: .normal) btn.setTitleColor(.clear, for: .selected) if name.hasPrefix("http") { loadImage(urlString: name) { (image) in btn.setBackgroundImage(image, for: .normal) } } else { btn.setBackgroundImage(UIImage.init(named: name), for: .normal) } if let tempSelectedName = selectedName { if tempSelectedName.hasPrefix("http") { loadImage(urlString: tempSelectedName) { (image) in btn.setBackgroundImage(image, for: .selected) } } else { btn.setBackgroundImage(UIImage.init(named: tempSelectedName), for: .selected) } } } } // MARK:添加、移除 Badge 相关方法 private extension SGPagingTitleView { /// 根据标题下标添加对应的 badge func p_addBadge(index: Int) { DispatchQueue.main.asyncAfter(deadline: .now() + 0.02) { let btn: UIButton = self.tempBtns[index] let btnTextWidth: CGFloat = self.P_calculateWidth(string: btn.currentTitle!, font: self.configure.font) let btnTextHeight: CGFloat = self.P_calculateHeight(string: btn.currentTitle!, font: self.configure.font) let badgeX: CGFloat = 0.5 * (btn.frame.size.width - btnTextWidth) + btnTextWidth + self.configure.badgeOff.x let badgeY: CGFloat = 0.5 * (btn.frame.size.height - btnTextHeight) + self.configure.badgeOff.y - self.configure.badgeHeight let badgeW: CGFloat = self.configure.badgeHeight let badgeH: CGFloat = badgeW let badge: UILabel = UILabel() badge.frame = CGRect.init(x: badgeX, y: badgeY, width: badgeW, height: badgeH) badge.layer.backgroundColor = self.configure.badgeColor.cgColor badge.layer.cornerRadius = 0.5 * self.configure.badgeHeight btn.addSubview(badge) } } /// 根据标题下标添加对应的 badge 及其文字 func p_addBadge(text: String, index: Int) { DispatchQueue.main.asyncAfter(deadline: .now() + 0.02) { let btn: UIButton = self.tempBtns[index] let btnTextWidth: CGFloat = self.P_calculateWidth(string: btn.currentTitle!, font: self.configure.font) let btnTextHeight: CGFloat = self.P_calculateHeight(string: btn.currentTitle!, font: self.configure.font) let badgeX: CGFloat = 0.5 * (btn.frame.size.width - btnTextWidth) + btnTextWidth + self.configure.badgeOff.x let badgeY: CGFloat = 0.5 * (btn.frame.size.height - btnTextHeight) + self.configure.badgeOff.y - self.configure.badgeHeight let badgeW: CGFloat = self.P_calculateWidth(string: text, font: self.configure.badgeTextFont) + self.configure.badgeAdditionalWidth let badgeH: CGFloat = self.configure.badgeHeight let badge: UILabel = UILabel() badge.frame = CGRect.init(x: badgeX, y: badgeY, width: badgeW, height: badgeH) badge.text = text badge.textColor = self.configure.badgeTextColor badge.font = self.configure.badgeTextFont badge.textAlignment = .center badge.layer.backgroundColor = self.configure.badgeColor.cgColor badge.layer.cornerRadius = self.configure.badgeCornerRadius badge.layer.borderWidth = self.configure.badgeBorderWidth badge.layer.borderColor = self.configure.badgeBorderColor.cgColor btn.addSubview(badge) } } /// 根据标题下标移除对应的 badge func p_removeBadge(index: Int) { let btn: UIButton = tempBtns[index] for (_, subView) in btn.subviews.enumerated() { if subView.isMember(of: UILabel.self) { subView.removeFromSuperview() } } } } // MARK: 用于修改标题选中样式 private extension SGPagingTitleView { /// 修改标题选中样式 func p_setPagingTitleView(progress: CGFloat, currentIndex: Int, targetIndex: Int) { let currentBtn = tempBtns[currentIndex] let targetBtn = tempBtns[targetIndex] signBtnIndex = targetBtn.tag /// 1、标题选中居中处理 if allBtnWidth > frame.size.width { if signBtnClick == false { selectedBtnCenter(btn: targetBtn) } signBtnClick = false } /// 2、处理指示器的逻辑 if configure.showIndicator { // 指示器存在逻辑处理 if allBtnWidth <= frame.size.width { // 固定样式处理 if configure.equivalence { // 均分样式 if configure.indicatorScrollStyle == .Default { equivalenceIndicatorScrollDefaull(progress: progress, currentBtn: currentBtn, targetBtn: targetBtn) } else { equivalenceIndicatorScrollHalfEnd(progress: progress, currentBtn: currentBtn, targetBtn: targetBtn) } } else { if configure.indicatorScrollStyle == .Default { indicatorScrollDefaull(progress: progress, currentBtn: currentBtn, targetBtn: targetBtn) } else { indicatorScrollHalfEnd(progress: progress, currentBtn: currentBtn, targetBtn: targetBtn) } } } else { // 滚动样式处理 if configure.indicatorScrollStyle == .Default { indicatorScrollDefaull(progress: progress, currentBtn: currentBtn, targetBtn: targetBtn) } else { indicatorScrollHalfEnd(progress: progress, currentBtn: currentBtn, targetBtn: targetBtn) } } } else { // 指示器不存在逻辑处理 if configure.indicatorScrollStyle == .Half { noIndicatorScrollHalf(progress: progress, currentBtn: currentBtn, targetBtn: targetBtn) } else { noIndicatorScroll(progress: progress, currentBtn: currentBtn, targetBtn: targetBtn) } } /// 3、颜色的渐变(复杂) if configure.gradientEffect { gradientEffect(progress: progress, currentBtn: currentBtn, targetBtn: targetBtn) } /// 4、标题文字缩放属性(开启文字选中字号属性将不起作用) let selectedFont: UIFont = configure.selectedFont let defaultFont: UIFont = .systemFont(ofSize: 15) let selectedFontName: String = selectedFont.fontName let selectedFontPointSize: CGFloat = selectedFont.pointSize let defaultFontName: String = defaultFont.fontName let defaultFontPointSize: CGFloat = defaultFont.pointSize if selectedFontName == defaultFontName && selectedFontPointSize == defaultFontPointSize { if configure.textZoom { let currentBtnZoomRatio: CGFloat = (1 - progress) * configure.textZoomRatio currentBtn.transform = CGAffineTransform(scaleX: currentBtnZoomRatio + 1, y: currentBtnZoomRatio + 1) let targetBtnZoomRatio: CGFloat = progress * configure.textZoomRatio targetBtn.transform = CGAffineTransform(scaleX: targetBtnZoomRatio + 1, y: targetBtnZoomRatio + 1) } } } /// 有指示器:固定样式下:均分布局默认滚动样式 private func equivalenceIndicatorScrollDefaull(progress: CGFloat, currentBtn: UIButton, targetBtn: UIButton) { if progress >= 0.8 { // 此处取 >= 0.8 而不是 1.0 为的是防止用户滚动过快而按钮的选中状态并没有改变 changeSelectedBtn(btn: targetBtn) } let btnWidth: CGFloat = frame.size.width / CGFloat(titles.count) // Fixed 样式处理 if configure.indicatorType == .Fixed { let targetBtnCenterX: CGFloat = targetBtn.center.x let currentBtnCenterX: CGFloat = currentBtn.center.x let totalOffsetCenterX: CGFloat = targetBtnCenterX - currentBtnCenterX indicator.center.x = currentBtnCenterX + progress * totalOffsetCenterX return } // Dynamic 样式处理 if configure.indicatorType == .Dynamic { let currentBtnTag = currentBtn.tag let targetBtnTag = targetBtn.tag let targetBtnMaxX = CGFloat(targetBtn.tag + 1) * btnWidth let currentBtnMaxX = CGFloat(currentBtn.tag + 1) * btnWidth if currentBtnTag <= targetBtnTag { // 往左滑 if progress <= 0.5 { indicator.frame.size.width = configure.indicatorDynamicWidth + 2 * progress * btnWidth } else { let targetBtnIndicatorX: CGFloat = targetBtnMaxX - 0.5 * (btnWidth - configure.indicatorDynamicWidth) - configure.indicatorDynamicWidth indicator.frame.origin.x = targetBtnIndicatorX + 2 * (progress - 1) * btnWidth indicator.frame.size.width = configure.indicatorDynamicWidth + 2 * (1 - progress) * btnWidth } } else { if progress <= 0.5 { let currentBtnIndicatorX: CGFloat = currentBtnMaxX - 0.5 * (btnWidth - configure.indicatorDynamicWidth) - configure.indicatorDynamicWidth indicator.frame.origin.x = currentBtnIndicatorX - 2 * progress * btnWidth indicator.frame.size.width = configure.indicatorDynamicWidth + 2 * progress * btnWidth } else { let targetBtnIndicatorX: CGFloat = targetBtnMaxX - configure.indicatorDynamicWidth - 0.5 * (btnWidth - configure.indicatorDynamicWidth) indicator.frame.origin.x = targetBtnIndicatorX // 这句代码必须写,防止滚动结束之后指示器位置存在偏差,这里的偏差是由于 progress >= 0.8 导致的 indicator.frame.size.width = configure.indicatorDynamicWidth + 2 * (1 - progress) * btnWidth } } return } // Default、Cover 样式处理 // 文字宽度 let targetBtnTextWidth: CGFloat = P_calculateWidth(string: targetBtn.currentTitle!, font: configure.font) let currentBtnTextWidth: CGFloat = P_calculateWidth(string: currentBtn.currentTitle!, font: configure.font) let targetBtnMaxX: CGFloat = CGFloat(targetBtn.tag + 1) * btnWidth let currentBtnMaxX: CGFloat = CGFloat(currentBtn.tag + 1) * btnWidth let targetIndicatorX: CGFloat = targetBtnMaxX - targetBtnTextWidth - 0.5 * (btnWidth - targetBtnTextWidth + configure.indicatorAdditionalWidth) let currentIndicatorX: CGFloat = currentBtnMaxX - currentBtnTextWidth - 0.5 * (btnWidth - currentBtnTextWidth + configure.indicatorAdditionalWidth) let totalOffsetX: CGFloat = targetIndicatorX - currentIndicatorX /// 2、计算文字之间差值 // targetBtn 文字右边的 x 值 let targetBtnRightTextX: CGFloat = targetBtnMaxX - 0.5 * (btnWidth - targetBtnTextWidth) // originalBtn 文字右边的 x 值 let currentBtnRightTextX: CGFloat = currentBtnMaxX - 0.5 * (btnWidth - currentBtnTextWidth) let totalRightTextDistance: CGFloat = targetBtnRightTextX - currentBtnRightTextX // 计算 indicatorView 滚动时 x 的偏移量 let offsetX: CGFloat = totalOffsetX * progress // 计算 indicatorView 滚动时文字宽度的偏移量 let distance: CGFloat = progress * (totalRightTextDistance - totalOffsetX) /// 3、计算 indicatorView 新的 frame indicator.frame.origin.x = currentIndicatorX + offsetX let indicatorWidth: CGFloat = configure.indicatorAdditionalWidth + currentBtnTextWidth + distance if indicatorWidth >= targetBtn.frame.size.width { let moveTotalX: CGFloat = targetBtn.frame.origin.x - currentBtn.frame.origin.x let moveX: CGFloat = moveTotalX * progress indicator.center.x = currentBtn.center.x + moveX } else { indicator.frame.size.width = indicatorWidth } } /// 有指示器:固定样式下:均分布局 Half、End 滚动样式 private func equivalenceIndicatorScrollHalfEnd(progress: CGFloat, currentBtn: UIButton, targetBtn: UIButton) { let btnWidth: CGFloat = frame.size.width / CGFloat(titles.count) /// 1、处理 indicatorScrollStyle 的 Half 逻辑 if configure.indicatorScrollStyle == .Half { // 1.1、处理 Fixed 样式 if configure.indicatorType == .Fixed { if progress >= 0.5 { UIView.animate(withDuration: configure.indicatorAnimationTime) { self.indicator.center.x = targetBtn.center.x self.changeSelectedBtn(btn: targetBtn) } } else { UIView.animate(withDuration: configure.indicatorAnimationTime) { self.indicator.center.x = currentBtn.center.x self.changeSelectedBtn(btn: currentBtn) } } return } // 1.2、处理 Dynamic 样式 if configure.indicatorType == .Dynamic { let currentBtnTag = currentBtn.tag let targetBtnTag = targetBtn.tag let targetBtnMaxX: CGFloat = CGFloat(targetBtn.tag + 1) * btnWidth let currentBtnMaxX: CGFloat = CGFloat(currentBtn.tag + 1) * btnWidth if currentBtnTag <= targetBtnTag { // 往左滑 if progress <= 0.5 { indicator.frame.size.width = configure.indicatorDynamicWidth + 2 * progress * btnWidth changeSelectedBtn(btn: currentBtn) } else { let targetBtnIndicatorX: CGFloat = targetBtnMaxX - 0.5 * (btnWidth - configure.indicatorDynamicWidth) - configure.indicatorDynamicWidth indicator.frame.origin.x = targetBtnIndicatorX + 2 * (progress - 1) * btnWidth indicator.frame.size.width = configure.indicatorDynamicWidth + 2 * (1 - progress) * btnWidth changeSelectedBtn(btn: targetBtn) } } else { if progress <= 0.5 { let currentBtnIndicatorX: CGFloat = currentBtnMaxX - 0.5 * (btnWidth - configure.indicatorDynamicWidth) - configure.indicatorDynamicWidth indicator.frame.origin.x = currentBtnIndicatorX - 2 * progress * btnWidth indicator.frame.size.width = configure.indicatorDynamicWidth + 2 * progress * btnWidth changeSelectedBtn(btn: currentBtn) } else { let targetBtnIndicatorX: CGFloat = targetBtnMaxX - configure.indicatorDynamicWidth - 0.5 * (btnWidth - configure.indicatorDynamicWidth) indicator.frame.origin.x = targetBtnIndicatorX // 这句代码必须写,防止滚动结束之后指示器位置存在偏差,这里的偏差是由于 progress >= 0.8 导致的 indicator.frame.size.width = configure.indicatorDynamicWidth + 2 * (1 - progress) * btnWidth changeSelectedBtn(btn: targetBtn) } } return } // 1.3、处理指示器 Default、Cover 样式 if progress >= 0.5 { let indicatorWidth = P_calculateWidth(string: targetBtn.currentTitle!, font: configure.font) + configure.indicatorAdditionalWidth UIView.animate(withDuration: configure.indicatorAnimationTime) { [self] in if indicatorWidth >= targetBtn.frame.size.width { self.indicator.frame.size.width = targetBtn.frame.size.width } else { self.indicator.frame.size.width = indicatorWidth } self.indicator.center.x = targetBtn.center.x self.changeSelectedBtn(btn: targetBtn) } } else { let indicatorWidth = P_calculateWidth(string: currentBtn.currentTitle!, font: configure.font) + configure.indicatorAdditionalWidth UIView.animate(withDuration: configure.indicatorAnimationTime) { if indicatorWidth >= currentBtn.frame.size.width { self.indicator.frame.size.width = currentBtn.frame.size.width } else { self.indicator.frame.size.width = indicatorWidth } self.indicator.center.x = currentBtn.center.x self.changeSelectedBtn(btn: currentBtn) } } return } /// 2、处理 indicatorScrollStyle 的 End 逻辑 // 1、处理 Fixed 样式 if configure.indicatorType == .Fixed { if (progress == 1.0) { UIView.animate(withDuration: configure.indicatorAnimationTime) { self.indicator.center.x = targetBtn.center.x self.changeSelectedBtn(btn: targetBtn) } } else { UIView.animate(withDuration: configure.indicatorAnimationTime) { self.indicator.center.x = currentBtn.center.x self.changeSelectedBtn(btn: currentBtn) } } return } // 1.2、处理 Dynamic 样式 if configure.indicatorType == .Dynamic { let currentBtnTag = currentBtn.tag let targetBtnTag = targetBtn.tag let targetBtnMaxX: CGFloat = CGFloat(targetBtn.tag + 1) * btnWidth let currentBtnMaxX: CGFloat = CGFloat(currentBtn.tag + 1) * btnWidth if currentBtnTag <= targetBtnTag { // 往左滑 if progress <= 0.5 { indicator.frame.size.width = configure.indicatorDynamicWidth + 2 * progress * btnWidth if progress < 0.8 { changeSelectedBtn(btn: currentBtn) } } else { let targetBtnIndicatorX: CGFloat = targetBtnMaxX - 0.5 * (btnWidth - configure.indicatorDynamicWidth) - configure.indicatorDynamicWidth indicator.frame.origin.x = targetBtnIndicatorX + 2 * (progress - 1) * btnWidth indicator.frame.size.width = configure.indicatorDynamicWidth + 2 * (1 - progress) * btnWidth if progress >= 0.8 { changeSelectedBtn(btn: targetBtn) } } } else { if progress <= 0.5 { let currentBtnIndicatorX: CGFloat = currentBtnMaxX - 0.5 * (btnWidth - configure.indicatorDynamicWidth) - configure.indicatorDynamicWidth indicator.frame.origin.x = currentBtnIndicatorX - 2 * progress * btnWidth indicator.frame.size.width = configure.indicatorDynamicWidth + 2 * progress * btnWidth if progress < 0.8 { changeSelectedBtn(btn: currentBtn) } } else { let targetBtnIndicatorX: CGFloat = targetBtnMaxX - configure.indicatorDynamicWidth - 0.5 * (btnWidth - configure.indicatorDynamicWidth) indicator.frame.origin.x = targetBtnIndicatorX // 这句代码必须写,防止滚动结束之后指示器位置存在偏差,这里的偏差是由于 progress >= 0.8 导致的 indicator.frame.size.width = configure.indicatorDynamicWidth + 2 * (1 - progress) * btnWidth if progress >= 0.8 { changeSelectedBtn(btn: targetBtn) } } } return } // 3、处理指示器 Default、Cover 样式 if progress == 1.0 { let indicatorWidth = P_calculateWidth(string: targetBtn.currentTitle!, font: configure.font) + configure.indicatorAdditionalWidth UIView.animate(withDuration: configure.indicatorAnimationTime) { [self] in if indicatorWidth >= targetBtn.frame.size.width { self.indicator.frame.size.width = targetBtn.frame.size.width } else { self.indicator.frame.size.width = indicatorWidth } self.indicator.center.x = targetBtn.center.x self.changeSelectedBtn(btn: targetBtn) } } else { let indicatorWidth = P_calculateWidth(string: currentBtn.currentTitle!, font: configure.font) + configure.indicatorAdditionalWidth UIView.animate(withDuration: configure.indicatorAnimationTime) { if indicatorWidth >= currentBtn.frame.size.width { self.indicator.frame.size.width = currentBtn.frame.size.width } else { self.indicator.frame.size.width = indicatorWidth } self.indicator.center.x = currentBtn.center.x self.changeSelectedBtn(btn: currentBtn) } } } /// 有指示器:从左到右自动布局:默认滚动样式 private func indicatorScrollDefaull(progress: CGFloat, currentBtn: UIButton, targetBtn: UIButton) { // 改变按钮的选择状态 if (progress >= 0.8) { changeSelectedBtn(btn: targetBtn) } // 处理 Fixed 样式 if configure.indicatorType == .Fixed { let targetIndicatorX: CGFloat = targetBtn.frame.maxX - 0.5 * (targetBtn.frame.size.width - configure.indicatorFixedWidth) - configure.indicatorFixedWidth let currentIndicatorX: CGFloat = currentBtn.frame.maxX - configure.indicatorFixedWidth - 0.5 * (currentBtn.frame.size.width - configure.indicatorFixedWidth) let totalOffsetX: CGFloat = targetIndicatorX - currentIndicatorX let offsetX: CGFloat = totalOffsetX * progress indicator.frame.origin.x = currentIndicatorX + offsetX return } // 处理 Dynamic 样式 if configure.indicatorType == .Dynamic { let currentBtnTag = currentBtn.tag let targetBtnTag = targetBtn.tag if currentBtnTag <= targetBtnTag { // 往左滑 // targetBtn 与 currentBtn 中心点之间的距离 let btnCenterXDistance: CGFloat = targetBtn.center.x - currentBtn.center.x if progress <= 0.5 { indicator.frame.size.width = 2 * progress * btnCenterXDistance + configure.indicatorDynamicWidth } else { let targetBtnX: CGFloat = targetBtn.frame.maxX - configure.indicatorDynamicWidth - 0.5 * (targetBtn.frame.size.width - configure.indicatorDynamicWidth) indicator.frame.origin.x = targetBtnX + 2 * (progress - 1) * btnCenterXDistance indicator.frame.size.width = 2 * (1 - progress) * btnCenterXDistance + configure.indicatorDynamicWidth } } else { // currentBtn 与 targetBtn 中心点之间的距离 let btnCenterXDistance: CGFloat = currentBtn.center.x - targetBtn.center.x if progress <= 0.5 { let currentBtnX: CGFloat = currentBtn.frame.maxX - configure.indicatorDynamicWidth - 0.5 * (currentBtn.frame.size.width - configure.indicatorDynamicWidth) indicator.frame.origin.x = currentBtnX - 2 * progress * btnCenterXDistance indicator.frame.size.width = 2 * progress * btnCenterXDistance + configure.indicatorDynamicWidth } else { let targetBtnX: CGFloat = targetBtn.frame.maxX - configure.indicatorDynamicWidth - 0.5 * (targetBtn.frame.size.width - configure.indicatorDynamicWidth) indicator.frame.origin.x = targetBtnX // 这句代码必须写,防止滚动结束之后指示器位置存在偏差,这里的偏差是由于 progress >= 0.8 导致的 indicator.frame.size.width = 2 * (1 - progress) * btnCenterXDistance + configure.indicatorDynamicWidth } } return } // 处理指示器 Default、Cover 样式 if configure.textZoom { let currentBtnTextWidth: CGFloat = P_calculateWidth(string: currentBtn.currentTitle!, font: configure.font) let targetBtnTextWidth: CGFloat = P_calculateWidth(string: targetBtn.currentTitle!, font: configure.font) // 文字距离差 let diffText: CGFloat = targetBtnTextWidth - currentBtnTextWidth // 中心点距离差 let distanceCenter: CGFloat = targetBtn.center.x - currentBtn.center.x let offsetCenterX: CGFloat = distanceCenter * progress let indicatorWidth: CGFloat = configure.indicatorAdditionalWidth + targetBtnTextWidth if indicatorWidth >= targetBtn.frame.size.width { indicator.frame.size.width = targetBtn.frame.size.width } else { let tempIndicatorWidth: CGFloat = currentBtnTextWidth + diffText * progress indicator.frame.size.width = tempIndicatorWidth + configure.indicatorAdditionalWidth } indicator.center.x = currentBtn.center.x + offsetCenterX return } // 1、计算 targetBtn 与 currentBtn 之间的 x 差值 let totalOffsetX: CGFloat = targetBtn.frame.origin.x - currentBtn.frame.origin.x // 2、计算 targetBtn 与 currentBtn 之间距离的差值 let totalDistance: CGFloat = targetBtn.frame.maxX - currentBtn.frame.maxX /// 计算 indicator 滚动时 x 的偏移量 var offsetX: CGFloat = 0.0 /// 计算 indicator 滚动时宽度的偏移量 var distance: CGFloat = 0.0 let targetBtnTextWidth: CGFloat = P_calculateWidth(string: targetBtn.currentTitle!, font: configure.font) let indicatorWidth: CGFloat = configure.indicatorAdditionalWidth + targetBtnTextWidth if indicatorWidth >= targetBtn.frame.size.width { offsetX = totalOffsetX * progress distance = progress * (totalDistance - totalOffsetX) indicator.frame.origin.x = currentBtn.frame.origin.x + offsetX indicator.frame.size.width = currentBtn.frame.size.width + distance } else { offsetX = totalOffsetX * progress + 0.5 * configure.additionalWidth - 0.5 * configure.indicatorAdditionalWidth distance = progress * (totalDistance - totalOffsetX) - configure.additionalWidth /// 计算 indicator 新的 frame indicator.frame.origin.x = currentBtn.frame.origin.x + offsetX indicator.frame.size.width = currentBtn.frame.size.width + distance + configure.indicatorAdditionalWidth } } /// 有指示器:从左到右自动布局:Half、End 滚动样式 private func indicatorScrollHalfEnd(progress: CGFloat, currentBtn: UIButton, targetBtn: UIButton) { // 1、处理 indicatorScrollStyle 的 Half 逻辑 if configure.indicatorScrollStyle == .Half { // 1.1、处理 Fixed 样式 if configure.indicatorType == .Fixed { if progress >= 0.5 { UIView.animate(withDuration: configure.indicatorAnimationTime) { self.indicator.center.x = targetBtn.center.x self.changeSelectedBtn(btn: targetBtn) } } else { UIView.animate(withDuration: configure.indicatorAnimationTime) { self.indicator.center.x = currentBtn.center.x self.changeSelectedBtn(btn: currentBtn) } } return } // 1.2、处理 Dynamic 样式 if configure.indicatorType == .Dynamic { let currentBtnTag = currentBtn.tag let targetBtnTag = targetBtn.tag if currentBtnTag <= targetBtnTag { // 往左滑 // targetBtn 与 currentBtn 中心点之间的距离 let btnCenterXDistance: CGFloat = targetBtn.center.x - currentBtn.center.x if progress <= 0.5 { indicator.frame.size.width = 2 * progress * btnCenterXDistance + configure.indicatorDynamicWidth changeSelectedBtn(btn: currentBtn) } else { let targetBtnX: CGFloat = targetBtn.frame.maxX - configure.indicatorDynamicWidth - 0.5 * (targetBtn.frame.size.width - configure.indicatorDynamicWidth) indicator.frame.origin.x = targetBtnX + 2 * (progress - 1) * btnCenterXDistance indicator.frame.size.width = 2 * (1 - progress) * btnCenterXDistance + configure.indicatorDynamicWidth changeSelectedBtn(btn: targetBtn) } } else { // currentBtn 与 targetBtn 中心点之间的距离 let btnCenterXDistance: CGFloat = currentBtn.center.x - targetBtn.center.x if progress <= 0.5 { let currentBtnX: CGFloat = currentBtn.frame.maxX - configure.indicatorDynamicWidth - 0.5 * (currentBtn.frame.size.width - configure.indicatorDynamicWidth) indicator.frame.origin.x = currentBtnX - 2 * progress * btnCenterXDistance indicator.frame.size.width = 2 * progress * btnCenterXDistance + configure.indicatorDynamicWidth changeSelectedBtn(btn: currentBtn) } else { let targetBtnX: CGFloat = targetBtn.frame.maxX - configure.indicatorDynamicWidth - 0.5 * (targetBtn.frame.size.width - configure.indicatorDynamicWidth) indicator.frame.origin.x = targetBtnX // 这句代码必须写,防止滚动结束之后指示器位置存在偏差,这里的偏差是由于 progress >= 0.8 导致的 indicator.frame.size.width = 2 * (1 - progress) * btnCenterXDistance + configure.indicatorDynamicWidth changeSelectedBtn(btn: targetBtn) } } return } // 1.3、处理指示器 Default、Cover 样式 if progress >= 0.5 { let indicatorWidth = P_calculateWidth(string: targetBtn.currentTitle!, font: configure.font) + configure.indicatorAdditionalWidth UIView.animate(withDuration: configure.indicatorAnimationTime) { [self] in if indicatorWidth >= targetBtn.frame.size.width { self.indicator.frame.size.width = targetBtn.frame.size.width } else { self.indicator.frame.size.width = indicatorWidth } self.indicator.center.x = targetBtn.center.x self.changeSelectedBtn(btn: targetBtn) } } else { let indicatorWidth = P_calculateWidth(string: currentBtn.currentTitle!, font: configure.font) + configure.indicatorAdditionalWidth UIView.animate(withDuration: configure.indicatorAnimationTime) { if indicatorWidth >= currentBtn.frame.size.width { self.indicator.frame.size.width = currentBtn.frame.size.width } else { self.indicator.frame.size.width = indicatorWidth } self.indicator.center.x = currentBtn.center.x self.changeSelectedBtn(btn: currentBtn) } } return } // 2、处理 indicatorScrollStyleEnd 逻辑 // 1、处理 Fixed 样式 if configure.indicatorType == .Fixed { if (progress == 1.0) { UIView.animate(withDuration: configure.indicatorAnimationTime) { self.indicator.center.x = targetBtn.center.x self.changeSelectedBtn(btn: targetBtn) } } else { UIView.animate(withDuration: configure.indicatorAnimationTime) { self.indicator.center.x = currentBtn.center.x self.changeSelectedBtn(btn: currentBtn) } } return } // 2、处理 Dynamic 样式 if configure.indicatorType == .Dynamic { let currentBtnTag = currentBtn.tag let targetBtnTag = targetBtn.tag if currentBtnTag <= targetBtnTag { // 往左滑 // targetBtn 与 currentBtn 中心点之间的距离 let btnCenterXDistance: CGFloat = targetBtn.center.x - currentBtn.center.x if progress <= 0.5 { indicator.frame.size.width = 2 * progress * btnCenterXDistance + configure.indicatorDynamicWidth changeSelectedBtn(btn: currentBtn) } else { let targetBtnX: CGFloat = targetBtn.frame.maxX - configure.indicatorDynamicWidth - 0.5 * (targetBtn.frame.size.width - configure.indicatorDynamicWidth) indicator.frame.origin.x = targetBtnX + 2 * (progress - 1) * btnCenterXDistance indicator.frame.size.width = 2 * (1 - progress) * btnCenterXDistance + configure.indicatorDynamicWidth if progress >= 0.8 { changeSelectedBtn(btn: targetBtn) } } } else { // currentBtn 与 targetBtn 中心点之间的距离 let btnCenterXDistance: CGFloat = currentBtn.center.x - targetBtn.center.x if progress <= 0.5 { let currentBtnX: CGFloat = currentBtn.frame.maxX - configure.indicatorDynamicWidth - 0.5 * (currentBtn.frame.size.width - configure.indicatorDynamicWidth) indicator.frame.origin.x = currentBtnX - 2 * progress * btnCenterXDistance indicator.frame.size.width = 2 * progress * btnCenterXDistance + configure.indicatorDynamicWidth changeSelectedBtn(btn: currentBtn) } else { let targetBtnX: CGFloat = targetBtn.frame.maxX - configure.indicatorDynamicWidth - 0.5 * (targetBtn.frame.size.width - configure.indicatorDynamicWidth) indicator.frame.origin.x = targetBtnX // 这句代码必须写,防止滚动结束之后指示器位置存在偏差,这里的偏差是由于 progress >= 0.8 导致的 indicator.frame.size.width = 2 * (1 - progress) * btnCenterXDistance + configure.indicatorDynamicWidth if progress >= 0.8 { changeSelectedBtn(btn: targetBtn) } } } return } // 3、处理指示器 Default、Cover 样式 if progress == 1.0 { let indicatorWidth = P_calculateWidth(string: targetBtn.currentTitle!, font: configure.font) + configure.indicatorAdditionalWidth UIView.animate(withDuration: configure.indicatorAnimationTime) { [self] in if indicatorWidth >= targetBtn.frame.size.width { self.indicator.frame.size.width = targetBtn.frame.size.width } else { self.indicator.frame.size.width = indicatorWidth } self.indicator.center.x = targetBtn.center.x self.changeSelectedBtn(btn: targetBtn) } } else { let indicatorWidth = P_calculateWidth(string: currentBtn.currentTitle!, font: configure.font) + configure.indicatorAdditionalWidth UIView.animate(withDuration: configure.indicatorAnimationTime) { if indicatorWidth >= currentBtn.frame.size.width { self.indicator.frame.size.width = currentBtn.frame.size.width } else { self.indicator.frame.size.width = indicatorWidth } self.indicator.center.x = currentBtn.center.x self.changeSelectedBtn(btn: currentBtn) } } } /// 无指示器 private func noIndicatorScroll(progress: CGFloat, currentBtn: UIButton, targetBtn: UIButton) { if progress == 1.0 { UIView.animate(withDuration: configure.indicatorAnimationTime) { self.changeSelectedBtn(btn: targetBtn) } } else { UIView.animate(withDuration: configure.indicatorAnimationTime) { self.changeSelectedBtn(btn: currentBtn) } } } /// 无指示器:Half 滚动样式 private func noIndicatorScrollHalf(progress: CGFloat, currentBtn: UIButton, targetBtn: UIButton) { if progress >= 0.5 { UIView.animate(withDuration: configure.indicatorAnimationTime) { self.changeSelectedBtn(btn: targetBtn) } } else { UIView.animate(withDuration: configure.indicatorAnimationTime) { self.changeSelectedBtn(btn: currentBtn) } } } /// 颜色的渐变逻辑处理(复杂) private func gradientEffect(progress: CGFloat, currentBtn: UIButton, targetBtn: UIButton) { let targetProgress: CGFloat = progress let currentProgress: CGFloat = 1 - progress let r = endR - startR let g = endG - startG let b = endB - startB let currentColor: UIColor = UIColor.init(red: startR + r * currentProgress, green: startG + g * currentProgress, blue: startB + b * currentProgress, alpha: 1.0) let targetColor: UIColor = UIColor.init(red: startR + r * targetProgress, green: startG + g * targetProgress, blue: startB + b * targetProgress, alpha: 1.0) currentBtn.titleLabel?.textColor = currentColor targetBtn.titleLabel?.textColor = targetColor } } // MARK: initialization private extension SGPagingTitleView { func initialization() { if configure.textZoomRatio < 0.0 { configure.textZoomRatio = 0.0 } else if configure.textZoomRatio > 1.0 { configure.textZoomRatio = 1.0 } if configure.indicatorAnimationTime < 0.0 { configure.indicatorAnimationTime = 0.0 } else if configure.indicatorAnimationTime > 0.3 { configure.indicatorAnimationTime = 0.3 } } } // MARK: 添加内部子视图 private extension SGPagingTitleView { func addSubviews() { addSubview(scrollView) if configure.showBottomSeparator { addSubview(bottomSeparator) } addTitleBtns() if configure.showIndicator { if configure.indicatorLocation == .Default { scrollView.insertSubview(indicator, at: 0) } else { scrollView.addSubview(indicator) } } } func addTitleBtns() { let titleCount = titles.count titles.forEach { (title) in let titleWidth: CGFloat = P_calculateWidth(string: title, font: configure.font) allBtnTextWidth += titleWidth } allBtnWidth = allBtnTextWidth + configure.additionalWidth * CGFloat(titleCount) allBtnWidth = CGFloat(ceilf(Float(allBtnWidth))) for idx in 0..<titleCount { let btn = SGPagingTitleButton() btn.tag = idx btn.titleLabel?.font = configure.font btn.setTitle(titles[idx], for: .normal) btn.setTitleColor(configure.color, for: .normal) btn.setTitleColor(configure.selectedColor, for: .selected) btn.addTarget(self, action: #selector(btn_action(button:)), for: .touchUpInside) scrollView.addSubview(btn) tempBtns.append(btn) } // 添加按钮间分割线 if configure.showSeparator { for _ in 0..<(titleCount - 1) { let separator: UIView = UIView() separator.backgroundColor = configure.separatorColor scrollView.addSubview(separator) separators.append(separator) } } // 标题文字渐变效果下对标题文字默认、选中状态下颜色的记录 if configure.gradientEffect { P_startColor(color: configure.color) P_endColor(color: configure.selectedColor) } if allBtnWidth <= frame.size.width { let btnY: CGFloat = 0.0 let btnW: CGFloat = frame.size.width / CGFloat(titleCount) let btnH: CGFloat = frame.size.height if configure.equivalence { /// 固定样式下均分布局标题 for (index, btn) in tempBtns.enumerated() { let btnX = btnW * CGFloat(index) btn.frame = CGRect.init(x: btnX, y: btnY, width: btnW, height: btnH) } // 设置标题间分割线的 frame if configure.showSeparator { let separatorW: CGFloat = 1 var separatorH: CGFloat = frame.size.height - configure.separatorAdditionalReduceLength if separatorH < 0 { separatorH = frame.size.height } let separatorY: CGFloat = 0.5 * (frame.size.height - separatorH) for (idx, separator) in separators.enumerated() { let separatorX: CGFloat = btnW * CGFloat((idx + 1)) - 0.5 * separatorW separator.frame = CGRect.init(x: separatorX, y: separatorY, width: separatorW, height: separatorH) } } } else { /// 固定样式下从左到右布局标题 fromLeftToRightLayout() } if configure.bounce == false { scrollView.bounces = false } } else { fromLeftToRightLayout() if configure.bounces == false { scrollView.bounces = false } } } /// 从左到右布局标题 func fromLeftToRightLayout() { var btnX: CGFloat = 0.0 let btnY: CGFloat = 0.0 var btnW: CGFloat = 0.0 let btnH: CGFloat = frame.size.height for (_, btn) in tempBtns.enumerated() { btnW = P_calculateWidth(string: btn.currentTitle!, font: configure.font) + configure.additionalWidth btn.frame = CGRect.init(x: btnX, y: btnY, width: btnW, height: btnH) btnX = btnX + btnW } // 设置标题间分割线的 frame if configure.showSeparator { let separatorW: CGFloat = 1 var separatorH: CGFloat = frame.size.height - configure.separatorAdditionalReduceLength if separatorH < 0 { separatorH = frame.size.height } let separatorY: CGFloat = 0.5 * (frame.size.height - separatorH) for (idx, separator) in separators.enumerated() { let btn: UIButton = tempBtns[idx] let separatorX: CGFloat = btn.frame.maxX - 0.5 * separatorW separator.frame = CGRect.init(x: separatorX, y: separatorY, width: separatorW, height: separatorH) } } let lastBtn = tempBtns.last scrollView.contentSize = CGSize(width: (lastBtn?.frame.maxX)!, height: frame.size.height) } } // MARK: 标题按钮的点击事件 private extension SGPagingTitleView { @objc func btn_action(button: UIButton) { changeSelectedBtn(btn: button) if allBtnWidth > frame.size.width { signBtnClick = true selectedBtnCenter(btn: button) } if configure.showIndicator { changeIndicatorWithButton(btn: button) } if delegate != nil && (delegate?.responds(to: #selector(delegate?.pagingTitleView(titleView:index:))))! { delegate?.pagingTitleView!(titleView: self, index: button.tag) } signBtnIndex = button.tag } /// 改变选中按钮 func changeSelectedBtn(btn: UIButton) { if tempBtn == nil { btn.isSelected = true tempBtn = btn } else if tempBtn != nil && tempBtn == btn { btn.isSelected = true } else if tempBtn != nil && tempBtn != btn { tempBtn?.isSelected = false btn.isSelected = true tempBtn = btn } index = btn.tag let selectedFont: UIFont = configure.selectedFont let defaultFont: UIFont = .systemFont(ofSize: 15) let selectedFontName: String = selectedFont.fontName let selectedFontPointSize: CGFloat = selectedFont.pointSize let defaultFontName: String = defaultFont.fontName let defaultFontPointSize: CGFloat = defaultFont.pointSize if selectedFontName == defaultFontName && selectedFontPointSize == defaultFontPointSize { // 标题文字缩放属性(开启 selectedFont 属性将不起作用) if configure.textZoom { tempBtns.forEach { (EBtn) in EBtn.transform = .identity } // 1.记录按钮缩放前的宽度 let zoomFrontBtnWidth: CGFloat = btn.frame.size.width /// 处理按钮缩放 let afterZoomRatio: CGFloat = 1 + configure.textZoomRatio btn.transform = CGAffineTransform(scaleX: afterZoomRatio, y: afterZoomRatio) // 2.记录按钮缩放后的宽度 let zoomAfterBtnWidth: CGFloat = btn.frame.size.width // 缩放后与缩放前之间的差值 let diffForntAfter: CGFloat = zoomAfterBtnWidth - zoomFrontBtnWidth /// 处理指示器 if configure.indicatorAdditionalWidth >= diffForntAfter { configure.indicatorAdditionalWidth = diffForntAfter } if configure.indicatorType == .Fixed { var indicatorWidth = configure.indicatorFixedWidth if indicatorWidth > btn.frame.size.width { indicatorWidth = btn.frame.size.width } indicator.frame.size.width = configure.indicatorFixedWidth indicator.center.x = btn.center.x } else { let btnTextWidth = P_calculateWidth(string: btn.currentTitle!, font: configure.font) var indicatorWidth = btnTextWidth + configure.indicatorAdditionalWidth if indicatorWidth > btn.frame.size.width { indicatorWidth = btn.frame.size.width } indicator.frame.size.width = indicatorWidth indicator.center.x = btn.center.x } } // 此处作用:避免滚动过程中点击标题手指不离开屏幕的前提下再次滚动造成的误差(由于文字渐变效果导致未选中标题的不准确处理) if configure.gradientEffect { tempBtns.forEach { (EBtn) in EBtn.titleLabel?.textColor = configure.color } btn.titleLabel?.textColor = configure.selectedColor } } else { // 此处作用:避免滚动过程中点击标题手指不离开屏幕的前提下再次滚动造成的误差(由于文字渐变效果导致未选中标题的不准确处理) if configure.gradientEffect { tempBtns.forEach { (EBtn) in EBtn.titleLabel?.textColor = configure.color EBtn.titleLabel?.font = configure.font } btn.titleLabel?.textColor = configure.selectedColor btn.titleLabel?.font = configure.selectedFont } else { tempBtns.forEach { (EBtn) in EBtn.titleLabel?.font = configure.font } btn.titleLabel?.font = configure.selectedFont } } } /// 滚动样式下选中标题居中处理 func selectedBtnCenter(btn: UIButton) { var offsetX: CGFloat = btn.center.x - frame.size.width * 0.5 if offsetX < 0 { offsetX = 0 } let maxOffsetX: CGFloat = scrollView.contentSize.width - frame.size.width if offsetX > maxOffsetX { offsetX = maxOffsetX } scrollView.setContentOffset(CGPoint.init(x: offsetX, y: 0), animated: true) } /// 根据标题按钮选中的变化而去改变指示器 func changeIndicatorWithButton(btn: UIButton) { UIView.animate(withDuration: configure.indicatorAnimationTime) { if self.configure.indicatorType == .Fixed { self.indicator.frame.size.width = self.configure.indicatorFixedWidth self.indicator.center.x = btn.center.x return } if self.configure.indicatorType == .Dynamic { self.indicator.frame.size.width = self.configure.indicatorDynamicWidth self.indicator.center.x = btn.center.x return } if self.configure.textZoom == false { var indicatorWidth: CGFloat = self.P_calculateWidth(string: btn.currentTitle!, font: self.configure.font) + self.configure.indicatorAdditionalWidth if indicatorWidth > btn.frame.size.width { indicatorWidth = btn.frame.size.width } self.indicator.frame.size.width = indicatorWidth self.indicator.center.x = btn.center.x } } } } // MARK: Indicator 布局及相关属性处理 extension SGPagingTitleView { func P_layoutIndicator(tempIndicator: UIView) { if configure.indicatorType == .Cover { if configure.indicatorHeight >= frame.size.height { tempIndicator.frame.origin.y = 0 tempIndicator.frame.size.height = frame.size.height } else { tempIndicator.frame.origin.y = 0.5 * (frame.size.height - configure.indicatorHeight) tempIndicator.frame.size.height = configure.indicatorHeight } tempIndicator.layer.borderWidth = configure.indicatorBorderWidth tempIndicator.layer.borderColor = configure.indicatorBorderColor.cgColor } else { if configure.indicatorHeight >= frame.size.height { tempIndicator.frame.origin.y = 0 tempIndicator.frame.size.height = frame.size.height } else { tempIndicator.frame.origin.y = frame.size.height - configure.indicatorToBottomDistance - configure.indicatorHeight tempIndicator.frame.size.height = configure.indicatorHeight } } if configure.indicatorCornerRadius > 0.5 * tempIndicator.frame.size.height { tempIndicator.layer.cornerRadius = 0.5 * tempIndicator.frame.size.height } else { tempIndicator.layer.cornerRadius = configure.indicatorCornerRadius } } } // MARK: 内部公共方法抽取 private extension SGPagingTitleView { /// 计算字符串的宽度 func P_calculateWidth(string: String, font: UIFont) -> CGFloat { let attrs = [NSAttributedString.Key.font: font] let attrString = NSAttributedString(string: string, attributes: attrs) return attrString.boundingRect(with: CGSize(width: 0, height: 0), options: .usesLineFragmentOrigin, context: nil).size.width } /// 计算字符串的高 func P_calculateHeight(string: String, font: UIFont) -> CGFloat { let attrs = [NSAttributedString.Key.font: font] let attrString = NSAttributedString(string: string, attributes: attrs) return attrString.boundingRect(with: CGSize(width: 0, height: 0), options: .usesLineFragmentOrigin, context: nil).size.height } /// 开始颜色 func P_startColor(color: UIColor) { let components = P_getRGBComponents(color: color) startR = components[0] startG = components[1] startB = components[2] } /// 结束颜色 func P_endColor(color: UIColor) { let components = P_getRGBComponents(color: color) endR = components[0] endG = components[1] endB = components[2] } /// 颜色处理 func P_getRGBComponents(color: UIColor) -> [CGFloat] { let rgbColorSpace = CGColorSpaceCreateDeviceRGB() let data = UnsafeMutablePointer<CUnsignedChar>.allocate(capacity: 4) let context = CGContext(data: data, width: 1, height: 1, bitsPerComponent: 8, bytesPerRow: 4, space: rgbColorSpace, bitmapInfo: 1) context?.setFillColor(color.cgColor) context?.fill(CGRect.init(x: 0, y: 0, width: 1, height: 1)) var components:[CGFloat] = [] for i in 0..<3 { components.append(CGFloat(data[i])/255.0) } return components } } // MARK: - 内部标题图片相关方法 private extension SGPagingTitleView { func setImage(btn: UIButton, imageName: String, location: ImageLocation, spacing: CGFloat) { if imageName.hasPrefix("http") { loadImage(urlString: imageName) { (image) in btn.setImage(image, for: .normal) btn.setImage(location: location, space: spacing) } } else { btn.setImage(UIImage.init(named: imageName), for: .normal) btn.setImage(location: location, space: spacing) } } typealias LoadImageCompleteBlock = ((_ image: UIImage) -> ())? /// 加载网络图片 func loadImage(urlString: String, complete: LoadImageCompleteBlock) { let blockOperation = BlockOperation.init { let url = URL.init(string: urlString) guard let imageData = NSData(contentsOf: url!) else { return } let image = UIImage(data: imageData as Data) OperationQueue.main.addOperation { if complete != nil { complete!(image!) } } } OperationQueue().addOperation(blockOperation) } } private class SGPagingTitleButton: UIButton { override var isHighlighted: Bool { set {} get {return false} } }
mit
xwu/swift
test/Interop/Cxx/templates/swift-class-instantiation-in-namespace-module-interface.swift
5
911
// RUN: %empty-directory(%t) // RUN: %target-swiftxx-frontend -emit-module -o %t/SwiftClassTemplateInNamespaceModule.swiftmodule %S/Inputs/SwiftClassTemplateInNamespaceModule.swift -I %S/Inputs -enable-library-evolution -swift-version 5 // RUN: %target-swift-ide-test -print-module -module-to-print=SwiftClassTemplateInNamespaceModule -I %t/ -source-filename=x -enable-cxx-interop | %FileCheck %s // The following bug needs to be resolved so decls in __ObjC don't dissapear. // REQUIRES: SR-14211 // CHECK: import ClassTemplateInNamespaceForSwiftModule // CHECK: func receiveShip(_ i: inout Space.__CxxTemplateInstN5Space4ShipIbEE) // CHECK: func receiveShipWithEngine(_ i: inout Space.__CxxTemplateInstN5Space4ShipIN6Engine8TurbojetEEE) // CHECK: func returnShip() -> Space.__CxxTemplateInstN5Space4ShipIbEE // CHECK: func returnShipWithEngine() -> Space.__CxxTemplateInstN5Space4ShipIN6Engine8TurbojetEEE
apache-2.0
petrmanek/revolver
Sources/Evaluator.swift
1
997
/// Evaluator determines quality of chromosomes. /// /// This is an abstract class. You **cannot** instantate it directly. /// When subclassing it, be sure to implement the `evaluateIndividuals()` method. open class Evaluator<Chromosome: ChromosomeType> { public typealias EvaluationHandler = (_ index: Int) -> () public init() { } /** Evaluate population of individuals. - parameter individuals: Population to evaluate. - parameter individualEvaluated: Handler to call when an individual is evaluated. - warning: This method is abstract. You **must** override it in subclasses. - note: This method is expected to be *synchronous*. It **must not** return to its caller until all individuals are evaluated. */ open func evaluateIndividuals(_ individuals: MatingPool<Chromosome>, individualEvaluated: @escaping EvaluationHandler) { preconditionFailure("This method must be implemented in a subclass.") } }
mit
nsutanto/ios-VirtualTourist
VirtualTourist/Model/CoreData/CoreDataStack.swift
1
5761
// // CoreDataStack.swift // // // Created by Fernando Rodríguez Romero on 21/02/16. // Copyright © 2016 udacity.com. All rights reserved. // import CoreData // MARK: - CoreDataStack struct CoreDataStack { // MARK: Properties private let model: NSManagedObjectModel internal let coordinator: NSPersistentStoreCoordinator private let modelURL: URL internal let dbURL: URL internal let persistingContext: NSManagedObjectContext internal let backgroundContext: NSManagedObjectContext let context: NSManagedObjectContext // MARK: Initializers init?(modelName: String) { // Assumes the model is in the main bundle guard let modelURL = Bundle.main.url(forResource: modelName, withExtension: "momd") else { print("Unable to find \(modelName)in the main bundle") return nil } self.modelURL = modelURL // Try to create the model from the URL guard let model = NSManagedObjectModel(contentsOf: modelURL) else { print("unable to create a model from \(modelURL)") return nil } self.model = model // Create the store coordinator coordinator = NSPersistentStoreCoordinator(managedObjectModel: model) // Create a persistingContext (private queue) and a child one (main queue) // create a context and add connect it to the coordinator persistingContext = NSManagedObjectContext(concurrencyType: .privateQueueConcurrencyType) persistingContext.persistentStoreCoordinator = coordinator context = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType) context.parent = persistingContext // Create a background context child of main context backgroundContext = NSManagedObjectContext(concurrencyType: .privateQueueConcurrencyType) backgroundContext.parent = context // Add a SQLite store located in the documents folder let fm = FileManager.default guard let docUrl = fm.urls(for: .documentDirectory, in: .userDomainMask).first else { print("Unable to reach the documents folder") return nil } self.dbURL = docUrl.appendingPathComponent("model.sqlite") // Options for migration let options = [NSInferMappingModelAutomaticallyOption: true,NSMigratePersistentStoresAutomaticallyOption: true] do { try addStoreCoordinator(NSSQLiteStoreType, configuration: nil, storeURL: dbURL, options: options as [NSObject : AnyObject]?) } catch { print("unable to add store at \(dbURL)") } } // MARK: Utils func addStoreCoordinator(_ storeType: String, configuration: String?, storeURL: URL, options : [NSObject:AnyObject]?) throws { try coordinator.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: dbURL, options: nil) } } // MARK: - CoreDataStack (Removing Data) internal extension CoreDataStack { func dropAllData() throws { // delete all the objects in the db. This won't delete the files, it will // just leave empty tables. try coordinator.destroyPersistentStore(at: dbURL, ofType: NSSQLiteStoreType , options: nil) try addStoreCoordinator(NSSQLiteStoreType, configuration: nil, storeURL: dbURL, options: nil) } } // MARK: - CoreDataStack (Batch Processing in the Background) extension CoreDataStack { typealias Batch = (_ workerContext: NSManagedObjectContext) -> () func performBackgroundBatchOperation(_ batch: @escaping Batch) { backgroundContext.perform() { batch(self.backgroundContext) // Save it to the parent context, so normal saving // can work do { try self.backgroundContext.save() } catch { fatalError("Error while saving backgroundContext: \(error)") } } } } // MARK: - CoreDataStack (Save Data) extension CoreDataStack { func save() { // We call this synchronously, but it's a very fast // operation (it doesn't hit the disk). We need to know // when it ends so we can call the next save (on the persisting // context). This last one might take some time and is done // in a background queue context.performAndWait() { if self.context.hasChanges { do { try self.context.save() } catch { fatalError("Error while saving main context: \(error)") } // now we save in the background self.persistingContext.perform() { do { try self.persistingContext.save() } catch { fatalError("Error while saving persisting context: \(error)") } } } } } func autoSave(_ delayInSeconds : Int) { if delayInSeconds > 0 { do { try self.context.save() //print("Autosaving") } catch { print("Error while autosaving") } let delayInNanoSeconds = UInt64(delayInSeconds) * NSEC_PER_SEC let time = DispatchTime.now() + Double(Int64(delayInNanoSeconds)) / Double(NSEC_PER_SEC) DispatchQueue.main.asyncAfter(deadline: time) { self.autoSave(delayInSeconds) } } } }
mit
ceecer1/open-muvr
ios/Lift/DemoSessionController.swift
5
4166
import Foundation struct DataFile { var path: String var size: NSNumber var name: String } class DemoSessionTableModel : NSObject, UITableViewDataSource { private var dataFiles: [DataFile] init(muscleGroupKeys: [String]) { dataFiles = NSBundle.mainBundle().pathsForResourcesOfType(".dat", inDirectory: nil) .map { p -> String in return p as String } .filter { p in return !muscleGroupKeys.filter { k in return p.lastPathComponent.hasPrefix(k) }.isEmpty } .map { path in let attrs = NSFileManager.defaultManager().attributesOfItemAtPath(path, error: nil)! let size: NSNumber = attrs[NSFileSize] as NSNumber return DataFile(path: path, size: size, name: path.lastPathComponent) } super.init() } // MARK: UITableViewDataSource func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return dataFiles.count } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let data = dataFiles[indexPath.row] let cell = tableView.dequeueReusableCellWithIdentifier("default") as UITableViewCell cell.textLabel!.text = data.name let fmt = NSNumberFormatter() fmt.numberStyle = NSNumberFormatterStyle.DecimalStyle let sizeString = fmt.stringFromNumber(data.size)! cell.detailTextLabel!.text = "\(sizeString) B" return cell } func filePathAtIndexPath(indexPath: NSIndexPath) -> String? { return dataFiles[indexPath.row].path } } class DemoSessionController : UIViewController, UITableViewDelegate, ExerciseSessionSettable { @IBOutlet var tableView: UITableView! @IBOutlet var stopSessionButton: UIBarButtonItem! private var tableModel: DemoSessionTableModel? private var session: ExerciseSession? private var timer: NSTimer? private var startTime: NSDate? // MARK: main override func viewWillDisappear(animated: Bool) { timer!.invalidate() navigationItem.prompt = nil session?.end(const(())) } @IBAction func stopSession() { if stopSessionButton.tag < 0 { stopSessionButton.title = "Really?" stopSessionButton.tag = 3 } else { navigationItem.prompt = nil navigationController!.popToRootViewControllerAnimated(true) } } override func viewDidLoad() { tableView.delegate = self tableView.dataSource = tableModel! stopSessionButton.title = "Stop" stopSessionButton.tag = 0 startTime = NSDate() tabBarController?.tabBar.hidden = true timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: "tick", userInfo: nil, repeats: true) } func tick() { let elapsed = Int(NSDate().timeIntervalSinceDate(self.startTime!)) let minutes: Int = elapsed / 60 let seconds: Int = elapsed - minutes * 60 navigationItem.prompt = NSString(format: "Elapsed %d:%02d", minutes, seconds) stopSessionButton.tag -= 1 if stopSessionButton.tag < 0 { stopSessionButton.title = "Stop" } } // MARK: ExerciseSessionSettable func setExerciseSession(session: ExerciseSession) { self.session = session tableModel = DemoSessionTableModel(muscleGroupKeys: session.props.muscleGroupKeys) } // MARK: UITableViewDelegate func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { fatalError("This needs work") // let path = tableModel!.filePathAtIndexPath(indexPath) // let data = NSFileManager.defaultManager().contentsAtPath(path!)! // let mp = MutableMultiPacket().append(DeviceInfo.Location.Wrist, data: data) // session?.submitData(mp, const(())) // tableView.deselectRowAtIndexPath(indexPath, animated: true) } }
apache-2.0
swiftsanyue/TestKitchen
TestKitchen/TestKitchen/classes/ingredient(食材)/recommend(推荐)/main(主要模块)/foodCourse(食材课程)/view/FCVideoCell.swift
1
1411
// // FCVideoCell.swift // TestKitchen // // Created by ZL on 16/11/4. // Copyright © 2016年 zl. All rights reserved. // import UIKit class FCVideoCell: UITableViewCell { //播放视频 var playClosure:(String-> Void)? //显示数据 var cellModel: FoodCourseSerial? { didSet{ if cellModel != nil { showData() } } } func showData() { //图片 let url = NSURL(string: (cellModel?.course_image)!) bgImgeView.kf_setImageWithURL(url, placeholderImage: UIImage(named: "sdefaultImage"), optionsInfo: nil, progressBlock: nil, completionHandler: nil) //文字 numLabel.text = "\(cellModel!.video_watchcount!)人做过" numLabel.textColor = UIColor.whiteColor() } @IBOutlet weak var bgImgeView: UIImageView! @IBOutlet weak var numLabel: UILabel! @IBAction func playBtn(sender: UIButton) { if cellModel?.course_video != nil && playClosure != nil { playClosure!((cellModel?.course_video)!) } } override func awakeFromNib() { super.awakeFromNib() } override func setSelected(selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } }
mit
kstaring/swift
test/SILGen/Inputs/AppKit.swift
15
294
import Foundation @_exported import AppKit // Fix the ARGV type of NSApplicationMain, which nonsensically takes // argv as a const char**. @_silgen_name("NSApplicationMain") public func NSApplicationMain( _ argc: Int32, _ argv: UnsafeMutablePointer<UnsafeMutablePointer<CChar>?> ) -> Int32
apache-2.0
HJliu1123/LearningNotes-LHJ
April/swift基础.playground/Pages/集合类型.xcplaygroundpage/Contents.swift
1
2607
//: [Previous](@previous) import Foundation var str = "Hello, playground" //: [Next](@next) /* 数组 */ var arr : Array<String> arr = ["akf", "afhu"] arr.insert("skf", atIndex: 1) arr.removeAtIndex(1) //删除前面一个 arr.removeFirst(1) var array : Array<Int> = Array<Int>() array.append(10) var array1 = Array<Int>() array1.append(100) var array2 : [Int] = [3,5,6,3] var array3 = [4,2,3] var array4 = [String]() array4.append("dlfk") var shopList = ["泡面","牙膏"] shopList += ["香烟"] shopList.insert("饮料", atIndex: 1) shopList.append("零食") //var str1 = shopList.removeLast() // //shopList //shopList.removeAtIndex(2) //shopList //var range = Range(start: 0, end: 2) //shopList.removeRange(range) //shopList shopList[0] = "大米" for shopping in shopList { print(shopping) } for var i = 0; i < shopList.count; i++ { print("第\(i)个位置的元素是\(shopList[i])") } //二维数组 let n = 9 var nine = [[Int]](count: n, repeatedValue: [Int](count: n, repeatedValue: 0)) assert(n % 2 != 0,"n必须是奇数") var row = 0 var col = n / 2 for var i = 1; i <= n * n; i++ { nine[row][col] = i row-- col++ if row < 0 && col >= n { row += 2 col-- } else if row < 0 { row = n - 1 } else if col >= n { col = 0 } else if nine[row][col] != 0 { row += 2 col-- } } nine //字典 var dict : Dictionary<String, Int> = Dictionary<String, Int>() var dict2 = Dictionary<String, Int>() var dict3 = [String : Int]() dict3["sdk"] = 100 var airports : [String : String] = ["PEK":"北京首都机场","CAN":"广州白云机场"] var airports2 : Dictionary<String,String> = ["sha":"上海"] airports["SHA2"] = "" airports.updateValue("上海虹桥机场", forKey: "SHA2") airports2.removeValueForKey("sha") for (key, value) in airports { print("key = \(key),value = \(value)") } //引用类型 var dict4 = NSDictionary() //选举计数 let ballot = ["shasha","lili","zhangsan","lishi","shasha","lili","shasha","lishi","shasha","zhangsan","lishi","lili"] var vote = [String : Int]() for name in ballot { if let cnt = vote[name] { vote[name] = cnt + 1 } else { vote[name] = 1 } } vote /* *set集合 */ var set1 : Set<String> = ["rock","classic","jazz","hip hop"] set1.insert("afds") if let str = set1.remove("afds") { print("suc") } else { print("fail") } set1.contains("rock") //遍历 for str in set1 { print(str) } var sortArr : Array<String> = set1.sort() for str in set1.sort() { print(str) }
apache-2.0
arvedviehweger/swift
test/Compatibility/tuple_arguments.swift
1
39709
// RUN: %target-typecheck-verify-swift -swift-version 3 // Tests for tuple argument behavior in Swift 3, which was broken. // The Swift 4 test is in test/Constraints/tuple_arguments.swift. // Key: // - "Crashes in actual Swift 3" -- snippets which crashed in Swift 3.0.1. // These don't have well-defined semantics in Swift 3 mode and don't // matter for source compatibility purposes. // // - "Does not diagnose in Swift 3 mode" -- snippets which failed to typecheck // in Swift 3.0.1, but now typecheck. This is fine. // // - "Diagnoses in Swift 3 mode" -- snippets which typechecked in Swift 3.0.1, // but now fail to typecheck. These are bugs in Swift 3 mode that should be // fixed. // // - "Crashes in Swift 3 mode" -- snippets which did not crash Swift 3.0.1, // but now crash. These are bugs in Swift 3 mode that should be fixed. func concrete(_ x: Int) {} func concreteLabeled(x: Int) {} func concreteTwo(_ x: Int, _ y: Int) {} // expected-note 3 {{'concreteTwo' declared here}} func concreteTuple(_ x: (Int, Int)) {} do { concrete(3) concrete((3)) concreteLabeled(x: 3) concreteLabeled(x: (3)) concreteLabeled((x: 3)) // expected-error {{missing argument label 'x:' in call}} concreteTwo(3, 4) concreteTwo((3, 4)) // expected-error {{missing argument for parameter #2 in call}} concreteTuple(3, 4) // expected-error {{extra argument in call}} concreteTuple((3, 4)) } do { let a = 3 let b = 4 let c = (3) let d = (a, b) concrete(a) concrete((a)) concrete(c) concreteTwo(a, b) concreteTwo((a, b)) concreteTwo(d) // expected-error {{passing 2 arguments to a callee as a single tuple value has been removed in Swift 3}} concreteTuple(a, b) concreteTuple((a, b)) concreteTuple(d) } do { var a = 3 // expected-warning {{variable 'a' was never mutated; consider changing to 'let' constant}} var b = 4 // expected-warning {{variable 'b' was never mutated; consider changing to 'let' constant}} var c = (3) // expected-warning {{variable 'c' was never mutated; consider changing to 'let' constant}} var d = (a, b) // expected-warning {{variable 'd' was never mutated; consider changing to 'let' constant}} concrete(a) concrete((a)) concrete(c) concreteTwo(a, b) concreteTwo((a, b)) // expected-error {{missing argument for parameter #2 in call}} concreteTwo(d) // expected-error {{missing argument for parameter #2 in call}} concreteTuple(a, b) // expected-error {{extra argument in call}} concreteTuple((a, b)) concreteTuple(d) } func generic<T>(_ x: T) {} func genericLabeled<T>(x: T) {} func genericTwo<T, U>(_ x: T, _ y: U) {} // expected-note 5 {{'genericTwo' declared here}} func genericTuple<T, U>(_ x: (T, U)) {} do { generic(3) generic(3, 4) generic((3)) generic((3, 4)) genericLabeled(x: 3) genericLabeled(x: 3, 4) // expected-error {{extra argument in call}} genericLabeled(x: (3)) genericLabeled(x: (3, 4)) genericTwo(3, 4) genericTwo((3, 4)) // expected-error {{missing argument for parameter #2 in call}} genericTuple(3, 4) // expected-error {{extra argument in call}} genericTuple((3, 4)) } do { let a = 3 let b = 4 let c = (3) let d = (a, b) generic(a) generic(a, b) generic((a)) generic(c) generic((a, b)) generic(d) genericTwo(a, b) genericTwo((a, b)) // expected-error {{missing argument for parameter #2 in call}} genericTwo(d) // expected-error {{missing argument for parameter #2 in call}} genericTuple(a, b) // expected-error {{extra argument in call}} genericTuple((a, b)) genericTuple(d) } do { var a = 3 var b = 4 var c = (3) var d = (a, b) generic(a) // generic(a, b) // Crashes in actual Swift 3 generic((a)) generic(c) generic((a, b)) generic(d) genericTwo(a, b) genericTwo((a, b)) // expected-error {{missing argument for parameter #2 in call}} genericTwo(d) // expected-error {{missing argument for parameter #2 in call}} genericTuple(a, b) // expected-error {{extra argument in call}} genericTuple((a, b)) genericTuple(d) } var function: (Int) -> () var functionTwo: (Int, Int) -> () // expected-note 3 {{'functionTwo' declared here}} var functionTuple: ((Int, Int)) -> () do { function(3) function((3)) functionTwo(3, 4) functionTwo((3, 4)) // expected-error {{missing argument for parameter #2 in call}} functionTuple(3, 4) // expected-error {{extra argument in call}} functionTuple((3, 4)) } do { let a = 3 let b = 4 let c = (3) let d = (a, b) function(a) function((a)) function(c) functionTwo(a, b) functionTwo((a, b)) functionTwo(d) // expected-error {{passing 2 arguments to a callee as a single tuple value has been removed in Swift 3}} functionTuple(a, b) functionTuple((a, b)) functionTuple(d) } do { var a = 3 var b = 4 var c = (3) var d = (a, b) function(a) function((a)) function(c) functionTwo(a, b) functionTwo((a, b)) // expected-error {{missing argument for parameter #2 in call}} functionTwo(d) // expected-error {{missing argument for parameter #2 in call}} functionTuple(a, b) // expected-error {{extra argument in call}} functionTuple((a, b)) functionTuple(d) } struct Concrete {} extension Concrete { func concrete(_ x: Int) {} func concreteTwo(_ x: Int, _ y: Int) {} // expected-note 3 {{'concreteTwo' declared here}} func concreteTuple(_ x: (Int, Int)) {} } do { let s = Concrete() s.concrete(3) s.concrete((3)) s.concreteTwo(3, 4) s.concreteTwo((3, 4)) // expected-error {{missing argument for parameter #2 in call}} s.concreteTuple(3, 4) // expected-error {{extra argument in call}} s.concreteTuple((3, 4)) } do { let s = Concrete() let a = 3 let b = 4 let c = (3) let d = (a, b) s.concrete(a) s.concrete((a)) s.concrete(c) s.concreteTwo(a, b) s.concreteTwo((a, b)) s.concreteTwo(d) // expected-error {{passing 2 arguments to a callee as a single tuple value has been removed in Swift 3}} s.concreteTuple(a, b) s.concreteTuple((a, b)) s.concreteTuple(d) } do { var s = Concrete() var a = 3 var b = 4 var c = (3) var d = (a, b) s.concrete(a) s.concrete((a)) s.concrete(c) s.concreteTwo(a, b) s.concreteTwo((a, b)) // expected-error {{missing argument for parameter #2 in call}} s.concreteTwo(d) // expected-error {{missing argument for parameter #2 in call}} s.concreteTuple(a, b) // expected-error {{extra argument in call}} s.concreteTuple((a, b)) s.concreteTuple(d) } extension Concrete { func generic<T>(_ x: T) {} func genericLabeled<T>(x: T) {} func genericTwo<T, U>(_ x: T, _ y: U) {} // expected-note 5 {{'genericTwo' declared here}} func genericTuple<T, U>(_ x: (T, U)) {} } do { let s = Concrete() s.generic(3) s.generic(3, 4) s.generic((3)) s.generic((3, 4)) s.genericLabeled(x: 3) s.genericLabeled(x: 3, 4) // expected-error {{extra argument in call}} s.genericLabeled(x: (3)) s.genericLabeled(x: (3, 4)) s.genericTwo(3, 4) s.genericTwo((3, 4)) // expected-error {{missing argument for parameter #2 in call}} s.genericTuple(3, 4) // expected-error {{extra argument in call}} s.genericTuple((3, 4)) } do { let s = Concrete() let a = 3 let b = 4 let c = (3) let d = (a, b) s.generic(a) s.generic(a, b) s.generic((a)) s.generic((a, b)) s.generic(d) s.genericTwo(a, b) s.genericTwo((a, b)) // expected-error {{missing argument for parameter #2 in call}} s.genericTwo(d) // expected-error {{missing argument for parameter #2 in call}} s.genericTuple(a, b) // expected-error {{extra argument in call}} s.genericTuple((a, b)) s.genericTuple(d) } do { var s = Concrete() var a = 3 var b = 4 var c = (3) var d = (a, b) s.generic(a) // s.generic(a, b) // Crashes in actual Swift 3 s.generic((a)) s.generic((a, b)) s.generic(d) s.genericTwo(a, b) s.genericTwo((a, b)) // expected-error {{missing argument for parameter #2 in call}} s.genericTwo(d) // expected-error {{missing argument for parameter #2 in call}} s.genericTuple(a, b) // expected-error {{extra argument in call}} s.genericTuple((a, b)) s.genericTuple(d) } extension Concrete { mutating func mutatingConcrete(_ x: Int) {} mutating func mutatingConcreteTwo(_ x: Int, _ y: Int) {} // expected-note 3 {{'mutatingConcreteTwo' declared here}} mutating func mutatingConcreteTuple(_ x: (Int, Int)) {} } do { var s = Concrete() s.mutatingConcrete(3) s.mutatingConcrete((3)) s.mutatingConcreteTwo(3, 4) s.mutatingConcreteTwo((3, 4)) // expected-error {{missing argument for parameter #2 in call}} s.mutatingConcreteTuple(3, 4) // expected-error {{extra argument in call}} s.mutatingConcreteTuple((3, 4)) } do { var s = Concrete() let a = 3 let b = 4 let c = (3) let d = (a, b) s.mutatingConcrete(a) s.mutatingConcrete((a)) s.mutatingConcrete(c) s.mutatingConcreteTwo(a, b) s.mutatingConcreteTwo((a, b)) s.mutatingConcreteTwo(d) // expected-error {{passing 2 arguments to a callee as a single tuple value has been removed in Swift 3}} s.mutatingConcreteTuple(a, b) s.mutatingConcreteTuple((a, b)) s.mutatingConcreteTuple(d) } do { var s = Concrete() var a = 3 var b = 4 var c = (3) var d = (a, b) s.mutatingConcrete(a) s.mutatingConcrete((a)) s.mutatingConcrete(c) s.mutatingConcreteTwo(a, b) s.mutatingConcreteTwo((a, b)) // expected-error {{missing argument for parameter #2 in call}} s.mutatingConcreteTwo(d) // expected-error {{missing argument for parameter #2 in call}} s.mutatingConcreteTuple(a, b) // expected-error {{extra argument in call}} s.mutatingConcreteTuple((a, b)) s.mutatingConcreteTuple(d) } extension Concrete { mutating func mutatingGeneric<T>(_ x: T) {} mutating func mutatingGenericLabeled<T>(x: T) {} mutating func mutatingGenericTwo<T, U>(_ x: T, _ y: U) {} // expected-note 5 {{'mutatingGenericTwo' declared here}} mutating func mutatingGenericTuple<T, U>(_ x: (T, U)) {} } do { var s = Concrete() s.mutatingGeneric(3) s.mutatingGeneric(3, 4) s.mutatingGeneric((3)) s.mutatingGeneric((3, 4)) s.mutatingGenericLabeled(x: 3) s.mutatingGenericLabeled(x: 3, 4) // expected-error {{extra argument in call}} s.mutatingGenericLabeled(x: (3)) s.mutatingGenericLabeled(x: (3, 4)) s.mutatingGenericTwo(3, 4) s.mutatingGenericTwo((3, 4)) // expected-error {{missing argument for parameter #2 in call}} s.mutatingGenericTuple(3, 4) // expected-error {{extra argument in call}} s.mutatingGenericTuple((3, 4)) } do { var s = Concrete() let a = 3 let b = 4 let c = (3) let d = (a, b) s.mutatingGeneric(a) s.mutatingGeneric(a, b) s.mutatingGeneric((a)) s.mutatingGeneric((a, b)) s.mutatingGeneric(d) s.mutatingGenericTwo(a, b) s.mutatingGenericTwo((a, b)) // expected-error {{missing argument for parameter #2 in call}} s.mutatingGenericTwo(d) // expected-error {{missing argument for parameter #2 in call}} s.mutatingGenericTuple(a, b) // expected-error {{extra argument in call}} s.mutatingGenericTuple((a, b)) s.mutatingGenericTuple(d) } do { var s = Concrete() var a = 3 var b = 4 var c = (3) var d = (a, b) s.mutatingGeneric(a) // s.mutatingGeneric(a, b) // Crashes in actual Swift 3 s.mutatingGeneric((a)) s.mutatingGeneric((a, b)) s.mutatingGeneric(d) s.mutatingGenericTwo(a, b) s.mutatingGenericTwo((a, b)) // expected-error {{missing argument for parameter #2 in call}} s.mutatingGenericTwo(d) // expected-error {{missing argument for parameter #2 in call}} s.mutatingGenericTuple(a, b) // expected-error {{extra argument in call}} s.mutatingGenericTuple((a, b)) s.mutatingGenericTuple(d) } extension Concrete { var function: (Int) -> () { return concrete } var functionTwo: (Int, Int) -> () { return concreteTwo } var functionTuple: ((Int, Int)) -> () { return concreteTuple } } do { let s = Concrete() s.function(3) s.function((3)) s.functionTwo(3, 4) s.functionTwo((3, 4)) // expected-error {{missing argument for parameter #2 in call}} s.functionTuple(3, 4) // expected-error {{extra argument in call}} s.functionTuple((3, 4)) } do { let s = Concrete() let a = 3 let b = 4 let c = (3) let d = (a, b) s.function(a) s.function((a)) s.function(c) s.functionTwo(a, b) s.functionTwo((a, b)) s.functionTwo(d) // expected-error {{passing 2 arguments to a callee as a single tuple value has been removed in Swift 3}} s.functionTuple(a, b) s.functionTuple((a, b)) s.functionTuple(d) } do { var s = Concrete() var a = 3 var b = 4 var c = (3) var d = (a, b) s.function(a) s.function((a)) s.function(c) s.functionTwo(a, b) s.functionTwo((a, b)) // expected-error {{missing argument for parameter #2 in call}} s.functionTwo(d) // expected-error {{missing argument for parameter #2 in call}} s.functionTuple(a, b) // expected-error {{extra argument in call}} s.functionTuple((a, b)) s.functionTuple(d) } struct InitTwo { init(_ x: Int, _ y: Int) {} // expected-note 3 {{'init' declared here}} } struct InitTuple { init(_ x: (Int, Int)) {} } struct InitLabeledTuple { init(x: (Int, Int)) {} } do { _ = InitTwo(3, 4) _ = InitTwo((3, 4)) // expected-error {{missing argument for parameter #2 in call}} _ = InitTuple(3, 4) // expected-error {{extra argument in call}} _ = InitTuple((3, 4)) _ = InitLabeledTuple(x: 3, 4) // expected-error {{extra argument in call}} _ = InitLabeledTuple(x: (3, 4)) } do { let a = 3 let b = 4 let c = (a, b) _ = InitTwo(a, b) _ = InitTwo((a, b)) _ = InitTwo(c) // expected-error {{passing 2 arguments to a callee as a single tuple value has been removed in Swift 3}} _ = InitTuple(a, b) _ = InitTuple((a, b)) _ = InitTuple(c) } do { var a = 3 // expected-warning {{variable 'a' was never mutated; consider changing to 'let' constant}} var b = 4 // expected-warning {{variable 'b' was never mutated; consider changing to 'let' constant}} var c = (a, b) // expected-warning {{variable 'c' was never mutated; consider changing to 'let' constant}} _ = InitTwo(a, b) _ = InitTwo((a, b)) // expected-error {{missing argument for parameter #2 in call}} _ = InitTwo(c) // expected-error {{missing argument for parameter #2 in call}} _ = InitTuple(a, b) // expected-error {{extra argument in call}} _ = InitTuple((a, b)) _ = InitTuple(c) } struct SubscriptTwo { subscript(_ x: Int, _ y: Int) -> Int { get { return 0 } set { } } // expected-note 3 {{'subscript' declared here}} } struct SubscriptTuple { subscript(_ x: (Int, Int)) -> Int { get { return 0 } set { } } } struct SubscriptLabeledTuple { subscript(x x: (Int, Int)) -> Int { get { return 0 } set { } } } do { let s1 = SubscriptTwo() _ = s1[3, 4] _ = s1[(3, 4)] // expected-error {{missing argument for parameter #2 in call}} let s2 = SubscriptTuple() _ = s2[3, 4] // expected-error {{extra argument in call}} _ = s2[(3, 4)] let s3 = SubscriptLabeledTuple() _ = s3[x: 3, 4] // expected-error {{extra argument in call}} _ = s3[x: (3, 4)] } do { let a = 3 let b = 4 let d = (a, b) let s1 = SubscriptTwo() _ = s1[a, b] _ = s1[(a, b)] _ = s1[d] let s2 = SubscriptTuple() _ = s2[a, b] _ = s2[(a, b)] _ = s2[d] } do { var a = 3 // expected-warning {{variable 'a' was never mutated; consider changing to 'let' constant}} var b = 4 // expected-warning {{variable 'b' was never mutated; consider changing to 'let' constant}} var d = (a, b) // expected-warning {{variable 'd' was never mutated; consider changing to 'let' constant}} var s1 = SubscriptTwo() _ = s1[a, b] _ = s1[(a, b)] // expected-error {{missing argument for parameter #2 in call}} _ = s1[d] // expected-error {{missing argument for parameter #2 in call}} var s2 = SubscriptTuple() _ = s2[a, b] // expected-error {{extra argument in call}}} _ = s2[(a, b)] _ = s2[d] } enum Enum { case two(Int, Int) // expected-note 3 {{'two' declared here}} case tuple((Int, Int)) case labeledTuple(x: (Int, Int)) } do { _ = Enum.two(3, 4) _ = Enum.two((3, 4)) // expected-error {{missing argument for parameter #2 in call}} _ = Enum.tuple(3, 4) // expected-error {{extra argument in call}} _ = Enum.tuple((3, 4)) _ = Enum.labeledTuple(x: 3, 4) // expected-error {{extra argument in call}} _ = Enum.labeledTuple(x: (3, 4)) } do { let a = 3 let b = 4 let c = (a, b) _ = Enum.two(a, b) _ = Enum.two((a, b)) _ = Enum.two(c) // expected-error {{passing 2 arguments to a callee as a single tuple value has been removed in Swift 3}} _ = Enum.tuple(a, b) _ = Enum.tuple((a, b)) _ = Enum.tuple(c) } do { var a = 3 var b = 4 var c = (a, b) _ = Enum.two(a, b) _ = Enum.two((a, b)) // expected-error {{missing argument for parameter #2 in call}} _ = Enum.two(c) // expected-error {{missing argument for parameter #2 in call}} _ = Enum.tuple(a, b) // expected-error {{extra argument in call}} _ = Enum.tuple((a, b)) _ = Enum.tuple(c) } struct Generic<T> {} extension Generic { func generic(_ x: T) {} func genericLabeled(x: T) {} func genericTwo(_ x: T, _ y: T) {} // expected-note 2 {{'genericTwo' declared here}} func genericTuple(_ x: (T, T)) {} } do { let s = Generic<Double>() s.generic(3.0) s.generic((3.0)) s.genericLabeled(x: 3.0) s.genericLabeled(x: (3.0)) s.genericTwo(3.0, 4.0) s.genericTwo((3.0, 4.0)) // expected-error {{missing argument for parameter #2 in call}} s.genericTuple(3.0, 4.0) // expected-error {{extra argument in call}} s.genericTuple((3.0, 4.0)) let sTwo = Generic<(Double, Double)>() sTwo.generic(3.0, 4.0) // expected-error {{extra argument in call}} sTwo.generic((3.0, 4.0)) sTwo.genericLabeled(x: 3.0, 4.0) // expected-error {{extra argument in call}} sTwo.genericLabeled(x: (3.0, 4.0)) } do { let s = Generic<Double>() let a = 3.0 let b = 4.0 let c = (3.0) let d = (a, b) s.generic(a) s.generic((a)) s.generic(c) s.genericTwo(a, b) s.genericTwo((a, b)) s.genericTuple(a, b) s.genericTuple((a, b)) let sTwo = Generic<(Double, Double)>() sTwo.generic(a, b) sTwo.generic((a, b)) sTwo.generic(d) } do { var s = Generic<Double>() var a = 3.0 var b = 4.0 var c = (3.0) var d = (a, b) s.generic(a) s.generic((a)) s.generic(c) s.genericTwo(a, b) s.genericTwo((a, b)) // expected-error {{missing argument for parameter #2 in call}} s.genericTuple(a, b) // expected-error {{extra argument in call}} s.genericTuple((a, b)) var sTwo = Generic<(Double, Double)>() sTwo.generic(a, b) // expected-error {{extra argument in call}} sTwo.generic((a, b)) sTwo.generic(d) } extension Generic { mutating func mutatingGeneric(_ x: T) {} mutating func mutatingGenericLabeled(x: T) {} mutating func mutatingGenericTwo(_ x: T, _ y: T) {} // expected-note 2 {{'mutatingGenericTwo' declared here}} mutating func mutatingGenericTuple(_ x: (T, T)) {} } do { var s = Generic<Double>() s.mutatingGeneric(3.0) s.mutatingGeneric((3.0)) s.mutatingGenericLabeled(x: 3.0) s.mutatingGenericLabeled(x: (3.0)) s.mutatingGenericTwo(3.0, 4.0) s.mutatingGenericTwo((3.0, 4.0)) // expected-error {{missing argument for parameter #2 in call}} s.mutatingGenericTuple(3.0, 4.0) // expected-error {{extra argument in call}} s.mutatingGenericTuple((3.0, 4.0)) var sTwo = Generic<(Double, Double)>() sTwo.mutatingGeneric(3.0, 4.0) // expected-error {{extra argument in call}} sTwo.mutatingGeneric((3.0, 4.0)) sTwo.mutatingGenericLabeled(x: 3.0, 4.0) // expected-error {{extra argument in call}} sTwo.mutatingGenericLabeled(x: (3.0, 4.0)) } do { var s = Generic<Double>() let a = 3.0 let b = 4.0 let c = (3.0) let d = (a, b) s.mutatingGeneric(a) s.mutatingGeneric((a)) s.mutatingGeneric(c) s.mutatingGenericTwo(a, b) s.mutatingGenericTwo((a, b)) s.mutatingGenericTuple(a, b) s.mutatingGenericTuple((a, b)) var sTwo = Generic<(Double, Double)>() sTwo.mutatingGeneric(a, b) sTwo.mutatingGeneric((a, b)) sTwo.mutatingGeneric(d) } do { var s = Generic<Double>() var a = 3.0 var b = 4.0 var c = (3.0) var d = (a, b) s.mutatingGeneric(a) s.mutatingGeneric((a)) s.mutatingGeneric(c) s.mutatingGenericTwo(a, b) s.mutatingGenericTwo((a, b)) // expected-error {{missing argument for parameter #2 in call}} s.mutatingGenericTuple(a, b) // expected-error {{extra argument in call}} s.mutatingGenericTuple((a, b)) var sTwo = Generic<(Double, Double)>() sTwo.mutatingGeneric(a, b) // expected-error {{extra argument in call}} sTwo.mutatingGeneric((a, b)) sTwo.mutatingGeneric(d) } extension Generic { var genericFunction: (T) -> () { return generic } var genericFunctionTwo: (T, T) -> () { return genericTwo } var genericFunctionTuple: ((T, T)) -> () { return genericTuple } } do { let s = Generic<Double>() s.genericFunction(3.0) s.genericFunction((3.0)) s.genericFunctionTwo(3.0, 4.0) s.genericFunctionTwo((3.0, 4.0)) // expected-error {{missing argument for parameter #2 in call}} s.genericFunctionTuple(3.0, 4.0) // expected-error {{extra argument in call}} s.genericFunctionTuple((3.0, 4.0)) let sTwo = Generic<(Double, Double)>() sTwo.genericFunction(3.0, 4.0) sTwo.genericFunction((3.0, 4.0)) // Does not diagnose in Swift 3 mode } do { let s = Generic<Double>() let a = 3.0 let b = 4.0 let c = (3.0) let d = (a, b) s.genericFunction(a) s.genericFunction((a)) s.genericFunction(c) s.genericFunctionTwo(a, b) s.genericFunctionTwo((a, b)) s.genericFunctionTuple(a, b) s.genericFunctionTuple((a, b)) let sTwo = Generic<(Double, Double)>() sTwo.genericFunction(a, b) sTwo.genericFunction((a, b)) sTwo.genericFunction(d) // Does not diagnose in Swift 3 mode } do { var s = Generic<Double>() var a = 3.0 var b = 4.0 var c = (3.0) var d = (a, b) s.genericFunction(a) s.genericFunction((a)) s.genericFunction(c) s.genericFunctionTwo(a, b) s.genericFunctionTwo((a, b)) // expected-error {{missing argument for parameter #2 in call}} s.genericFunctionTuple(a, b) // expected-error {{extra argument in call}} s.genericFunctionTuple((a, b)) var sTwo = Generic<(Double, Double)>() sTwo.genericFunction(a, b) sTwo.genericFunction((a, b)) // Does not diagnose in Swift 3 mode sTwo.genericFunction(d) // Does not diagnose in Swift 3 mode } struct GenericInit<T> { // expected-note 2 {{'T' declared as parameter to type 'GenericInit'}} init(_ x: T) {} } struct GenericInitLabeled<T> { init(x: T) {} } struct GenericInitTwo<T> { init(_ x: T, _ y: T) {} // expected-note 8 {{'init' declared here}} } struct GenericInitTuple<T> { init(_ x: (T, T)) {} } struct GenericInitLabeledTuple<T> { init(x: (T, T)) {} } do { _ = GenericInit(3, 4) _ = GenericInit((3, 4)) _ = GenericInitLabeled(x: 3, 4) // expected-error {{extra argument in call}} _ = GenericInitLabeled(x: (3, 4)) _ = GenericInitTwo(3, 4) _ = GenericInitTwo((3, 4)) // expected-error {{missing argument for parameter #2 in call}} _ = GenericInitTuple(3, 4) // expected-error {{extra argument in call}} _ = GenericInitTuple((3, 4)) _ = GenericInitLabeledTuple(x: 3, 4) // expected-error {{extra argument in call}} _ = GenericInitLabeledTuple(x: (3, 4)) } do { _ = GenericInit<(Int, Int)>(3, 4) _ = GenericInit<(Int, Int)>((3, 4)) // expected-error {{expression type 'GenericInit<(Int, Int)>' is ambiguous without more context}} _ = GenericInitLabeled<(Int, Int)>(x: 3, 4) // expected-error {{extra argument in call}} _ = GenericInitLabeled<(Int, Int)>(x: (3, 4)) _ = GenericInitTwo<Int>(3, 4) _ = GenericInitTwo<Int>((3, 4)) // expected-error {{missing argument for parameter #2 in call}} _ = GenericInitTuple<Int>(3, 4) // expected-error {{extra argument in call}} _ = GenericInitTuple<Int>((3, 4)) _ = GenericInitLabeledTuple<Int>(x: 3, 4) // expected-error {{extra argument in call}} _ = GenericInitLabeledTuple<Int>(x: (3, 4)) } do { let a = 3 let b = 4 let c = (a, b) _ = GenericInit(a, b) _ = GenericInit((a, b)) _ = GenericInit(c) _ = GenericInitTwo(a, b) _ = GenericInitTwo((a, b)) // expected-error {{missing argument for parameter #2 in call}} _ = GenericInitTwo(c) // expected-error {{missing argument for parameter #2 in call}} _ = GenericInitTuple(a, b) // expected-error {{extra argument in call}} _ = GenericInitTuple((a, b)) _ = GenericInitTuple(c) } do { let a = 3 let b = 4 let c = (a, b) _ = GenericInit<(Int, Int)>(a, b) _ = GenericInit<(Int, Int)>((a, b)) _ = GenericInit<(Int, Int)>(c) _ = GenericInitTwo<Int>(a, b) _ = GenericInitTwo<Int>((a, b)) // Does not diagnose in Swift 3 mode _ = GenericInitTwo<Int>(c) // expected-error {{passing 2 arguments to a callee as a single tuple value has been removed in Swift 3}} _ = GenericInitTuple<Int>(a, b) // Does not diagnose in Swift 3 mode _ = GenericInitTuple<Int>((a, b)) _ = GenericInitTuple<Int>(c) } do { var a = 3 var b = 4 var c = (a, b) _ = GenericInit(a, b) // expected-error {{extra argument in call}} _ = GenericInit((a, b)) // expected-error {{generic parameter 'T' could not be inferred}} // expected-note {{explicitly specify the generic arguments to fix this issue}} _ = GenericInit(c) // expected-error {{generic parameter 'T' could not be inferred}} // expected-note {{explicitly specify the generic arguments to fix this issue}} _ = GenericInitTwo(a, b) _ = GenericInitTwo((a, b)) // expected-error {{missing argument for parameter #2 in call}} _ = GenericInitTwo(c) // expected-error {{missing argument for parameter #2 in call}} _ = GenericInitTuple(a, b) // expected-error {{extra argument in call}} _ = GenericInitTuple((a, b)) _ = GenericInitTuple(c) } do { var a = 3 // expected-warning {{variable 'a' was never mutated; consider changing to 'let' constant}} var b = 4 // expected-warning {{variable 'b' was never mutated; consider changing to 'let' constant}} var c = (a, b) // expected-warning {{variable 'c' was never mutated; consider changing to 'let' constant}} // _ = GenericInit<(Int, Int)>(a, b) // Crashes in Swift 3 _ = GenericInit<(Int, Int)>((a, b)) // expected-error {{expression type 'GenericInit<(Int, Int)>' is ambiguous without more context}} _ = GenericInit<(Int, Int)>(c) // expected-error {{expression type 'GenericInit<(Int, Int)>' is ambiguous without more context}} _ = GenericInitTwo<Int>(a, b) _ = GenericInitTwo<Int>((a, b)) // expected-error {{missing argument for parameter #2 in call}} _ = GenericInitTwo<Int>(c) // expected-error {{missing argument for parameter #2 in call}} _ = GenericInitTuple<Int>(a, b) // expected-error {{extra argument in call}} _ = GenericInitTuple<Int>((a, b)) _ = GenericInitTuple<Int>(c) } struct GenericSubscript<T> { subscript(_ x: T) -> Int { get { return 0 } set { } } } struct GenericSubscriptLabeled<T> { subscript(x x: T) -> Int { get { return 0 } set { } } } struct GenericSubscriptTwo<T> { subscript(_ x: T, _ y: T) -> Int { get { return 0 } set { } } // expected-note {{'subscript' declared here}} } struct GenericSubscriptTuple<T> { subscript(_ x: (T, T)) -> Int { get { return 0 } set { } } } struct GenericSubscriptLabeledTuple<T> { subscript(x x: (T, T)) -> Int { get { return 0 } set { } } } do { let s1 = GenericSubscript<(Double, Double)>() _ = s1[3.0, 4.0] _ = s1[(3.0, 4.0)] // expected-error {{expression type 'Int' is ambiguous without more context}} let s1a = GenericSubscriptLabeled<(Double, Double)>() _ = s1a [x: 3.0, 4.0] // expected-error {{extra argument in call}} _ = s1a [x: (3.0, 4.0)] let s2 = GenericSubscriptTwo<Double>() _ = s2[3.0, 4.0] _ = s2[(3.0, 4.0)] // expected-error {{missing argument for parameter #2 in call}} let s3 = GenericSubscriptTuple<Double>() _ = s3[3.0, 4.0] // expected-error {{extra argument in call}} _ = s3[(3.0, 4.0)] let s3a = GenericSubscriptLabeledTuple<Double>() _ = s3a[x: 3.0, 4.0] // expected-error {{extra argument in call}} _ = s3a[x: (3.0, 4.0)] } do { let a = 3.0 let b = 4.0 let d = (a, b) let s1 = GenericSubscript<(Double, Double)>() _ = s1[a, b] _ = s1[(a, b)] _ = s1[d] let s2 = GenericSubscriptTwo<Double>() _ = s2[a, b] _ = s2[(a, b)] // Does not diagnose in Swift 3 mode _ = s2[d] // Does not diagnose in Swift 3 mode let s3 = GenericSubscriptTuple<Double>() _ = s3[a, b] // Does not diagnose in Swift 3 mode _ = s3[(a, b)] _ = s3[d] } do { var a = 3.0 // expected-warning {{variable 'a' was never mutated; consider changing to 'let' constant}} var b = 4.0 // expected-warning {{variable 'b' was never mutated; consider changing to 'let' constant}} var d = (a, b) // expected-warning {{variable 'd' was never mutated; consider changing to 'let' constant}} var s1 = GenericSubscript<(Double, Double)>() _ = s1[a, b] _ = s1[(a, b)] // expected-error {{expression type '@lvalue Int' is ambiguous without more context}} _ = s1[d] // expected-error {{expression type '@lvalue Int' is ambiguous without more context}} var s2 = GenericSubscriptTwo<Double>() _ = s2[a, b] _ = s2[(a, b)] // expected-error {{cannot convert value of type '(Double, Double)' to expected argument type '(_, _)'}} _ = s2[d] // expected-error {{cannot convert value of type '(Double, Double)' to expected argument type '(_, _)'}} var s3 = GenericSubscriptTuple<Double>() _ = s3[a, b] // expected-error {{extra argument in call}} _ = s3[(a, b)] _ = s3[d] } enum GenericEnum<T> { case one(T) case labeled(x: T) case two(T, T) // expected-note 8 {{'two' declared here}} case tuple((T, T)) } do { _ = GenericEnum.one(3, 4) _ = GenericEnum.one((3, 4)) _ = GenericEnum.labeled(x: 3, 4) // expected-error {{extra argument in call}} _ = GenericEnum.labeled(x: (3, 4)) _ = GenericEnum.labeled(3, 4) // expected-error {{extra argument in call}} _ = GenericEnum.labeled((3, 4)) // expected-error {{missing argument label 'x:' in call}} _ = GenericEnum.two(3, 4) _ = GenericEnum.two((3, 4)) // expected-error {{missing argument for parameter #2 in call}} _ = GenericEnum.tuple(3, 4) // expected-error {{extra argument in call}} _ = GenericEnum.tuple((3, 4)) } do { _ = GenericEnum<(Int, Int)>.one(3, 4) _ = GenericEnum<(Int, Int)>.one((3, 4)) // Does not diagnose in Swift 3 mode _ = GenericEnum<(Int, Int)>.labeled(x: 3, 4) // expected-error {{extra argument in call}} _ = GenericEnum<(Int, Int)>.labeled(x: (3, 4)) _ = GenericEnum<(Int, Int)>.labeled(3, 4) // expected-error {{extra argument in call}} _ = GenericEnum<(Int, Int)>.labeled((3, 4)) // expected-error {{missing argument label 'x:' in call}} _ = GenericEnum<Int>.two(3, 4) _ = GenericEnum<Int>.two((3, 4)) // expected-error {{missing argument for parameter #2 in call}} _ = GenericEnum<Int>.tuple(3, 4) // expected-error {{extra argument in call}} _ = GenericEnum<Int>.tuple((3, 4)) } do { let a = 3 let b = 4 let c = (a, b) _ = GenericEnum.one(a, b) _ = GenericEnum.one((a, b)) _ = GenericEnum.one(c) _ = GenericEnum.two(a, b) _ = GenericEnum.two((a, b)) // expected-error {{missing argument for parameter #2 in call}} _ = GenericEnum.two(c) // expected-error {{missing argument for parameter #2 in call}} _ = GenericEnum.tuple(a, b) // expected-error {{extra argument in call}} _ = GenericEnum.tuple((a, b)) _ = GenericEnum.tuple(c) } do { let a = 3 let b = 4 let c = (a, b) _ = GenericEnum<(Int, Int)>.one(a, b) _ = GenericEnum<(Int, Int)>.one((a, b)) _ = GenericEnum<(Int, Int)>.one(c) _ = GenericEnum<Int>.two(a, b) _ = GenericEnum<Int>.two((a, b)) _ = GenericEnum<Int>.two(c) // expected-error {{passing 2 arguments to a callee as a single tuple value has been removed in Swift 3}} _ = GenericEnum<Int>.tuple(a, b) _ = GenericEnum<Int>.tuple((a, b)) _ = GenericEnum<Int>.tuple(c) } do { var a = 3 var b = 4 var c = (a, b) // _ = GenericEnum.one(a, b) // Crashes in actual Swift 3 _ = GenericEnum.one((a, b)) // Does not diagnose in Swift 3 mode _ = GenericEnum.one(c) // Does not diagnose in Swift 3 mode _ = GenericEnum.two(a, b) _ = GenericEnum.two((a, b)) // expected-error {{missing argument for parameter #2 in call}} _ = GenericEnum.two(c) // expected-error {{missing argument for parameter #2 in call}} _ = GenericEnum.tuple(a, b) // expected-error {{extra argument in call}} _ = GenericEnum.tuple((a, b)) _ = GenericEnum.tuple(c) } do { var a = 3 var b = 4 var c = (a, b) // _ = GenericEnum<(Int, Int)>.one(a, b) // Crashes in actual Swift 3 _ = GenericEnum<(Int, Int)>.one((a, b)) // Does not diagnose in Swift 3 mode _ = GenericEnum<(Int, Int)>.one(c) // Does not diagnose in Swift 3 mode _ = GenericEnum<Int>.two(a, b) _ = GenericEnum<Int>.two((a, b)) // expected-error {{missing argument for parameter #2 in call}} _ = GenericEnum<Int>.two(c) // expected-error {{missing argument for parameter #2 in call}} _ = GenericEnum<Int>.tuple(a, b) // expected-error {{extra argument in call}} _ = GenericEnum<Int>.tuple((a, b)) _ = GenericEnum<Int>.tuple(c) } protocol Protocol { associatedtype Element } extension Protocol { func requirement(_ x: Element) {} func requirementLabeled(x: Element) {} func requirementTwo(_ x: Element, _ y: Element) {} // expected-note 2 {{'requirementTwo' declared here}} func requirementTuple(_ x: (Element, Element)) {} } struct GenericConforms<T> : Protocol { typealias Element = T } do { let s = GenericConforms<Double>() s.requirement(3.0) s.requirement((3.0)) s.requirementLabeled(x: 3.0) s.requirementLabeled(x: (3.0)) s.requirementTwo(3.0, 4.0) s.requirementTwo((3.0, 4.0)) // expected-error {{missing argument for parameter #2 in call}} s.requirementTuple(3.0, 4.0) // expected-error {{extra argument in call}} s.requirementTuple((3.0, 4.0)) let sTwo = GenericConforms<(Double, Double)>() sTwo.requirement(3.0, 4.0) // expected-error {{extra argument in call}} sTwo.requirement((3.0, 4.0)) sTwo.requirementLabeled(x: 3.0, 4.0) // expected-error {{extra argument in call}} sTwo.requirementLabeled(x: (3.0, 4.0)) } do { let s = GenericConforms<Double>() let a = 3.0 let b = 4.0 let c = (3.0) let d = (a, b) s.requirement(a) s.requirement((a)) s.requirement(c) s.requirementTwo(a, b) s.requirementTwo((a, b)) // Does not diagnose in Swift 3 mode s.requirementTuple(a, b) // Does not diagnose in Swift 3 mode s.requirementTuple((a, b)) let sTwo = GenericConforms<(Double, Double)>() sTwo.requirement(a, b) sTwo.requirement((a, b)) sTwo.requirement(d) } do { var s = GenericConforms<Double>() var a = 3.0 var b = 4.0 var c = (3.0) var d = (a, b) s.requirement(a) s.requirement((a)) s.requirement(c) s.requirementTwo(a, b) s.requirementTwo((a, b)) // expected-error {{missing argument for parameter #2 in call}} s.requirementTuple(a, b) // expected-error {{extra argument in call}} s.requirementTuple((a, b)) var sTwo = GenericConforms<(Double, Double)>() sTwo.requirement(a, b) // expected-error {{extra argument in call}} sTwo.requirement((a, b)) sTwo.requirement(d) } extension Protocol { func takesClosure(_ fn: (Element) -> ()) {} func takesClosureTwo(_ fn: (Element, Element) -> ()) {} func takesClosureTuple(_ fn: ((Element, Element)) -> ()) {} } do { let s = GenericConforms<Double>() s.takesClosure({ _ = $0 }) s.takesClosure({ x in }) s.takesClosure({ (x: Double) in }) s.takesClosureTwo({ _ = $0 }) s.takesClosureTwo({ x in }) s.takesClosureTwo({ (x: (Double, Double)) in }) s.takesClosureTwo({ _ = $0; _ = $1 }) s.takesClosureTwo({ (x, y) in }) s.takesClosureTwo({ (x: Double, y:Double) in }) s.takesClosureTuple({ _ = $0 }) s.takesClosureTuple({ x in }) s.takesClosureTuple({ (x: (Double, Double)) in }) s.takesClosureTuple({ _ = $0; _ = $1 }) s.takesClosureTuple({ (x, y) in }) s.takesClosureTuple({ (x: Double, y:Double) in }) let sTwo = GenericConforms<(Double, Double)>() sTwo.takesClosure({ _ = $0 }) sTwo.takesClosure({ x in }) sTwo.takesClosure({ (x: (Double, Double)) in }) sTwo.takesClosure({ _ = $0; _ = $1 }) sTwo.takesClosure({ (x, y) in }) sTwo.takesClosure({ (x: Double, y: Double) in }) } do { let _: ((Int, Int)) -> () = { _ = $0 } let _: ((Int, Int)) -> () = { _ = ($0.0, $0.1) } let _: ((Int, Int)) -> () = { t in _ = (t.0, t.1) } let _: ((Int, Int)) -> () = { _ = ($0, $1) } let _: ((Int, Int)) -> () = { t, u in _ = (t, u) } let _: (Int, Int) -> () = { _ = $0 } let _: (Int, Int) -> () = { _ = ($0.0, $0.1) } let _: (Int, Int) -> () = { t in _ = (t.0, t.1) } let _: (Int, Int) -> () = { _ = ($0, $1) } let _: (Int, Int) -> () = { t, u in _ = (t, u) } } // rdar://problem/28952837 - argument labels ignored when calling function // with single 'Any' parameter func takesAny(_: Any) {} enum HasAnyCase { case any(_: Any) } do { let fn: (Any) -> () = { _ in } fn(123) fn(data: 123) takesAny(123) takesAny(data: 123) _ = HasAnyCase.any(123) _ = HasAnyCase.any(data: 123) } // rdar://problem/29739905 - protocol extension methods on Array had // ParenType sugar stripped off the element type typealias BoolPair = (Bool, Bool) func processArrayOfFunctions(f1: [((Bool, Bool)) -> ()], f2: [(Bool, Bool) -> ()], c: Bool) { let p = (c, c) f1.forEach { block in block(p) block((c, c)) block(c, c) } f2.forEach { block in block(p) // expected-error {{passing 2 arguments to a callee as a single tuple value has been removed in Swift 3}} block((c, c)) block(c, c) } f2.forEach { (block: ((Bool, Bool)) -> ()) in block(p) block((c, c)) block(c, c) } f2.forEach { (block: (Bool, Bool) -> ()) in block(p) // expected-error {{passing 2 arguments to a callee as a single tuple value has been removed in Swift 3}} block((c, c)) block(c, c) } } // expected-error@+1 {{cannot create a single-element tuple with an element label}} func singleElementTupleArgument(completion: ((didAdjust: Bool)) -> Void) { // TODO: Error could be improved. // expected-error@+1 {{cannot convert value of type '(didAdjust: Bool)' to expected argument type 'Bool'}} completion((didAdjust: true)) } // SR-4378 -- FIXME -- this should type check, it used to work in Swift 3.0 final public class MutableProperty<Value> { public init(_ initialValue: Value) {} } enum DataSourcePage<T> { case notLoaded } let pages1: MutableProperty<(data: DataSourcePage<Int>, totalCount: Int)> = MutableProperty(( // expected-error@-1 {{cannot convert value of type 'MutableProperty<(data: _, totalCount: Int)>' to specified type 'MutableProperty<(data: DataSourcePage<Int>, totalCount: Int)>'}} data: .notLoaded, totalCount: 0 )) let pages2: MutableProperty<(data: DataSourcePage<Int>, totalCount: Int)> = MutableProperty(( // expected-error@-1 {{cannot convert value of type 'MutableProperty<(data: DataSourcePage<_>, totalCount: Int)>' to specified type 'MutableProperty<(data: DataSourcePage<Int>, totalCount: Int)>'}} data: DataSourcePage.notLoaded, totalCount: 0 )) let pages3: MutableProperty<(data: DataSourcePage<Int>, totalCount: Int)> = MutableProperty(( // expected-error@-1 {{expression type 'MutableProperty<(data: DataSourcePage<Int>, totalCount: Int)>' is ambiguous without more context}} data: DataSourcePage<Int>.notLoaded, totalCount: 0 ))
apache-2.0
huangboju/Moots
UICollectionViewLayout/SwiftSpreadsheet-master/Example/SwiftSpreadsheet/ViewController.swift
1
7718
// // ViewController.swift // SwiftSpreadsheet // // Created by Wojtek Kordylewski on 03/23/2017. // Copyright (c) 2017 Wojtek Kordylewski. All rights reserved. // import UIKit import SwiftSpreadsheet class DefaultCollectionViewCell: UICollectionViewCell { @IBOutlet weak var infoLabel: UILabel! } class SpreadsheetCollectionReusableView: UICollectionReusableView { @IBOutlet weak var infoLabel: UILabel! } class ViewController: UIViewController { let defaultCellIdentifier = "DefaultCellIdentifier" let defaultSupplementaryViewIdentifier = "DefaultSupplementaryViewIdentifier" struct DecorationViewNames { static let topLeft = "SpreadsheetTopLeftDecorationView" static let topRight = "SpreadsheetTopRightDecorationView" static let bottomLeft = "SpreadsheetBottomLeftDecorationView" static let bottomRight = "SpreadsheetBottomRightDecorationView" } struct SupplementaryViewNames { static let left = "SpreadsheetLeftRowView" static let right = "SpreadsheetRightRowView" static let top = "SpreadsheetTopColumnView" static let bottom = "SpreadsheetBottomColumnView" } @IBOutlet weak var collectionView: UICollectionView! let dataArray: [[Double]] let numberFormatter = NumberFormatter() let personCount = 30 let lightGreyColor = UIColor(red: 0.9, green: 0.9, blue: 0.9, alpha: 1) required init?(coder aDecoder: NSCoder) { //Setting up demo data var finalArray = [[Double]]() for _ in 0 ..< self.personCount { var subArray = [Double]() for _ in 0 ..< 12 { subArray.append(Double(arc4random() % 4000)) } finalArray.append(subArray) } self.dataArray = finalArray super.init(coder: aDecoder) } override func viewDidLoad() { super.viewDidLoad() //DecorationView Nibs let topLeftDecorationViewNib = UINib(nibName: DecorationViewNames.topLeft, bundle: nil) let topRightDecorationViewNib = UINib(nibName: DecorationViewNames.topRight, bundle: nil) let bottomLeftDecorationViewNib = UINib(nibName: DecorationViewNames.bottomLeft, bundle: nil) let bottomRightDecorationViewNib = UINib(nibName: DecorationViewNames.bottomRight, bundle: nil) //SupplementaryView Nibs let topSupplementaryViewNib = UINib(nibName: SupplementaryViewNames.top, bundle: nil) let bottomSupplementaryViewNib = UINib(nibName: SupplementaryViewNames.bottom, bundle: nil) let leftSupplementaryViewNib = UINib(nibName: SupplementaryViewNames.left, bundle: nil) let rightSupplementaryViewNib = UINib(nibName: SupplementaryViewNames.right, bundle: nil) //Setup Layout let layout = SpreadsheetLayout(delegate: self, topLeftDecorationViewNib: topLeftDecorationViewNib, topRightDecorationViewNib: topRightDecorationViewNib, bottomLeftDecorationViewNib: bottomLeftDecorationViewNib, bottomRightDecorationViewNib: bottomRightDecorationViewNib) //Default is true, set false here if you do not want some of these sides to remain sticky layout.stickyLeftRowHeader = true layout.stickyRightRowHeader = true layout.stickyTopColumnHeader = true layout.stickyBottomColumnFooter = true self.collectionView.collectionViewLayout = layout //Register Supplementary-Viewnibs for the given ViewKindTypes self.collectionView.register(leftSupplementaryViewNib, forSupplementaryViewOfKind: SpreadsheetLayout.ViewKindType.leftRowHeadline.rawValue, withReuseIdentifier: self.defaultSupplementaryViewIdentifier) self.collectionView.register(rightSupplementaryViewNib, forSupplementaryViewOfKind: SpreadsheetLayout.ViewKindType.rightRowHeadline.rawValue, withReuseIdentifier: self.defaultSupplementaryViewIdentifier) self.collectionView.register(topSupplementaryViewNib, forSupplementaryViewOfKind: SpreadsheetLayout.ViewKindType.topColumnHeader.rawValue, withReuseIdentifier: self.defaultSupplementaryViewIdentifier) self.collectionView.register(bottomSupplementaryViewNib, forSupplementaryViewOfKind: SpreadsheetLayout.ViewKindType.bottomColumnFooter.rawValue, withReuseIdentifier: self.defaultSupplementaryViewIdentifier) } } extension ViewController: UICollectionViewDataSource { func numberOfSections(in collectionView: UICollectionView) -> Int { return self.dataArray.count } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return self.dataArray[section].count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: self.defaultCellIdentifier, for: indexPath) as? DefaultCollectionViewCell else { fatalError("Invalid cell dequeued") } let value = self.dataArray[indexPath.section][indexPath.item] cell.infoLabel.text = self.numberFormatter.string(from: NSNumber(value: value)) cell.backgroundColor = indexPath.item % 2 == 1 ? self.lightGreyColor : UIColor.white return cell } func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView { guard let viewKind = SpreadsheetLayout.ViewKindType(rawValue: kind) else { fatalError("View Kind not available for string: \(kind)") } let supplementaryView = collectionView.dequeueReusableSupplementaryView(ofKind: viewKind.rawValue, withReuseIdentifier: self.defaultSupplementaryViewIdentifier, for: indexPath) as! SpreadsheetCollectionReusableView switch viewKind { case .leftRowHeadline: supplementaryView.infoLabel.text = "Section \(indexPath.section)" case .rightRowHeadline: let value = self.dataArray[indexPath.section].reduce(0) { $0 + $1 } supplementaryView.infoLabel.text = self.numberFormatter.string(from: NSNumber(value: value)) case .topColumnHeader: supplementaryView.infoLabel.text = "Item \(indexPath.item)" supplementaryView.backgroundColor = indexPath.item % 2 == 1 ? self.lightGreyColor : UIColor.white case .bottomColumnFooter: let value = self.dataArray.map { $0[indexPath.item] }.reduce(0) { $0 + $1 } supplementaryView.infoLabel.text = self.numberFormatter.string(from: NSNumber(value: value)) supplementaryView.backgroundColor = indexPath.item % 2 == 1 ? self.lightGreyColor : UIColor.white default: break } return supplementaryView } } //MARK: - Spreadsheet Layout Delegate extension ViewController: SpreadsheetLayoutDelegate { func spreadsheet(layout: SpreadsheetLayout, heightForRowsInSection section: Int) -> CGFloat { return 50 } func widthsOfSideRowsInSpreadsheet(layout: SpreadsheetLayout) -> (left: CGFloat?, right: CGFloat?) { return (120, 120) } func spreadsheet(layout: SpreadsheetLayout, widthForColumnAtIndex index: Int) -> CGFloat { return 80 } func heightsOfHeaderAndFooterColumnsInSpreadsheet(layout: SpreadsheetLayout) -> (headerHeight: CGFloat?, footerHeight: CGFloat?) { return (70, 70) } }
mit
zachmokahn/SUV
Sources/SUV/libUV/Operation/UVFSWrite.swift
1
49
import libUV public let UVFSWrite = uv_fs_write
mit
xxxAIRINxxx/ARNModalTransition
ARNModalTransition/ARNModalTransition/ModalViewController.swift
1
2169
// // ModalViewController.swift // ARNModalTransition // // Created by xxxAIRINxxx on 2015/01/17. // Copyright (c) 2015 xxxAIRINxxx. All rights reserved. // import UIKit class ModalViewController: UIViewController, UITableViewDataSource, UITableViewDelegate { var tapCloseButtonHandler : (ModalViewController -> Void)? var tableView : UITableView = UITableView(frame: CGRectZero, style: .Plain) let cellIdentifier : String = "Cell" deinit { print("deinit ModalViewController") } override func viewDidLoad() { super.viewDidLoad() self.tableView.frame = self.view.bounds self.tableView.dataSource = self self.tableView.delegate = self self.tableView.registerClass(UITableViewCell.classForCoder(), forCellReuseIdentifier: self.cellIdentifier) self.view.addSubview(self.tableView) self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Close", style: .Plain, target: self, action: #selector(ModalViewController.tapCloseButton)) self.navigationItem.rightBarButtonItem?.tintColor = UIColor.whiteColor() } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) print("ModalViewController viewWillAppear") } override func viewWillDisappear(animated: Bool) { super.viewWillDisappear(animated) print("ModalViewController viewWillDisappear") } func tapCloseButton() { self.tapCloseButtonHandler?(self) } // MARK: UITableViewDataSource func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 50 } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier(self.cellIdentifier, forIndexPath: indexPath) return cell } // MARK: UITableViewDelegate func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { tableView.deselectRowAtIndexPath(indexPath, animated: true) } }
mit
jubinjacob19/Catapult
NetworkingDemo/AsyncOperation.swift
1
1822
// // AsyncOperation.swift // NetworkingDemo // // Created by Jubin Jacob on 25/01/16. // Copyright © 2016 J. All rights reserved. // import UIKit infix operator |> { } func |> (operation1: NSOperation, operation2: NSOperation) { operation2.addDependency(operation1) } protocol ChecksReachabliy { var isReachable : Bool {get set} } class AsyncOperation: NSOperation,ChecksReachabliy { var isReachable = true // is reset in the reachablity check operation completion block override var asynchronous: Bool { return true } override init() { } private var _executing: Bool = false override var executing: Bool { get { return _executing } set { if _executing != newValue { willChangeValueForKey("isExecuting") _executing = newValue didChangeValueForKey("isExecuting") } } } private var _finished: Bool = false; override var finished: Bool { get { return _finished } set { if _finished != newValue { willChangeValueForKey("isFinished") _finished = newValue didChangeValueForKey("isFinished") } } } func completeOperation () { executing = false finished = true } override func start() { if cancelled { finished = true return } executing = true main() } override func cancel() { super.cancel() if(executing) { self.completeOperation() } } } extension String { var length: Int { return characters.count } }
mit
paleksandrs/APCoreDataKit
APCoreDataKitTests/NSManagedObjectContextStackSetupTests.swift
1
1829
// // Created by Aleksandrs Proskurins // // License // Copyright © 2016 Aleksandrs Proskurins // Released under an MIT license: http://opensource.org/licenses/MIT // import XCTest @testable import APCoreDataKit import CoreData class NSManagedObjectContextStackSetupTests: XCTestCase { func testManagedObjectContextWithSqlStoreNotNil() { let model = ManagedObjectModel(name: "TestModel", bundle: Bundle(for: type(of: self))) let moc = NSManagedObjectContext(model: model, storeType: PersistentStoreType.SQLite("TestModel")) XCTAssertNotNil(moc) } func testInsertingObjectIntoChildContextIncrementsObjectCountInParent() { let moc = createContextWithPersistentStoreType(PersistentStoreType.InMemory) let child = moc.child() let personsArray = fetchAllPersons(inMOC: moc) _ = child.createAndInsert(entity: Person.self) child.saveContext() let personsArrayAfter = fetchAllPersons(inMOC: moc) XCTAssertEqual(personsArray.count+1, personsArrayAfter.count) } //MARK : Helpers func createContextWithPersistentStoreType(_ type: PersistentStoreType) -> NSManagedObjectContext { let model = ManagedObjectModel(name: "TestModel", bundle: Bundle(for: type(of: self))) return NSManagedObjectContext(model: model, storeType: type) } func fetchAllPersons(inMOC moc: NSManagedObjectContext) -> [Person] { let fetchRequest = Person.entityFetchRequest() var personArray = [Person]() do { personArray = try moc.performFetch(request: fetchRequest) }catch { XCTAssertTrue(false) } return personArray } }
mit
mmrmmlrr/ExamMaster
Pods/ModelsTreeKit/ModelsTreeKit/Classes/Bubble/BubbleNotification.swift
1
1014
// // BubbleNotification.swift // ModelsTreeKit // // Created by aleksey on 27.02.16. // Copyright © 2016 aleksey chernish. All rights reserved. // import Foundation public protocol BubbleNotificationName { static var domain: String { get } var rawValue: String { get } } public func ==(lhs: BubbleNotificationName, rhs: BubbleNotificationName) -> Bool { return lhs.rawValue == rhs.rawValue } public struct BubbleNotification { public var name: BubbleNotificationName public var domain: String { get { return name.dynamicType.domain } } public var object: Any? public var hashValue: Int { return (name.rawValue.hashValue &+ name.rawValue.hashValue).hashValue } public init(name: BubbleNotificationName, object: Any? = nil) { self.name = name self.object = object } } extension BubbleNotification: Hashable, Equatable { } public func ==(a: BubbleNotification, b: BubbleNotification) -> Bool { return a.name == b.name && a.domain == b.domain }
mit
ChernyshenkoTaras/CTValidationTextField
CTValidationTextField/CTValidationTextField/Classes/Validation/Core/ValidationError.swift
1
1120
// // ValidationError.swift // Pods // // Created by Taras Chernyshenko on 3/4/17. // // import Foundation public enum ValidationError: Error { case letters case numbers case symbols([String]) case email case phone case minLength(Int) case maxLength(Int) case notEmpty func message() -> String { switch self { case .letters: return NSLocalizedString("letters", comment: "") case .numbers: return NSLocalizedString("numbers", comment: "") case .symbols(let symbols): return "[\(symbols.joined(separator: ", "))] \(NSLocalizedString("symbols", comment: ""))" case .email: return NSLocalizedString("E-mail", comment: "") case .phone: return NSLocalizedString("Phone", comment: "") case .minLength(let min): return "\(NSLocalizedString("minimum length", comment: "")): (\(min))" case .maxLength(let max): return "\(NSLocalizedString("maximum length", comment: "")): (\(max))" case .notEmpty: return NSLocalizedString("field is required", comment: "") } } }
mit
terflogag/OpenSourceController
Tests/LinuxMain.swift
1
121
import XCTest @testable import OpenSourceControllerTests XCTMain([ testCase(OpenSourceControllerTests.allTests), ])
mit
bluquar/emoji_keyboard
DecisiveEmojiKeyboard/DEKeyboard/EmojiScore.swift
1
6157
// // EmojiScore.swift // DecisiveEmojiKeyboard // // Created by Chris Barker on 11/25/14. // Copyright (c) 2014 Chris Barker. All rights reserved. // import UIKit let allEmojis = Array("😁😂😃😄😅😆😉😊😋😌😍😏😒😓😔😖😘😚😜😝😞😠😡😢😣😤😥😨😩😪😫😭😰😱😲😳😵😷😸😹😺😻😼😽😾😿🙀🙅🙆🙇🙈🙉🙊🙋🙌🙍🙎🙏🚀🚃🚄🚅🚇🚉🚌🚏🚑🚒🚓🚕🚗🚙🚚🚢🚤🚥🚧🚨🚩🚪🚫🚬🚭🚲🚶🚹🚺🚻🚼🚽🚾🛀🅰🅱🅾🅿🆎🆑🆒🆓🆔🆕🆖🆗🆘🆙🆚🇩🇪🇬🇧🇨🇳🇯🇵🇰🇷🇫🇷🇪🇸🇮🇹🇺🇸🇷🇺🈁🈂🈚🈯🈲🈳🈴🈵🈶🈷🈸🈹🈺🉐🉑🀄🃏🌀🌁🌂🌃🌄🌅🌆🌇🌈🌉🌊🌋🌌🌏🌑🌓🌔🌕🌙🌛🌟🌠🌰🌱🌴🌵🌷🌸🌹🌺🌻🌼🌽🌾🌿🍀🍁🍂🍃🍄🍅🍆🍇🍈🍉🍊🍌🍍🍎🍏🍑🍒🍓🍔🍕🍖🍗🍘🍙🍚🍛🍜🍝🍞🍟🍠🍡🍢🍣🍤🍥🍦🍧🍨🍩🍪🍫🍬🍭🍮🍯🍰🍱🍲🍳🍴🍵🍶🍷🍸🍹🍺🍻🎀🎁🎂🎃🎄🎅🎆🎇🎈🎉🎊🎋🎌🎍🎎🎏🎐🎑🎒🎓🎠🎡🎢🎣🎤🎥🎦🎧🎨🎩🎪🎫🎬🎭🎮🎯🎰🎱🎲🎳🎴🎵🎶🎷🎸🎹🎺🎻🎼🎽🎾🎿🏀🏁🏂🏃🏄🏆🏈🏊🏠🏡🏢🏣🏥🏦🏧🏨🏩🏪🏫🏬🏭🏮🏯🏰🐌🐍🐎🐑🐒🐔🐗🐘🐙🐚🐛🐜🐝🐞🐟🐠🐡🐢🐣🐤🐥🐦🐧🐨🐩🐫🐬🐭🐮🐯🐰🐱🐲🐳🐴🐵🐶🐷🐸🐹🐺🐻🐼🐽🐾👀👂👃👄👅👆👇👈👉👊👋👌👍👎👏👐👑👒👓👔👕👖👗👘👙👚👛👜👝👞👟👠👡👢👣👤👦👧👨👩👪👫👮👯👰👱👲👳👴👵👶👷👸👹👺👻👼👽👾👿💀💁💂💃💄💅💆💇💈💉💊💋💌💍💎💏💐💑💒💓💔💕💖💗💘💙💚💛💜💝💞💟💠💡💢💣💤💥💦💧💨💩💪💫💬💮💯💰💱💲💳💴💵💸💹💺💻💼💽💾💿📀📁📂📃📄📅📆📇📈📉📊📋📌📍📎📏📐📑📒📓📔📕📖📗📘📙📚📛📜📝📞📟📠📡📢📣📤📥📦📧📨📩📪📫📮📰📱📲📳📴📶📷📹📺📻📼🔃🔊🔋🔌🔍🔎🔏🔐🔑🔒🔓🔔🔖🔗🔘🔙🔚🔛🔜🔝🔞🔟🔠🔡🔢🔣🔤🔥🔦🔧🔨🔩🔪🔫🔮🔯🔰🔱🔲🔳🔴🔵🔶🔷🔸🔹🔺🔻🔼🔽🕐🕑🕒🕓🕔🕕🕖🕗🕘🕙🕚🕛🗻🗼🗽🗾🗿😀😇😈😎😐😑😕😗😙😛😟😦😧😬😮😯😴😶🚁🚂🚆🚈🚊🚍🚎🚐🚔🚖🚘🚛🚜🚝🚞🚟🚠🚡🚣🚦🚮🚯🚰🚱🚳🚴🚵🚷🚸🚿🛁🛂🛃🛄🛅🌍🌎🌐🌒🌖🌗🌘🌚🌜🌝🌞🌲🌳🍋🍐🍼🏇🏉🏤🐀🐁🐂🐃🐄🐅🐆🐇🐈🐉🐊🐋🐏🐐🐓🐕🐖🐪👥👬👭💭💶💷📬📭📯📵🔀🔁🔂🔄🔅🔆🔇🔉🔕🔬🔭🕜🕝🕞🕟🕠🕡🕢🕣🕤🕥🕦🕧") func randomEmoji() -> String { let index: Int = Int(arc4random_uniform(UInt32(allEmojis.count))) return String(allEmojis[index]) } class EmojiScore: NSObject { var mapping: Dictionary<String, Int> var best: String override init() { self.mapping = [:] self.best = "" super.init() self.updateBest() } convenience init(mapping: [String: Int]) { self.init() self.mapping = mapping self.updateBest() } convenience init(emojis: String) { var map: [String: Int] = [:] let emojiArray = Array(emojis) for emojiChar in emojiArray { let emoji = String(emojiChar) let idx = map.indexForKey(emoji) if (idx == nil) { map[emoji] = 1 } else { map[emoji] = 1 + map[emoji]! } } self.init(mapping: map) } func updateBest() -> Void { // O(n) update. Use sparingly! var maxRating: Int = -1 var maxEmoji: String = "" for (emoji, rating) in self.mapping { if (maxRating < rating || maxEmoji == "") { maxEmoji = emoji maxRating = rating } } if maxRating < 0 { maxEmoji = randomEmoji() } self.best = maxEmoji } func updateBest(challenger: String) -> Void { // O(1) update. Only compares the current maximum and the argument. let bestScore: Int = self.score(self.best) let challengeScore: Int = self.score(challenger) if (challengeScore >= bestScore) { self.best = challenger } } func add(other: EmojiScore) -> Void { for (emoji, score) in other.mapping { self.alter(emoji, delta: score) } } func dot(other: EmojiScore) -> Int { var accum: Int = 0 if (self.mapping.count > other.mapping.count) { for (emoji, score) in other.mapping { accum += score * self.score(emoji) } } else { for (emoji, score) in self.mapping { accum += score * other.score(emoji) } } return accum } func score(emoji: String) -> Int { let idx = self.mapping.indexForKey(emoji) if (idx == nil) { return 0 } else { return self.mapping[emoji]! } } func removeBest() -> String { self.mapping[self.best] = -1 self.updateBest() return self.best } func alter(emoji: String, delta: Int) { // Alters the score for a single emoji // Updates .best if necessary if delta != 0 { var newScore: Int = self.score(emoji) + delta if (newScore == 0) { self.mapping.removeValueForKey(emoji) } else { self.mapping[emoji] = newScore } self.updateBest(emoji) } } }
gpl-2.0
huonw/swift
test/SILGen/conditionally_unreachable.swift
3
1607
// RUN: %target-swift-emit-silgen -enable-sil-ownership -parse-stdlib -primary-file %s | %FileCheck %s -check-prefix=RAW // RUN: %target-swift-emit-sil -enable-sil-ownership -assert-config Debug -parse-stdlib -primary-file %s | %FileCheck -check-prefix=DEBUG %s // RUN: %target-swift-emit-sil -enable-sil-ownership -O -assert-config Debug -parse-stdlib -primary-file %s | %FileCheck -check-prefix=DEBUG %s // RUN: %target-swift-emit-sil -enable-sil-ownership -assert-config Release -parse-stdlib -primary-file %s | %FileCheck -check-prefix=RELEASE %s // RUN: %target-swift-emit-sil -enable-sil-ownership -O -assert-config Release -parse-stdlib -primary-file %s | %FileCheck -check-prefix=RELEASE %s import Swift @_silgen_name("foo") func foo() func condUnreachable() { if Int32(Builtin.assert_configuration()) == 0 { foo() } else { Builtin.conditionallyUnreachable() } } // RAW-LABEL: sil hidden @$S25conditionally_unreachable15condUnreachableyyF // RAW: cond_br {{%.*}}, [[YEA:bb[0-9]+]], [[NAY:bb[0-9]+]] // RAW: [[YEA]]: // RAW: function_ref @foo // RAW: [[NAY]]: // RAW: builtin "conditionallyUnreachable" // DEBUG-LABEL: sil hidden @$S25conditionally_unreachable15condUnreachableyyF // DEBUG-NOT: cond_br // DEBUG: function_ref @foo // DEBUG-NOT: {{ unreachable}} // DEBUG: return // RELEASE-LABEL: sil hidden @$S25conditionally_unreachable15condUnreachableyyF // RELEASE-NOT: cond_br // RELEASE-NOT: function_ref @foo // RELEASE-NOT: return // RELEASE-NOT: builtin // RELEASE: {{ unreachable}}
apache-2.0
noppoMan/aws-sdk-swift
Sources/Soto/Services/Translate/Translate_Paginator.swift
1
5973
//===----------------------------------------------------------------------===// // // This source file is part of the Soto for AWS open source project // // Copyright (c) 2017-2020 the Soto project authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information // See CONTRIBUTORS.txt for the list of Soto project authors // // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// // THIS FILE IS AUTOMATICALLY GENERATED by https://github.com/soto-project/soto/tree/main/CodeGenerator. DO NOT EDIT. import SotoCore // MARK: Paginators extension Translate { /// Provides a list of custom terminologies associated with your account. /// /// Provide paginated results to closure `onPage` for it to combine them into one result. /// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`. /// /// Parameters: /// - input: Input for request /// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called. /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned /// along with a boolean indicating if the paginate operation should continue. public func listTerminologiesPaginator<Result>( _ input: ListTerminologiesRequest, _ initialValue: Result, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (Result, ListTerminologiesResponse, EventLoop) -> EventLoopFuture<(Bool, Result)> ) -> EventLoopFuture<Result> { return client.paginate( input: input, initialValue: initialValue, command: listTerminologies, tokenKey: \ListTerminologiesResponse.nextToken, on: eventLoop, onPage: onPage ) } /// Provide paginated results to closure `onPage`. /// /// - Parameters: /// - input: Input for request /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue. public func listTerminologiesPaginator( _ input: ListTerminologiesRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (ListTerminologiesResponse, EventLoop) -> EventLoopFuture<Bool> ) -> EventLoopFuture<Void> { return client.paginate( input: input, command: listTerminologies, tokenKey: \ListTerminologiesResponse.nextToken, on: eventLoop, onPage: onPage ) } /// Gets a list of the batch translation jobs that you have submitted. /// /// Provide paginated results to closure `onPage` for it to combine them into one result. /// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`. /// /// Parameters: /// - input: Input for request /// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called. /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned /// along with a boolean indicating if the paginate operation should continue. public func listTextTranslationJobsPaginator<Result>( _ input: ListTextTranslationJobsRequest, _ initialValue: Result, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (Result, ListTextTranslationJobsResponse, EventLoop) -> EventLoopFuture<(Bool, Result)> ) -> EventLoopFuture<Result> { return client.paginate( input: input, initialValue: initialValue, command: listTextTranslationJobs, tokenKey: \ListTextTranslationJobsResponse.nextToken, on: eventLoop, onPage: onPage ) } /// Provide paginated results to closure `onPage`. /// /// - Parameters: /// - input: Input for request /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue. public func listTextTranslationJobsPaginator( _ input: ListTextTranslationJobsRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (ListTextTranslationJobsResponse, EventLoop) -> EventLoopFuture<Bool> ) -> EventLoopFuture<Void> { return client.paginate( input: input, command: listTextTranslationJobs, tokenKey: \ListTextTranslationJobsResponse.nextToken, on: eventLoop, onPage: onPage ) } } extension Translate.ListTerminologiesRequest: AWSPaginateToken { public func usingPaginationToken(_ token: String) -> Translate.ListTerminologiesRequest { return .init( maxResults: self.maxResults, nextToken: token ) } } extension Translate.ListTextTranslationJobsRequest: AWSPaginateToken { public func usingPaginationToken(_ token: String) -> Translate.ListTextTranslationJobsRequest { return .init( filter: self.filter, maxResults: self.maxResults, nextToken: token ) } }
apache-2.0
TouchInstinct/LeadKit
Sources/Extensions/DataLoading/PaginationDataLoading/UICollectionView+BackgroundViewHolder.swift
1
1215
// // Copyright (c) 2018 Touch Instinct // // 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.UICollectionView extension UICollectionView: BackgroundViewHolder { }
apache-2.0
tonystone/coherence
Tests/ContainerTests/BackgroundContextTests.swift
1
1615
// // BackgroundContextTests.swift // Coherence // // Created by Tony Stone on 4/2/17. // Copyright © 2017 Tony Stone. All rights reserved. // import Foundation import XCTest import CoreData @testable import Coherence class BackgroundContextTests: XCTestCase { func testInitWithConcurrencyType() { let input = NSManagedObjectContextConcurrencyType.privateQueueConcurrencyType XCTAssertNotNil(BackgroundContext(concurrencyType: input)) } func testInitWithCoder() { let input = BackgroundContext(concurrencyType: NSManagedObjectContextConcurrencyType.privateQueueConcurrencyType) let archive = NSKeyedArchiver.archivedData(withRootObject: input) let result = NSKeyedUnarchiver.unarchiveObject(with: archive) XCTAssertTrue(result is BackgroundContext) } func testDeinitBlock() { var input: BackgroundContext? = BackgroundContext(concurrencyType: NSManagedObjectContextConcurrencyType.privateQueueConcurrencyType) let expectation = self.expectation(description: "Deinit called") input?.deinitBlock = { [weak expectation] in expectation?.fulfill() } /// Release the variable so deinit gets called. input = nil self.waitForExpectations(timeout: 5) } func testDeinitBlockNil() { /// /// This simply forces the deinit to be executed with a nil deinitBlock to exercise that code path. /// let _ = BackgroundContext(concurrencyType: NSManagedObjectContextConcurrencyType.privateQueueConcurrencyType) sleep(1) } }
apache-2.0
CPRTeam/CCIP-iOS
OPass/Tabs/MoreTab/TelegramController.swift
1
516
// // TelegramController.swift // OPass // // Created by 腹黒い茶 on 2018/11/5. // 2018 OPass. // import Foundation class TelegramController: OPassWebViewController, OPassWebViewIB { @IBOutlet var goReloadButton: UIBarButtonItem? @IBAction override func reload(_ sender: Any) { super.reload(sender); } var PageUrl: String = "" override func viewWillAppear(_ animated: Bool) { self.PageUrl = Constants.URL_TELEGRAM_GROUP super.viewWillAppear(animated) } }
gpl-3.0
austinzheng/swift
validation-test/compiler_crashers_fixed/00952-swift-constraints-constraintgraph-gatherconstraints.swift
65
643
// This source file is part of the Swift.org open source project // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // RUN: not %target-swift-frontend %s -typecheck class A = a: a<T { } case A.E i> (A? = a protocol B == "a() { } enum A where f..a(a(x) typealias d>(n: A: k.a(" var _ = A.E == b: Int protocol P { struct A { }(b(Any) -> String { if true as Boolean>(i("](B) typealias f : d where H) + seq func d
apache-2.0
benlangmuir/swift
test/IDE/print_attributed_imports.swift
13
675
// RUN: %empty-directory(%t) // RUN: echo 'public func module1() {}' >> %t/module1.swift // RUN: echo 'public func module2() {}' >> %t/module2.swift // RUN: %target-swift-frontend -emit-module -module-name Module1 -o %t %t/module1.swift // RUN: %target-swift-frontend -emit-module -module-name Module2 -o %t %t/module2.swift // RUN: %target-swift-frontend -I %t -emit-module -o %t/AttrImports.swiftmodule %S/print_attributed_imports.swift // RUN: %target-swift-ide-test -I %t -print-module -source-filename %s -module-to-print=AttrImports | %FileCheck %s @_exported import Module1 @_implementationOnly import Module2 // CHECK: import Module1 // CHECK-NOT: import Module2
apache-2.0
1457792186/JWSwift
熊猫TV2/XMTV/Classes/Entertainment/Controller/TableGamesVC.swift
2
525
// // TableGamesVC.swift // XMTV // // Created by Mac on 2017/1/11. // Copyright © 2017年 Mac. All rights reserved. // import UIKit class TableGamesVC: BaseEntertainmentVC { fileprivate lazy var tableGamesVM: TableGamesVM = TableGamesVM() override func viewDidLoad() { super.viewDidLoad() } override func loadData() { baseVM = self.tableGamesVM tableGamesVM.requestData { self.collectionView.reloadData() self.loadDataFinished() } } }
apache-2.0
yagiz/Bagel
mac/Bagel/Components/Details/DetailSections/DataViewController/DataViewModel.swift
1
471
// // DataViewModel.swift // Bagel // // Created by Yagiz Gurgul on 2.10.2018. // Copyright © 2018 Yagiz Lab. All rights reserved. // import Cocoa class DataViewModel: BaseViewModel { var packet: BagelPacket? var dataRepresentation: DataRepresentation? func register() { // } @objc func didSelectPacket() { self.packet = BagelController.shared.selectedProjectController?.selectedDeviceController?.selectedPacket } }
apache-2.0
IdeasOnCanvas/Callisto
Callisto/URLSession+synchronousTask.swift
1
904
// // URLSession+synchronousTask.swift // clangParser // // Created by Patrick Kladek on 21.04.17. // Copyright © 2017 Patrick Kladek. All rights reserved. // import Foundation extension URLSession { func synchronousDataTask(with request: URLRequest) throws -> (data: Data?, response: HTTPURLResponse?) { let semaphore = DispatchSemaphore(value: 0) var responseData: Data? var theResponse: URLResponse? var theError: Error? dataTask(with: request) { (data, response, error) -> Void in responseData = data theResponse = response theError = error semaphore.signal() }.resume() _ = semaphore.wait(timeout: .distantFuture) if let error = theError { throw error } return (data: responseData, response: theResponse as! HTTPURLResponse?) } }
mit
cubixlabs/GIST-Framework
GISTFramework/Classes/Controls/AnimatedTextInput/AnimatedTextView.swift
1
4074
import UIKit final class AnimatedTextView: UITextView { public var textAttributes: [NSAttributedString.Key: Any]? { didSet { guard let attributes = textAttributes else { return } typingAttributes = Dictionary(uniqueKeysWithValues: attributes.lazy.map { ($0.key, $0.value) }) } } public override var font: UIFont? { didSet { var attributes = typingAttributes attributes[NSAttributedString.Key.font] = font textAttributes = Dictionary(uniqueKeysWithValues: attributes.lazy.map { ($0.key, $0.value)}) } } public weak var textInputDelegate: TextInputDelegate? override init(frame: CGRect, textContainer: NSTextContainer?) { super.init(frame: frame, textContainer: textContainer) setup() } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setup() } fileprivate func setup() { contentInset = UIEdgeInsets(top: 0, left: -4, bottom: 0, right: 0) delegate = self } public override func resignFirstResponder() -> Bool { return super.resignFirstResponder() } } extension AnimatedTextView: TextInput { public func configureInputView(newInputView: UIView) { inputView = newInputView } public var currentText: String? { get { return text } set { self.text = newValue } } public var currentSelectedTextRange: UITextRange? { get { return self.selectedTextRange } set { self.selectedTextRange = newValue } } public var currentBeginningOfDocument: UITextPosition? { return self.beginningOfDocument } public var currentKeyboardAppearance: UIKeyboardAppearance { get { return self.keyboardAppearance } set { self.keyboardAppearance = newValue} } public var autocorrection: UITextAutocorrectionType { get { return self.autocorrectionType } set { self.autocorrectionType = newValue } } public var autocapitalization: UITextAutocapitalizationType { get { return self.autocapitalizationType } set { self.autocapitalizationType = newValue } } public func changeReturnKeyType(with newReturnKeyType: UIReturnKeyType) { returnKeyType = newReturnKeyType } public func currentPosition(from: UITextPosition, offset: Int) -> UITextPosition? { return position(from: from, offset: offset) } public func changeClearButtonMode(with newClearButtonMode: UITextField.ViewMode) {} public func updateData(_ data: Any?) { // DO WHAT SO EVER } //F.E. } extension AnimatedTextView: UITextViewDelegate { public func textViewDidBeginEditing(_ textView: UITextView) { textInputDelegate?.textInputDidBeginEditing(textInput: self) } public func textViewDidEndEditing(_ textView: UITextView) { textInputDelegate?.textInputDidEndEditing(textInput: self) } public func textViewDidChange(_ textView: UITextView) { let range = textView.selectedRange textView.attributedText = NSAttributedString(string: textView.text, attributes: textAttributes) textView.selectedRange = range textInputDelegate?.textInputDidChange(textInput: self) } public func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool { if text == "\n" { return textInputDelegate?.textInputShouldReturn(textInput: self) ?? true } return textInputDelegate?.textInput(textInput: self, shouldChangeCharactersIn: range, replacementString: text) ?? true } public func textViewShouldBeginEditing(_ textView: UITextView) -> Bool { return textInputDelegate?.textInputShouldBeginEditing(textInput: self) ?? true } public func textViewShouldEndEditing(_ textView: UITextView) -> Bool { return textInputDelegate?.textInputShouldEndEditing(textInput: self) ?? true } }
agpl-3.0
itsaboutcode/WordPress-iOS
WordPress/Jetpack/AppConfiguration.swift
1
670
import Foundation /** * Jetpack Configuration */ @objc class AppConfiguration: NSObject { @objc static let isJetpack: Bool = true @objc static let allowsNewPostShortcut: Bool = false @objc static let allowsConnectSite: Bool = false @objc static let allowSiteCreation: Bool = false @objc static let allowSignUp: Bool = false @objc static let allowsCustomAppIcons: Bool = false @objc static let showsReader: Bool = false @objc static let showsCreateButton: Bool = false @objc static let showsQuickActions: Bool = false @objc static let showsFollowedSitesSettings: Bool = false @objc static let showsWhatIsNew: Bool = false }
gpl-2.0
itsaboutcode/WordPress-iOS
WordPress/Classes/ViewRelated/Gutenberg/GutenbergViewController+Localization.swift
1
1115
import Foundation extension GutenbergViewController { enum Localization { static let fileName = "Localizable" } func parseGutenbergTranslations(in bundle: Bundle = Bundle.main) -> [String: [String]]? { guard let fileURL = bundle.url( forResource: Localization.fileName, withExtension: "strings", subdirectory: nil, localization: currentLProjFolderName() ) else { return nil } if let dictionary = NSDictionary(contentsOf: fileURL) as? [String: String] { var resultDict: [String: [String]] = [:] for (key, value) in dictionary { resultDict[key] = [value] } return resultDict } return nil } private func currentLProjFolderName() -> String? { var lProjFolderName = Locale.current.identifier if let identifierWithoutRegion = Locale.current.identifier.split(separator: "_").first { lProjFolderName = String(identifierWithoutRegion) } return lProjFolderName } }
gpl-2.0
AhmettKeskin/InteractivePlayerView
InteractivePlayerView/AppDelegate.swift
1
2175
// // AppDelegate.swift // InteractivePlayerView // // Created by AhmetKeskin on 02/09/15. // Copyright (c) 2015 Mobiwise. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? private func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> 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 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
mmllr/CleanTweeter
CleanTweeter/UseCases/TweetList/UI/View/iOS/CircularImageView.swift
1
765
// // CircularImageView.swift // CleanTweeter // // Created by Markus Müller on 04.01.16. // Copyright © 2016 Markus Müller. All rights reserved. // import UIKit @IBDesignable class CircularImageView: UIView { @IBInspectable var image: UIImage? { didSet { self.layer.masksToBounds = true; self.layer.contents = image?.cgImage self.layer.contentsGravity = CALayerContentsGravity.resizeAspectFill } } override var frame: CGRect { didSet { layer.cornerRadius = frame.width/2 layer.masksToBounds = layer.cornerRadius > 0 } } @IBInspectable var borderWidth: CGFloat = 0 { didSet { layer.borderWidth = borderWidth } } @IBInspectable var borderColor: UIColor? { didSet { layer.borderColor = borderColor?.cgColor } } }
mit
austinzheng/swift
validation-test/compiler_crashers_fixed/00923-swift-typebase-getcanonicaltype.swift
65
554
// This source file is part of the Swift.org open source project // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // RUN: not %target-swift-frontend %s -typecheck func f<H : T) -> { protocol P { protocol a { typealias e : e where I.R enum A { class C> { class A { struct Q<T! { } extension NSSet { } } } } } } var e: P
apache-2.0
mightydeveloper/swift
test/1_stdlib/Bit.swift
10
901
//===--- Bit.swift --------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // RUN: %target-run-simple-swift | FileCheck %s // REQUIRES: executable_test let zero: Bit = .Zero let one: Bit = .One // CHECK: testing print("testing") // CHECK-NEXT: 1 print((one - zero).rawValue) // CHECK-NEXT: 1 print(zero.successor().rawValue) // CHECK-NEXT: 0 print(one.predecessor().rawValue) // CHECK-NEXT: 0 print((one &+ one).rawValue) // CHECK: done. print("done.")
apache-2.0
bangslosan/SwiftColors
SwiftColorsExamplesTests/SwiftColorsTests.swift
8
3145
// // SwiftColorsTests.swift // SwiftColorsExamples // // Created by Evgen Dubinin on 12/16/14. // // #if os(iOS) import UIKit #else import Cocoa #endif import XCTest class SwiftColorsTests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } // is alpha equals to 1 by default after init func testAlphaInHexStringInit() { let hexBlackColor = SWColor(hexString: "000000") XCTAssertNotNil(hexBlackColor) var white: CGFloat = 0.0 var alpha: CGFloat = 0.0 hexBlackColor!.getWhite(&white, alpha: &alpha) let expectedAlpha: CGFloat = 1.0 XCTAssertEqual(alpha, expectedAlpha) } func testAlphaInHexStringAlphaInit() { let hexBlackColor = SWColor(hexString: "000000", alpha: 0.5) XCTAssertNotNil(hexBlackColor) var white: CGFloat = 0.0 var alpha: CGFloat = 0.0 hexBlackColor!.getWhite(&white, alpha: &alpha) let expectedAlpha: CGFloat = 0.5 XCTAssertEqual(alpha, expectedAlpha) } func testBlackColor() { let hexBlackColor = SWColor(hexString: "000000") XCTAssertNotNil(hexBlackColor) let blackColor = SWColor(red: 0.0, green: 0.0, blue: 0.0, alpha: 1.0) XCTAssertEqual(hexBlackColor!, blackColor, "Black color mismatch") } // test how Apple might create the black color func testBlackColorAppleWay() { let blackColor1 = SWColor.blackColor() let blackColor2 = SWColor(white: 0.0, alpha: 1.0) XCTAssertEqual(blackColor1, blackColor2) } // does # result in correct color func testHashColorString() { let hexWhiteColor = SWColor(hexString: "#FFFFFF") XCTAssertNotNil(hexWhiteColor) let whiteColor = SWColor(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0) XCTAssertEqual(hexWhiteColor!, whiteColor) } // does string w/ # and w/o # results in same color func testWithAndWithoutHash() { let colorWithHash = SWColor(hexString: "#490d87") XCTAssertNotNil(colorWithHash) let colorWithoutHash = SWColor(hexString: "490d87") XCTAssertNotNil(colorWithoutHash) XCTAssertEqual(colorWithHash!, colorWithoutHash!) } func testIncorrectFormatString() { let wrongColor01 = SWColor(hexString: "#incorrect") XCTAssertNil(wrongColor01) let wrongColor02 = SWColor(hexString: "GGGGGG") XCTAssertNil(wrongColor02) let wrongColor03 = SWColor(hexString: "-FFFFFF") XCTAssertNil(wrongColor03) let wrongColor04 = SWColor(hexString: "#FFFFF") XCTAssertNil(wrongColor04) let wrongColor05 = SWColor(hexString: "#GGG") XCTAssertNil(wrongColor05) let wrongColor06 = SWColor(hexString: "HHH") XCTAssertNil(wrongColor06) } }
mit
EgeTart/MedicineDMW
DWM/EnterpriseHeaderView.swift
1
870
// // EnterpriseHeaderView.swift // DWM // // Created by MacBook on 9/26/15. // Copyright © 2015 EgeTart. All rights reserved. // import UIKit class EnterpriseHeaderView: UITableViewHeaderFooterView { /* // Only override drawRect: if you perform custom drawing. // An empty implementation adversely affects performance during animation. override func drawRect(rect: CGRect) { // Drawing code } */ @IBOutlet weak var controlButton: UIButton! required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) let grayLine = UIView(frame: CGRect(x: 15, y: 43, width: UIScreen.mainScreen().bounds.width - 31, height: 0.3)) grayLine.backgroundColor = UIColor(red: 204 / 255.0, green: 204.0 / 255.0, blue: 204.0 / 255.0, alpha: 1.0) self.addSubview(grayLine) } }
mit
bryx-inc/BRYXStackView
Pod/Classes/StackView.swift
1
10964
// Copyright (c) 2015 Bryx, Inc. <harlan@bryx.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 UIKit /// A struct for holding references to views and their corresponding insets. private struct ViewBox { let view: UIView let edgeInsets: UIEdgeInsets } /// The StackView class provides a streamlined interface for /// laying out a collection of views in a column. /// StackView takes advantage of Auto Layout to make sure its /// views size appropriately on all devices and orientations. @availability(iOS, introduced=7.0) public class StackView: UIView { /// Holds a reference to the constraints placed on the /// views in the stack. /// /// When a new view is added, these constraints are /// removed from the StackView and re-generated. private var stackConstraints = [NSLayoutConstraint]() /// Holds all the stacked views and their corresponding /// edge insets so the constraints can be re-generated. private var viewBoxes = [ViewBox]() /// Tells whether or not we are currently batching updates. /// If this proerty is true, then updateConstraints will only /// call the superview's method. private var isBatchingUpdates = false public init() { super.init(frame: CGRectZero) self.setTranslatesAutoresizingMaskIntoConstraints(false) } required public init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } /// Removes all subviews from the StackView, /// and all associated constraints. @availability(iOS, introduced=7.0) public func removeAllSubviews() { self.batchUpdates({ for subview in self.subviews { subview.removeFromSuperview() } self.stackConstraints.removeAll(keepCapacity: true) self.viewBoxes.removeAll(keepCapacity: true) }) } /// Batches updates of views, and calls completion when finished. /// Use this when you have many views to add, and only want to update /// the constraints when all views have been added. /// /// :param: updates The updates (view insertions or removals) /// :param: completion An optional block to call once the updates have /// finished and the constraints have been updated. /// /// :note: This method is safe to call inside an existing batch update. public func batchUpdates(updates: () -> (), completion: (() -> ())? = nil) { if self.isBatchingUpdates { // If we're already batching updates, don't modify the isBatchingUpdates // value. Instead, just call the updates. updates() } else { self.isBatchingUpdates = true updates() self.isBatchingUpdates = false self.setNeedsUpdateConstraints() self.updateConstraintsIfNeeded() } completion?() } /// If the view hierarchy has changed, and the StackView is not batching updates, /// this method recomputes the constraints needed to represent the stacked views /// with all of their edge insets. override public func updateConstraints() { if self.stackConstraints.isEmpty && !self.isBatchingUpdates { var affectedBoxes = [ViewBox]() for box in self.viewBoxes { if box.view.hidden { continue } // Horizontally constrain the new view with respect to the edge insets. var views = ["view": box.view] let horizontal = NSLayoutConstraint.constraintsWithVisualFormat( "H:|-(\(box.edgeInsets.left))-[view]-(\(box.edgeInsets.right))-|", options: .DirectionLeadingToTrailing, metrics: nil, views: views ) as! [NSLayoutConstraint] self.addConstraints(horizontal) self.stackConstraints += horizontal // If there isn't an existing view in the stack, we'll need // to vertically constrain with respect to the superview, // so use `|`. Otherwise, if we have a previously-added view, // constrain vertically to that view and let parent: String var topInset = box.edgeInsets.top if let last = affectedBoxes.last { parent = "[parent]" views["parent"] = last.view // Add the previous view's 'bottom' to this view's // 'top'. topInset += last.edgeInsets.bottom } else { parent = "|" } // Vertically constrain the new view with respect to the edge insets. // Also add the bottom from the previous view's edge insets. let vertical = NSLayoutConstraint.constraintsWithVisualFormat( "V:\(parent)-(\(topInset))-[view]", options: .DirectionLeadingToTrailing, metrics: nil, views: views ) as! [NSLayoutConstraint] self.addConstraints(vertical) self.stackConstraints += vertical affectedBoxes.append(box) } if let box = affectedBoxes.last { // Reset the lastViewConstraints to the constraints on this new view. let lastConstraints = NSLayoutConstraint.constraintsWithVisualFormat( "V:[view]-(\(box.edgeInsets.bottom))-|", options: .DirectionLeadingToTrailing, metrics: nil, views: ["view": box.view] ) as! [NSLayoutConstraint] self.addConstraints(lastConstraints) self.stackConstraints += lastConstraints } } super.updateConstraints() } /// Adds a subview to the StackView with associated edge insets. /// StackView will attempt to create constraints such that the view has /// padding around it that matches the provided insets. /// /// :param: view The view to add. /// :param: edgeInsets A UIEdgeInsets struct containing top and bottom insets /// that the view should respect within the stack. public func addSubview(view: UIView, withEdgeInsets edgeInsets: UIEdgeInsets) { // Remove the constraints on the view. super.addSubview(view) view.setTranslatesAutoresizingMaskIntoConstraints(false) self.viewBoxes.append(ViewBox(view: view, edgeInsets: edgeInsets)) self.invalidateConstraints() } /// Inserts a subview at the provided index in the stack. Also re-orders the views /// in the stack such that the new order is respected. /// /// :param: view The view to add. /// :param: index The index, vertically, where the view should live in the stack. /// :param: edgeInsets: The insets to apply around the view. public func insertSubview(view: UIView, atIndex index: Int, withEdgeInsets edgeInsets: UIEdgeInsets) { super.insertSubview(view, atIndex: index) view.setTranslatesAutoresizingMaskIntoConstraints(false) self.viewBoxes.insert(ViewBox(view: view, edgeInsets: edgeInsets), atIndex: index) self.invalidateConstraints() } /// Inserts a subview at the provided index in the stack. Also re-orders the views /// in the stack such that the new order is respected. /// /// :param: view The view to add. /// :param: index The index, vertically, where the view should live in the stack. public override func insertSubview(view: UIView, atIndex index: Int) { self.insertSubview(view, atIndex: index, withEdgeInsets: UIEdgeInsetsZero) } /// Re-sets the edge insets associated with a view in the stack, and triggers a layout pass. /// If the view is not found in the stack, this method does nothing. /// /// :param: insets The new insets to apply to the view. /// :param: view The view to update. public func setEdgeInsets(insets: UIEdgeInsets, forView view: UIView) { for (index, box) in enumerate(self.viewBoxes) { if box.view === view { self.viewBoxes[index] = ViewBox(view: view, edgeInsets: insets) self.invalidateConstraints() break } } } /// Adds all of the provided views to the stack with the provided edgeInsets applied to each of them. /// /// :param: views An Array of UIViews to be added to the stack. /// :param: insets UIEdgeInsets to apply around each view. public func addSubviews(views: [UIView], withEdgeInsets edgeInsets: UIEdgeInsets = UIEdgeInsetsZero, completion: (() -> ())? = nil) { self.batchUpdates({ for view in views { self.addSubview(view, withEdgeInsets: edgeInsets) } }, completion: completion) } /// Removes all constraints added by the StackView and tells the /// view to update the constraints if it's not currently batching requests. public func invalidateConstraints() { self.removeConstraints(self.stackConstraints) self.stackConstraints.removeAll(keepCapacity: true) if !self.isBatchingUpdates { self.setNeedsUpdateConstraints() self.updateConstraintsIfNeeded() } } /// Adds a subview to the StackView with associated edge insets. /// StackView will attempt to create constraints such that the view has /// padding around it that matches the provided insets. /// /// :param: view The view to add. override public func addSubview(view: UIView) { self.addSubview(view, withEdgeInsets: UIEdgeInsetsZero) } }
mit
allbto/WayThere
ios/WayThere/Pods/Nimble/Nimble/Adapters/AdapterProtocols.swift
78
452
import Foundation /// Protocol for the assertion handler that Nimble uses for all expectations. public protocol AssertionHandler { func assert(assertion: Bool, message: String, location: SourceLocation) } /// Global backing interface for assertions that Nimble creates. /// Defaults to a private test handler that passes through to XCTest. /// /// @see AssertionHandler public var NimbleAssertionHandler: AssertionHandler = NimbleXCTestHandler()
mit
urbanthings/urbanthings-sdk-apple
UTAPIObjCAdapter/Public/TransitStopScheduledCall.swift
1
1034
// // TransitStopScheduledCall.swift // UrbanThingsAPI // // Created by Mark Woollard on 15/05/2016. // Copyright © 2016 UrbanThings. All rights reserved. // import Foundation import UTAPI /// `TransitStopScheduledCall` details scheduled calls made at a given stop. @objc public protocol TransitStopScheduledCall : NSObjectProtocol { /// The TransitStop at which the vehicle calls. var stop: TransitStop { get } /// The time(s) at which the vehicle is scheduled to call and the type of call. var scheduledCall: TransitScheduledCall { get } } @objc public class UTTransitStopScheduledCall : NSObject, TransitStopScheduledCall { let adapted: UTAPI.TransitStopScheduledCall public init(adapt: UTAPI.TransitStopScheduledCall) { self.adapted = adapt self.stop = UTTransitStop(adapt: adapt.stop) self.scheduledCall = UTTransitScheduledCall(adapt: adapt.scheduledCall) } public let stop: TransitStop public let scheduledCall: TransitScheduledCall }
apache-2.0
kasei/kineo
Tests/KineoTests/SPARQLContentNegotiator.swift
1
5309
import Foundation import XCTest import Kineo import SPARQLSyntax #if os(Linux) extension SPARQLContentNegotiatorTest { static var allTests : [(String, (SPARQLContentNegotiatorTest) -> () throws -> Void)] { return [ ("testSharedConneg", testSharedConneg), ("testExtendedSharedConneg", testExtendedSharedConneg), ] } } #endif class SPARQLContentNegotiatorTest: XCTestCase { var boolResult : QueryResult<[SPARQLResultSolution<Term>], [Triple]>! var triplesResult : QueryResult<[SPARQLResultSolution<Term>], [Triple]>! var bindingsResult : QueryResult<[SPARQLResultSolution<Term>], [Triple]>! override func setUp() { boolResult = QueryResult.boolean(true) triplesResult = QueryResult.triples([]) bindingsResult = QueryResult.bindings(["a"], []) super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testSharedSerializerConneg() { let c = SPARQLContentNegotiator.shared let boolResult : QueryResult<[SPARQLResultSolution<Term>], [Triple]> = QueryResult.boolean(true) let triplesResult : QueryResult<[SPARQLResultSolution<Term>], [Triple]> = QueryResult.triples([]) let bindingsResult : QueryResult<[SPARQLResultSolution<Term>], [Triple]> = QueryResult.bindings(["a"], []) // default serializer for */* XCTAssertEqual(c.negotiateSerializer(for: boolResult, accept: ["*/*"])!.canonicalMediaType, "application/sparql-results+json") XCTAssertEqual(c.negotiateSerializer(for: triplesResult, accept: ["*/*"])!.canonicalMediaType, "application/turtle") XCTAssertEqual(c.negotiateSerializer(for: bindingsResult, accept: ["*/*"])!.canonicalMediaType, "application/sparql-results+json") // default serializer for text/turtle XCTAssertNil(c.negotiateSerializer(for: boolResult, accept: ["text/turtle"])) XCTAssertEqual(c.negotiateSerializer(for: triplesResult, accept: ["text/turtle"])!.canonicalMediaType, "application/turtle") XCTAssertNil(c.negotiateSerializer(for: bindingsResult, accept: ["text/turtle"])) // default serializer for text/tab-separated-values XCTAssertNil(c.negotiateSerializer(for: boolResult, accept: ["text/tab-separated-values"])) XCTAssertNil(c.negotiateSerializer(for: triplesResult, accept: ["text/tab-separated-values"])) XCTAssertEqual(c.negotiateSerializer(for: bindingsResult, accept: ["text/tab-separated-values"])!.canonicalMediaType, "text/tab-separated-values") // serializer for application/n-triples, text/tab-separated-values, application/sparql-results+xml XCTAssertEqual(c.negotiateSerializer(for: boolResult, accept: ["application/n-triples", "text/tab-separated-values", "application/sparql-results+xml"])!.canonicalMediaType, "application/sparql-results+xml") XCTAssertEqual(c.negotiateSerializer(for: triplesResult, accept: ["application/n-triples", "text/tab-separated-values", "application/sparql-results+xml"])!.canonicalMediaType, "application/n-triples") XCTAssertEqual(c.negotiateSerializer(for: bindingsResult, accept: ["application/n-triples", "text/tab-separated-values", "application/sparql-results+xml"])!.canonicalMediaType, "text/tab-separated-values") } func testSharedParserConneg() { let c = SPARQLContentNegotiator.shared let makeResp : (String) -> HTTPURLResponse = { (ct) in return HTTPURLResponse(url: URL(string: "http://example.org/sparql")!, statusCode: 200, httpVersion: "1.1", headerFields: [ "Content-Type": ct ])! } XCTAssertTrue(c.negotiateParser(for: makeResp("application/sparql-results+xml")) is SPARQLXMLParser) XCTAssertTrue(c.negotiateParser(for: makeResp("application/sparql-results+json")) is SPARQLJSONParser) XCTAssertTrue(c.negotiateParser(for: makeResp("application/sparql-results+json;charset=utf-8")) is SPARQLJSONParser) } func testExtendedSharedConneg() { SPARQLContentNegotiator.shared.addSerializer(TestSerializer()) let c = SPARQLContentNegotiator.shared XCTAssertEqual(c.negotiateSerializer(for: boolResult, accept: ["text/html"])!.canonicalMediaType, "x-text/html") XCTAssertEqual(c.negotiateSerializer(for: triplesResult, accept: ["text/html"])!.canonicalMediaType, "x-text/html") XCTAssertEqual(c.negotiateSerializer(for: bindingsResult, accept: ["text/html"])!.canonicalMediaType, "x-text/html") } } struct TestSerializer: SPARQLSerializable { var serializesTriples = true var serializesBindings = true var serializesBoolean = true var canonicalMediaType = "x-text/html" var acceptableMediaTypes = ["text/html", "x-text/html"] func serialize<R, T>(_ results: QueryResult<R, T>) throws -> Data where R : Sequence, T : Sequence, R.Element == SPARQLResultSolution<Term>, T.Element == Triple { return "<html><h1>Hello!</h1></html>".data(using: .utf8)! } }
mit
weissi/swift-dealing-with-nserror
main.swift
1
1057
import Foundation func catOptionals<T>(xs:[T?]) -> [T] { var ys : [T] = [] for mx in xs { if let x = mx { ys.append(x) } } return ys } func copyItemAtPath(srcPath:String, toPath:String) -> Result<()> { return resultifyNSErrorReturningFunction { (outError:NSErrorPointer) in return NSFileManager.defaultManager().copyItemAtPath(srcPath, toPath: toPath, error:outError) ? () : nil } } func contentsOfDirectoryAtPath(dir:String) -> Result<[String]> { return resultifyNSErrorReturningFunction { (outError:NSErrorPointer) -> [String]? in switch NSFileManager.defaultManager().contentsOfDirectoryAtPath(dir, error:outError)?.map({ $0 as? String }) { case .Some(let files): return catOptionals(files) case .None: return nil } } } println("--> This should succeed:") println(contentsOfDirectoryAtPath("/tmp")) println() println("--> This should fail:") println(contentsOfDirectoryAtPath("/dev/null/this/does/not/exist"))
bsd-2-clause
SwiftStudies/OysterKit
Sources/ExampleLanguages/STLR Testing Extensions.swift
1
1460
// Copyright (c) 2018, RED When Excited // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import Foundation typealias TestSTLR = STLR
bsd-2-clause
CoderJChen/SWWB
CJWB/CJWB/Classes/Compose/picPicker/CJPicPickerViewCell.swift
1
1339
// // CJPicPickerViewCell.swift // CJWB // // Created by 星驿ios on 2017/9/13. // Copyright © 2017年 CJ. All rights reserved. // import UIKit class CJPicPickerViewCell: UICollectionViewCell { //MARK:- 控件的属性 @IBOutlet weak var addPhotoBtn: UIButton! @IBOutlet weak var removePhotoBtn: UIButton! @IBOutlet weak var imageView: UIImageView! //MARK:- 定义属性 var image : UIImage? { didSet{ if image != nil { imageView.image = image addPhotoBtn.isUserInteractionEnabled = false removePhotoBtn.isHidden = false }else{ imageView.image = nil addPhotoBtn.isUserInteractionEnabled = true removePhotoBtn.isHidden = true } } } //MARK:- 事件监听 @IBAction func addPhotoClick(_ sender: Any) { NotificationCenter.default.post(name: NSNotification.Name(rawValue: PicPickerAddPhotoNote), object: nil) } @IBAction func removePhotoClick(_ sender: UIButton) { NotificationCenter.default.post(name: NSNotification.Name(rawValue:PicPickerRemovePhotoNote), object: imageView.image) } override func awakeFromNib() { super.awakeFromNib() // Initialization code } }
apache-2.0
Brightify/ReactantUI
Sources/Tokenizer/Elements/Implementation/Switch.swift
1
1700
// // Switch.swift // ReactantUI // // Created by Matous Hybl. // Copyright © 2017 Brightify. All rights reserved. // import Foundation #if canImport(UIKit) import UIKit #endif public class Switch: View { public override class var availableProperties: [PropertyDescription] { return Properties.switch.allProperties } public class override func runtimeType() throws -> String { #if os(tvOS) throw TokenizationError.unsupportedElementError(element: Switch.self) #else return "UISwitch" #endif } #if canImport(UIKit) public override func initialize(context: ReactantLiveUIWorker.Context) throws -> UIView { #if os(tvOS) throw TokenizationError.unsupportedElementError(element: Switch.self) #else return UISwitch() #endif } #endif } public class SwitchProperties: ControlProperties { public let isOn: AssignablePropertyDescription<Bool> public let onTintColor: AssignablePropertyDescription<UIColorPropertyType> public let thumbTintColor: AssignablePropertyDescription<UIColorPropertyType> public let onImage: AssignablePropertyDescription<Image> public let offImage: AssignablePropertyDescription<Image> public required init(configuration: Configuration) { isOn = configuration.property(name: "isOn") onTintColor = configuration.property(name: "onTintColor") thumbTintColor = configuration.property(name: "thumbTintColor") onImage = configuration.property(name: "onImage") offImage = configuration.property(name: "offImage") super.init(configuration: configuration) } }
mit
fqhuy/minimind
miniminds/Utils.swift
1
324
// // Utils.swift // minimind // // Created by Phan Quoc Huy on 6/9/17. // Copyright © 2017 Phan Quoc Huy. All rights reserved. // import Foundation import UIKit public extension Array where Element == CGFloat { public var float: [Float] { get { return self.map{ Float($0) } } } }
mit
damienmsdevs/swift-mlibs
wyley-starwarsprofile.swift
1
2737
/* Words to Fill in Mad Lib */ //Let's create the nouns var firstNoun: String var secondNoun: String var thirdNoun: String //And the adjectives var firstPastTenseAdjective: String var secondAdjective: String //And the verbs var firstVerb: String var secondVerb: String var thirdVerb: String var fourthVerb: String //And the adverb var firstAdverb: String //Finally, I'll create some extra variables to spice up the story var firstName: String var firstLastName: String var secondName: String var firstNumber: String var secondNumber: String var firstRelative: String /* Mad Lib Questionnaire */ print("Please enter a noun", terminator: ": ") firstNoun = readLine()! print("Please enter another noun", terminator: ": ") secondNoun = readLine()! print("Please enter one final noun", terminator: ": ") thirdNoun = readLine()! print("Please enter an adjective", terminator: ": ") firstPastTenseAdjective = readLine()! print("Please enter another adjective", terminator: ": ") secondAdjective = readLine()! print("Please enter a verb", terminator: ": ") firstVerb = readLine()! print("Please enter another verb", terminator: ": ") secondVerb = readLine()! print("Please enter another verb", terminator: ": ") thirdVerb = readLine()! print("Please enter one final verb (this is the last verb, we promise)", terminator: ": ") fourthVerb = readLine()! print("Please enter an adverb", terminator: ": ") firstAdverb = readLine()! print("Please enter a name", terminator: ": ") firstName = readLine()! print("Please enter a name", terminator: ": ") firstLastName = readLine()! print("Please enter another name", terminator: ": ") secondName = readLine()! print("Please enter a number", terminator: ": ") firstNumber = readLine()! print("Please enter another number", terminator: ": ") secondNumber = readLine()! print("Please enter a relative's name", terminator: ": ") firstRelative = readLine()! /* Mad Lib Story */ //Before we continue, we'll clear the screen for the player so they don't see anything else. print("\u{001B}[2J") print("Greetings imbeciles. I am Darth \(firstLastName), the most \(firstPastTenseAdjective) \(firstNoun) in the galaxy.\n") print("I have destroyed \(firstNumber) planets using a \(secondNoun)-sized weapon called the Death \(thirdNoun). My reputation for killing \(firstAdverb) is something others \(firstVerb) at when they hear my name.'\n") print("I hate seeing my army \(secondVerb), and the only thing that's worse is when they \(thirdVerb). I have a \(secondAdjective) son that defies me; his name is \(secondName), and he is \(secondNumber) years old.\n") print("I hardly \(fourthVerb), except when someone decides to get in my way.\n") print("By the way, I am your \(firstRelative)!")
apache-2.0
jvesala/teknappi
teknappi/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxAlertViewDelegateProxy.swift
18
771
// // RxAlertViewDelegateProxy.swift // RxCocoa // // Created by Carlos García on 8/7/15. // Copyright (c) 2015 Krunoslav Zaher. All rights reserved. // import UIKit #if !RX_NO_MODULE import RxSwift #endif class RxAlertViewDelegateProxy : DelegateProxy , UIAlertViewDelegate , DelegateProxyType { class func currentDelegateFor(object: AnyObject) -> AnyObject? { let alertView: UIAlertView = castOrFatalError(object) return alertView.delegate } class func setCurrentDelegate(delegate: AnyObject?, toObject object: AnyObject) { let alertView: UIAlertView = castOrFatalError(object) alertView.delegate = castOptionalOrFatalError(delegate) } }
gpl-3.0